如何在 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