我从像这样的存储中获取缓冲区数据<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');
Run Code Online (Sandbox Code Playgroud)
Luc*_*ito 38
Buffer为JavaScriptBlob:首先,Node.jsBlob直到版本v15.7.0和v14.18.0Blob才具有该类,因此如果尚未导入该类,则需要导入该类:
// NOTE: starting from Node.js v18.0.0, the following code is not necessary anymore
// CJS style
const { Blob } = require("buffer");
// ESM style
import { Blob } from "buffer";
Run Code Online (Sandbox Code Playgroud)
注意:在 Node.js v14/v15/v16/v17 中(最后一次检查:截至、 和
v14.19.2)v15.14.0,该类被标记为实验性且不稳定。相反,在 Node.js 中,该类被标记为稳定。v16.14.2v17.9.0Blobv18.x.xBlob
更新 2022-04-25:从Node.js 版本
18.0.0开始,您不必再手动导入该类Blob,而是可以直接在代码中使用它!
一旦Blob类可用,转换本身就非常简单:
const buff = Buffer.from([1, 2, 3]); // Node.js Buffer
const blob = new Blob([buff]); // JavaScript Blob
Run Code Online (Sandbox Code Playgroud)
Buffer通过 JSON 传输 Node.js 的旧答案:如果需要通过 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");
Run Code Online (Sandbox Code Playgroud)