美文网首页
浏览器端访问IPFS网络

浏览器端访问IPFS网络

作者: 周宇盛 | 来源:发表于2018-12-20 17:24 被阅读18次

    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())
      })
    })
    

    参考


    1. https://docs.ipfs.io/reference/js/overview/

    2. https://docs.ipfs.io/reference/api/http/

    3. https://github.com/ipfs/js-ipfs

    4. https://js.ipfs.io/

    相关文章

      网友评论

          本文标题:浏览器端访问IPFS网络

          本文链接:https://www.haomeiwen.com/subject/baxukqtx.html