【问题标题】:read CAR file using js-car使用 js-car 读取 CAR 文件
【发布时间】:2022-06-14 22:42:10
【问题描述】:

我在 javascript 中有一个 CAR 文件对象,并希望使用 js-car github 读取它。但我不断收到unexpected end of the file 错误。这是我正在尝试的代码

let arrayBuffer = await files[0].arrayBuffer();
let bytes=new Uint8Array(carFile); 
const reader = await CarReader.fromBytes(bytes) //throws error here
const indexer = await CarIndexer.fromBytes(bytes) //throws error here

这个我也累了

let str = await files[0].stream() 
const reader = await CarReader.fromIterable(files[0].stream()) //throws error here

它们都不起作用。但是,对于同一个文件,此代码可以工作

const inStream = fs.createReadStream('test.car')
const reader = await CarReader.fromIterable(inStream)

我查过,我知道CarReader.fromBytes 需要Unit8Arrey,我确信files[0] 不为空。有谁知道我在这里缺少什么?

【问题讨论】:

    标签: javascript file uint8array


    【解决方案1】:

    对于人们将来可能会遇到类似问题,这是我的解决方案: 我直接使用res.body 并将其转换为async stream 并使用fromIterable 读取它

    async function* streamAsyncIterator(stream) {
      // Get a lock on the stream
      const reader = stream.getReader();
    
      try {
        while (true) {
          // Read from the stream
          const { done, value } = await reader.read();
          // Exit if we're done
          if (done) return;
          // Else yield the chunk
          yield value;
        }
      }
      finally {
        reader.releaseLock();
      }
    }
    
    const info = await w3StorageClient.status(response)
    
        if (info) {
          // Fetch and verify files from web3.storage
          const res = await w3StorageClient.get(response);
          const reader = await CarReader.fromIterable(streamAsyncIterator(res.body))
          // read the list of roots from the header
          const roots = await reader.getRoots()
          // retrieve a block, as a { cid:CID, bytes:UInt8Array } pair from the archive
          const got = await reader.get(roots[0])
          // also possible: for await (const { cid, bytes } of CarIterator.fromIterable(inStream)) { ... }
          let decoded = cbor.decode(got.bytes)
          console.log('Retrieved [%s] from example.car with CID [%s]',
          decoded,
            roots[0].toString())
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 2019-10-01
      • 2011-06-01
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多