在Node.js中从Web流创建blob

2w3kk1z5  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(226)

我试图通过ipfs-car(使用Web流)打包CAR文件,然后将其作为文件发送到请求中,但我不确定如何在WritableStream中流式传输后将其存储在Blob中。
我有一段代码

import { CAREncoderStream, createDirectoryEncoderStream } from 'ipfs-car'
import { WritableStream } from 'node:stream/web'

export const packCAR = async (files) => {
  const blockStream = createDirectoryEncoderStream(files)
  const carEncoderStream = new CAREncoderStream([])
  const outStream = new WritableStream()
  await blockStream.pipeThrough(carEncoderStream).pipeTo(outStream)
  const blob = new Blob(/* what do I put here? */)
}

我还没有找到任何人这样做,我只看到了如何将Blob转换为流,所以帮助将不胜感激:)

lnxxn5zx

lnxxn5zx1#

将WritableStream的内容存储到Blob中。这可以通过将WritableStream转换为ReadableStream,然后将其转换为ArrayBuffer,最后将ArrayBuffer存储到Blob中来完成。

import { CAREncoderStream, createDirectoryEncoderStream } from 'ipfs-car'
import { WritableStream, ReadableStream } from 'node:stream/web'

export const packCAR = async (files) => {
  const blockStream = createDirectoryEncoderStream(files)
  const carEncoderStream = new CAREncoderStream([])
  const chunks = []
  const outStream = new WritableStream({
    write(chunk) {
      chunks.push(chunk)
    },
    close() {
      console.log('Stream is closed.')
    }
  })
  await blockStream.pipeThrough(carEncoderStream).pipeTo(outStream)
  const arrayBuffer = await new Blob(chunks).arrayBuffer()
  const blob = new Blob([arrayBuffer])
  return blob
}

相关问题