Reputation: 342
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:
I am reading a file with: const readStream = fs.createReadStream('./veryBigFile');
and I pipe the output to a POST request like this:
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.
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).
Any ideas ?
Upvotes: 3
Views: 1290
Reputation: 342
After your comment kirill Groshkov, I decided to take a look again at my code and I understood how to make it work !
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.
So I still had to use readStream.destroy('YOUR CUSTOM ERROR MESSAGE') to stop reading from the file after timeout.
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}`);
}
});
Upvotes: 1