gpt4 book ai didi

node.js - 流上的 .pipe 和 pipeline 有什么区别

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:51 25 4
gpt4 key购买 nike

我发现了两种不同的方式在 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

我应该使用哪一个?这两者之间有什么好处?

最佳答案

TL;DR - 你最好使用管道

What's pipeline?

From the docs :一种模块方法,用于在流之间转发错误并正确清理并在管道完成时提供回调。

What's the motivation for using pipeline?

❌我们看一下下面的代码:

const { createReadStream } = require('fs');
const { createServer } = require('http');
const server = createServer(
(req, res) => {
createReadStream(__filename).pipe(res);
}
);

server.listen(3000);

这里出了什么问题?如果响应将退出或客户端关闭连接 - 则读取流不会关闭或销毁,这会导致内存泄漏。

✅因此,如果您使用pipeline,它将关闭所有其他流并确保没有内存泄漏。

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);

关于node.js - 流上的 .pipe 和 pipeline 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com