首页 新闻资讯 地被苗圃
精通IPFS:IPFS 获取内容之下篇 | BTC
发布日期:2022-10-17 00:38    点击次数:142
在上篇文章《IPFS 获取内容之上篇》中,我们提到调用 streamBytes 函数,根据偏移量、长度及节点的连接数组,获取指定的内容。在获取文件过程中,通过调用 streamBytes 函数来获取整个文件的内容。streamBytes 函数调用完成后返回的 pull 函数生成的 through 流就是我们要读取内容的流,它最终被传递给 IPFS core/components/get-pull-stream.js 中返回的 pull 函数生成的 through 流,而这个流又被同目录下 get.js 文件中 pull-stream 类库中的 asyncMap 流的处理函数转换为完整的缓冲区,从而被最终的应用的所使用,这段程序代码如下:
pull(
  self.getPullStream(ipfsPath, options),
  pull.asyncMap((file, cb) => {
    if (file.content) {
      pull(
        file.content,
        pull.collect((err,
拖车视频 buffers) => {
          if (err) { return cb(err) }
          file.content = Buffer.concat(buffers)
          cb(null, file)
        })
      )
    } else {
      cb(null, file)
    }
  }),
  pull.collect(callback)
)
上篇文章的内容,我们回忆到这里就结束了,下面我们仔细研究 streamBytes 函数及相关的深度遍历是如何实现的。

streamBytes 函数使用了 pull-traverse 类库提供深度优先、广度优先、叶子优先等算法,它的每个算法都返回一个 pull 类库的 through 流,新闻资讯这个流被它后面的流所调用。在这里使用深度优先算法,返回的流被 pull 类库的 map 流所调用,用于获取每一个元素。

深度优先算法的相关代码如下:

var once = exports.once =
function (value) {
  return function (abort, cb) {
    if(abort) return cb(abort)
    if(value != null) {
      var _value = value; value = null
      cb(null, _value)
    } else
      cb(true)
  }
}

var depthFirst = exports.depthFirst = function (start, createStream) {   var reads = [], ended

  reads.unshift(once(start))

  return function next (end, cb) {     if(!reads.length)       return cb(true)     if(ended)       return cb(ended)

    reads[0](end, function (end, data) {       if(end) {         if(end !== true) {           ended = end           reads.shift()

          while(reads.length)             reads.shift()(end, function () {})

          return cb(end)         }

        reads.shift()         return next(null, cb)       }

      reads.unshift(createStream(data))       cb(end, data)     })   } }

streamBytes 函数定义在 file.js 文件中,我们来看下它的内容:
function streamBytes (dag, node, fileSize, offset, length) {
  if (offset === fileSize 


Powered by 北京地球天使环保科技有限公司 @2013-2022 RSS地图 HTML地图

Copyright 站群 © 2013-2022 365建站器 版权所有