我正在使用node进行流测试,我设置了一个程序来使用流读取大文件并再次使用流写入。问题是当运行该程序时,Node的内存使用量会上升到1.3 GB,这恰好是要读取的文件的大小。就像它没有使用流,而是将其缓冲并一次性写入OR垃圾回收器没有销毁内存中的“chunk”变量。这是程序:
const { createReadStream, createWriteStream } = require('fs');
const readStream = createReadStream('../movie.mp4', {
highWaterMark: 10000
});
const writeStream = createWriteStream('./copy.mp4', {
highWaterMark: 10000
});
readStream.on('data', function (chunk) {
writeStream.write(chunk);
})
readStream.on('end', function () {
console.log("reading done");
writeStream.end();
});
writeStream.on('close', function () {
console.log("Writing done.");
})
奇怪的是,如果我将这些流进行管道处理,它会按照预期工作,并且内存使用率不会超过 20 MB。像这样:
const { createReadStream, createWriteStream } = require('fs');
const readStream = createReadStream('../movie.mp4', {
highWaterMark: 10000
});
const writeStream = createWriteStream('./copy.mp4', {
highWaterMark: 10000
});
readStream.pipe(writeStream);
什么可能会导致这种行为?
节点版本:v14.15.4