Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close readable stream to FIFO in NodeJS

I am creating a readable stream to a linux fifo in nodejs like this:

var stream = FS.createReadStream('fifo');

This all works well and I can receive the data from the fifo just fine. My problem is that I want to have a method to shut my software down gently and therefore I need to close this stream somehow.

Calling

process.exit();

does have no effect as the stream is blocking.

I also tried to destroy the stream manually by calling the undocumented methods stream.close() as well as stream.destroy() as described in the answers of this question.

I know that I could kill my own process using process.kill(process.pid, 'SIGKILL') but this feels like a really bad hack and could have bad impacts on the filesystem or database.

Isn't there a better way to achieve this?

You can try this minimal example to reproduce my problem:

var FS = require('fs');
console.log("Creating readable stream on fifo ...");
var stream = FS.createReadStream('fifo');
stream.once('close', function() {
    console.log("The close event was emitted.");
});
stream.close();
stream.destroy();
process.exit();

After creating a fifo called 'fifo' using mkfifo fifo.

How could I modify the above code to shutdown the software correctly?

like image 765
Prior99 Avatar asked Feb 15 '26 06:02

Prior99


1 Answers

Explicitly writing to the named pipe will unblock the read operation, for example:

require('child_process').execSync('echo "" > fifo');
process.exit();
like image 135
Philipp Claßen Avatar answered Feb 17 '26 21:02

Philipp Claßen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!