zoukankan      html  css  js  c++  java
  • [Node.js] Stream all things!

    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.

  • 相关阅读:
    解决div嵌套时IE8和FF无法自适应高度
    64位windows系统安装javaee6.0不成功解决方案
    awk 处理
    mysql 事务控制
    mysql 事务控制
    mysql 保留的关键字
    mysql 保留的关键字
    expect set timeout -1 永不超时
    expect set timeout -1 永不超时
    aliyun 安装图形
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10516507.html
Copyright © 2011-2022 走看看