NodeJS中将缓冲数据转换为Blob

23
我从类似于<Buffer 48 65 79 20 74 68 65 72 65 21>这样的存储器中获取缓冲区数据。我需要将其转换为Blob。但是当我尝试使用toString()方法获取编码文本时,就像浏览器呈现附件一样,我得到的是所有文本都被表示为Unicode字符。我需要一个Blob可以与其他JSON参数一起发送到UI,并且可以使用HTML5 FileReader API进行查看。麻烦您了。
我所尝试的方法如下,其中buffer是指第一行中的数据。
let binBuffer = Buffer.from(buffer,'binary').toString('utf8');

1
让binBuffer = 新的 Blob([buffer]); - Scott Stensland
缓冲区表示什么?@ScottStensland,例如问题中第1行中的缓冲区或者像数组数据:[48,65,79..],我们可以通过JSON.stringify(bufferdata)获取它们吗? - Lalitha
2
你应该真正考虑一下不要在JSON中发送二进制数据。唯一的方法是使用base64编码,这会增加33%的大小开销,需要大量额外的CPU和内存。更不用说,在接收端,当你通过解码步骤时,需要在内存中拥有多个副本。最好为二进制数据单独创建一个HTTP请求。如果由于某种原因无法实现此操作,请考虑使用类似CBOR的二进制格式,而不是JSON。 - Brad
2个回答

36

如果您想将Node.js的Buffer转换为JavaScript Blob

首先,Node.js直到版本v15.7.0v14.18.0才有Blob类,所以如果还没有,请导入Blob类:

// 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";

注意:在Node.js v14/v15/v16/v17中(截至v14.19.2v15.14.0v16.14.2v17.9.0),Blob类被标记为实验性的,不稳定。相反,在Node.js v18.x.x中,Blob类被标记为稳定。

更新于2022年4月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

如何通过JSON传输Node.js Buffer的旧回答:

如果您需要通过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");

这段代码非常有用,谢谢。但是人们来到这里是为了进行Buffer->Blob转换,也许我们还可以添加一些关于const blob = new Blob([buffer])的提及? - tokland
1
@tokland 已完成,感谢您的建议。 - Luca Polito

0
这是一个使用SDK v3的更新示例:

加密

const { KMSClient, EncryptCommand } = require("@aws-sdk/client-kms");

const mySecret = 'Something really important goes here';
const client = new KMSClient({region: 'my-region-here'});
const encryptCommand= new EncryptCommand({KeyId: 'my-kms-key-id', Plaintext: Buffer.from(mySecret) });
const encryptionResult = await client.send(encryptCommand);
const cipherText = Buffer.from(encryptionResult.CiphertextBlob).toString('base64')
console.log(cipherText);

解密
const { KMSClient, DecryptCommand } = require("@aws-sdk/client-kms");

const cipherText = 'base64 string from above or another encrypt command';
const client = new KMSClient({region: 'my-region-here'});
const decryptCommand= new DecryptCommand({KeyId: 'my-kms-key-id', CiphertextBlob: Buffer.from(cipherText, 'base64') });
const decryptionResult = await client.send(decryptCommand);
const originalSecret = Buffer.from(decryptionResult.Plaintext).toString();
console.log(originalSecret);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接