[Node.js] Stream all things!

本文探讨了在Node.js中使用流(Stream)API处理大文件的优势。通过对比传统文件读取方法,流API能显著降低内存消耗,避免一次性将大量数据加载到内存中,从而提高应用性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Node.js come alone with many Stream API. Stream is useful when handling large trunck of data.

For example, we have a big file to read from file system:

// create-big-file.js

const fs = require('fs')
const file = fs.createWriteStream('./big.file')

for (let i = 0; i <= 1e6; i++) {
    file.write('awefawgrga afewfa')
}

file.end();

 

If we are reading it using normal API:

const fs = require('fs')
const server = require('http').createServer();
server.on('request', (req, res) => {
    fs.readFile('./big.file', (err, data) => {
        if (err) throw err;

        res.end(data);
    })
});
server.listen(8000);

 

When running the code, we found that the normal memory cost is 8MB, when reading the large file, memory cost is 400+MB, basiclly it buffer all the file content into the memory, this is not the way we want.

 

Using Stream:

const fs = require('fs')
const server = require('http').createServer();
server.on('request', (req, res) => {
    /*fs.readFile('./big.file', (err, data) => {
        if (err) throw err;

        res.end(data);
    })*/
    const src = fs.createReadStream('./big.file')
    src.pipe(res)
});

server.listen(8000);

 

After updating the code, the memory usage of stream version stay around 30-40MB.

 

转载于:https://www.cnblogs.com/Answer1215/p/10516507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值