NodeJS doesn't run code from pipe on stdin until after stdin is closed

Viewed 128

I have a python program that runs js code. However, node js doesn't run any of the code it receives until after stdin is closed, even when syscall tracing confirms that it successfully read that content from its stdin. For more information, see here (The accepted answer). Is there any way to run commands before stdin is closed?

This can also be reproduced without Python, using bash as follows:

{
  echo 'console.log("HI");'
  sleep 1
  echo 'console.log("HI");'
  sleep 1
  echo "Sent both commands to node with one second delay after each" >&2
} | node

Its output is:

Sent both commands to node with one second delay after each
HI
HI

...whereas if the code were executed by Node as soon as it was received, one would see:

HI
HI
Sent both commands to node with one second delay after each
1 Answers

My solution to this problem was to make my own miniature interactive console:

const fs = require('fs');

while (true){
    const data = fs.readFileSync("myinput", "utf8");
    if (data){
        try{
            console.log(data);
            eval(data)
        } catch(err) {
            console.log(err)
        };
        fs.writeFileSync("myinput", "", "utf8")
    };
};

I would then start the program and write to the file myinput using it as an stdin.

Related