IPFS官方提供了2个js库,方便从浏览器端访问IPFS网络。[1]
- js-ipfs:直接访问IPFS网络,可以运行在浏览器或者本地。
- ipfs-http-client(之前称为js-ipfs-api):功能相比前者更小,不能直接访问IPFS网络,需要借助其他的IPFS节点的HTTP网关
官方推荐使用第二种方法,将IPFS节点放在单独的进程,更加稳定。[1]事实上,js-ipfs将ipfs-http-client包含了进来,当检测到本地在运行IPFS节点,会自动切换成使用ipfs-http-client,通过本地的ipfs节点访问IPFS网络。
ipfs-http-client
如果本地运行IPFS,会提供一系列的HTTP API,用于控制本地运行的IPFS,和调用命令行工具作用一样。[2] ipfs-http-client 对这些API进行了封装,使用更加方便。
var ipfsClient = require('ipfs-http-client')
// connect to ipfs daemon API server
var ipfs = ipfsClient({ host: 'localhost', port: '5001', protocol: 'http' })
上传文件:ipfs.add(data, [options], [callback])
获取文件:ipfs.cat(ipfsPath, [options], [callback])
如果浏览器安装了插件IPFS companion,则不调用ipfs-http-client库就能获得同样的接口,并且安全性更高。
js-ipfs[3][4]
const node = new IPFS()
const data = 'Hello, IPFS'
// once the node is ready
node.once('ready', () => {
// convert your data to a Buffer and add it to IPFS
node.files.add(node.types.Buffer.from(data), (err, files) => {
if (err) return console.error(err)
// 'hash', known as CID, is a string uniquely addressing the data
// and can be used to get it again. 'files' is an array because
// 'add' supports multiple additions, but we only added one entry
console.log(files[0].hash)
})
})
node.once('ready', () => {
node.files.cat('QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A', (err, data) => {
if (err) return console.error(err)
// convert Buffer back to string
console.log(data.toString())
})
})
网友评论