1

When I run this in bash:

mkfifo im-a-pipe && node -e '
var fs = require("fs")
var childProcess = require("child_process")

console.log("pre-open")
fs.open("im-a-pipe", "w", function(err, fd){
if(err)
throw err
console.log("opened")
})
console.log("post-open")
childProcess.exec("echo wat")
console.log("YOU CAN NOT SEE MEEE")
'

I expect the following output:

pre-open
post-open
YOU CAN NOT SEE MEEE

But instead node waits after printing the first two lines:

pre-open
post-open

I'm thinking that this probably has something to do with the pipe blocking until something opens the other side, but this behavior surprised me.

Am I missing something with how these functions are supposed to operate?

2 Answers2

1

This may be a bug in your operating system or just an older version of Node. Works for me on Mac with Node 4. A co-worker was able to run it on Debian but not until he upgraded to Node 8.

0

That is exactly how pipes work (either named or anonymous). The writer will block until there is a reader at the other end, and a reader would block without a writer. You could say that's a fundamental principle.

Here's a little demo you can do on the command-line. You will need two terminal sessions, I'll call them A and B.

On A:

mkfifo mypipe
ls > mypipe

Session A will block. Now on session B:

cat mypipe

That should display the ls output, and unblock session A.

You can also try this by doing the cat first.

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • Yeah, I understand that pipes block the writer until another process opens the pipe for reading, but two things are going on here: 1) Node.js generally uses a nonblocking interface, and childProcess.exec shouldn't block 2) The process isn't even blocking on the open call to the pipe. – Hurricane Hamilton Oct 28 '16 at 11:57