3

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?

Community
  • 1
  • 1
Prior99
  • 619
  • 5
  • 13
  • Creating the stream like this: ```stream = FS.createReadStream('fifo', {flags : 'r+'});``` and then closing it like this ```var c = FS.createWriteStream('fifo'); c.write('\0'); c.close(); stream.pause(); stream.close(); ``` works, but it feels more like a dirty hack. – Prior99 Jul 08 '15 at 13:21
  • 1
    there is an explanation in the node docs: https://nodejs.org/dist/latest-v11.x/docs/api/fs.html#fs_fs_createreadstream_path_options – Lloyd Dec 13 '18 at 10:45

1 Answers1

1

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

require('child_process').execSync('echo "" > fifo');
process.exit();
Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239