如何在 Nodejs 中将流转换为缓冲区
在 Nodejs 中,当处理非文本文件(例如图像)的 IO 操作(例如通过网络传输或从磁盘读取)时,有很大的机会以 stream.Readable
的形式接收内容,并且在我们能够处理内存中的完整数据(例如计算字节大小或图像尺寸)之前,我们需要将 stream
保存到 buffer
中,这里有几种方法。
with for await
to iterate over the async iterable stream
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
with event listener
to listen to data
and event
events from the stream
const chunks = [];
stream.on('data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
const buffer = Buffer.concat(chunks);
});
There is a very good article with more details and information: Understanding Streams in Node.js