【问题标题】:Conversion of buffer data to blob in NodeJS在 NodeJS 中将缓冲区数据转换为 blob
【发布时间】:2020-08-27 02:00:20
【问题描述】:

例如,我从<Buffer 48 65 79 20 74 68 65 72 65 21> 之类的存储中获取缓冲区数据。我需要将它转换成一个blob。但是,当我尝试执行 toString() 来获取编码文本时,就像浏览器呈现附件的方式一样,我将所有文本都作为 unicode 字符获取。我需要一个可以与 JSON 中的其他参数一起发送到 UI 的 blob,可用于使用 HTML5 FileReader API 进行查看。能否请您帮忙。

我尝试的是下面,其中缓冲区指的是第一行中的数据。

let binBuffer = Buffer.from(buffer,'binary').toString('utf8');

【问题讨论】:

  • 让 binBuffer = new Blob([buffer]);
  • 缓冲区表示什么? @ScottStensland 就像问题第 1 行中的一个或数组说 data:[48,65,79..] 我们在 JSON.stringify(bufferdata) 上得到的?
  • 你真的应该考虑用你的JSON发送二进制数据。做到这一点的唯一方法是 base64 编码,它增加了 33% 的大小开销,大量额外的 CPU 和内存。更不用说,在接收端,您在完成解码步骤时需要内存中的多个副本。最好对二进制数据有单独的 HTTP 请求。如果由于某种原因无法做到这一点,请考虑使用 CBOR 等二进制格式而不是 JSON。

标签: node.js file


【解决方案1】:

如果您需要通过 JSON 传输数据缓冲区,您可以使用基于文本的编码(如十六进制或 base64)对缓冲区进行编码。

例如:

// get the buffer from somewhere
const buff = fs.readFileSync("./test.bin");
// create a JSON string that contains the data in the property "blob"
const json = JSON.stringify({ blob: buff.toString("base64") });

// on another computer:
// retrieve the JSON string somehow
const json = getJsonString();
const parsed = JSON.parse(json);
// retrieve the original buffer of data
const buff = Buffer.from(parsed.blob, "base64");

【讨论】:

    【解决方案2】:

    解决这个问题的方法是创建一个可以在Array Buffers和Node Buffers之间转换的函数。

    Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

    在最近的节点版本中,它只是:

    let buffer = Buffer.from(arraybuffer);
    let arraybuffer = Uint8Array.from(buffer).buffer;
    

    【讨论】:

      猜你喜欢
      • 2023-03-02
      • 2021-04-24
      • 1970-01-01
      • 2016-03-13
      • 2021-10-29
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多