简体   繁体   English

在节点 js 上调用 readStream.destroy() 读取 stream 不会停止读取

[英]Calling readStream.destroy() on a node js read stream doesn't stop the reading

I hope you are all doing well.我希望你们一切都好。

I am facing an issue with streams in Node Js and I would like to solicit your help:我在 Node Js 中遇到了流问题,我想寻求您的帮助:

I am reading a file with: const readStream = fs.createReadStream('./veryBigFile');我正在读取一个文件: const readStream = fs.createReadStream('./veryBigFile');

and I pipe the output to a POST request like this:我 pipe 将 output 发送到这样的 POST 请求:

readStream.pipe(post_req); readStream.pipe(post_req);

However, I would like to stop the reading from the file after a certain timeout, and also to stop the POST request.但是,我想在某个超时后停止从文件中读取,并停止 POST 请求。

I tried both readStream.close() and readStream.destroy() but they don't work (I attached an 'end' listener to readStream, and it doesn't get triggered after the timeout).我尝试了 readStream.close() 和 readStream.destroy() 但它们不起作用(我在 readStream 上附加了一个“结束”侦听器,超时后它不会被触发)。

Any ideas?有任何想法吗?

After your comment kirill Groshkov, I decided to take a look again at my code and I understood how to make it work !在您发表评论 kirill Groshkov 之后,我决定再次查看我的代码,并且我了解如何使其工作!

After a destroy event is tirggered (with readStream.destroy()), it is an 'error' event that is emitted, not an 'end' event which I was listening to.在触发销毁事件后(使用 readStream.destroy()),它会发出一个“错误”事件,而不是我正在收听的“结束”事件。

So I still had to use readStream.destroy('YOUR CUSTOM ERROR MESSAGE') to stop reading from the file after timeout.所以我仍然不得不使用 readStream.destroy('YOUR CUSTOM ERROR MESSAGE') 在超时后停止读取文件。

Then I listened to this custom error with:然后我听了这个自定义错误:

        readStream.on('error', e => {
        if (e === 'YOUR CUSTOM ERROR MESSAGE') {
            post_req.abort(); //To cancel request
            // etc.
        } else {
            reject(`An error occured while uploading data: ${e}`);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM