文件流管道(pipe)

版权声明:欢迎交流讨论 https://blog.csdn.net/qq_37746973/article/details/83242597

在Node.js中读取文件时为使用非阻塞IO, 我们可以这样写:

    fs.createReadStream('./lvgu.jpg').on('data', (data) => {
      res.write(data);
    }).on('end', () => {
      res.end();
    })

还可以用pipe来简化代码:

fs.createReadStream('./lvgu.jpg').pipe(res);

通过 pipe, 将文件系统流接到了HTTP相应流中。这也是最有效的,推荐被用来实现静态文件托管功能的方法。

猜你喜欢

转载自blog.csdn.net/qq_37746973/article/details/83242597