问题描述
我在 node.js 中找到了两种不同的管道传输方式
I found two different ways to pipe streams in node.js
众所周知的.pipe()
流方法
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
和流的独立函数
https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback
我应该使用哪一个,这两者之间有什么好处?
Which one should I use and what are the benefits between those two?
推荐答案
TL;DR - 你最好使用 pipeline
TL;DR - You better want to use pipeline
什么是管道?
来自文档:在流之间进行管道传输的模块方法转发错误并正确清理并在管道完成时提供回调.
From the docs: A module method to pipe between streams forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.
使用管道的动机是什么?
❌我们来看看下面的代码:
❌Let's take a look at the following code:
const { createReadStream } = require('fs');
const { createServer } = require('http');
const server = createServer(
(req, res) => {
createReadStream(__filename).pipe(res);
}
);
server.listen(3000);
这里有什么问题?如果响应将退出或客户端关闭连接 - 那么读取流不会关闭或销毁,这会导致内存泄漏.
What's wrong here?If the response will quit or the client closes the connection - then the read stream is not closed or destroy which leads to a memory leak.
✅所以如果你使用pipeline
,它会关闭所有其他流并确保没有内存泄漏.
✅So if you use pipeline
, it would close all other streams and make sure that there are no memory leaks.
const { createReadStream } = require('fs');
const { createServer } = require('http');
const { pipeline } = require('stream');
const server = createServer(
(req, res) => {
pipeline(
createReadStream(__filename),
res,
err => {
if (err)
console.error('Pipeline failed.', err);
else
console.log('Pipeline succeeded.');
}
);
}
);
server.listen(3000);
这篇关于流上的 .pipe 和管道有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!