I have a node.js script that uses child_process.exec to call npm adduser
. Normally, if I type npm adduser into a console, I get:
Username: [stdin prompt]
Password: [stdin prompt]
etc.
If I use node.js to execute this code, then instead nothing gets printed out and it just gets stuck at an empty prompt, which goes on forever until I ctrl-C out of it.
How do I get the usual behavior? I basically just want to execute bash and let it do its thing...
The exec() function in Node. js creates a new shell process and executes a command in that shell. The output of the command is kept in a buffer in memory, which you can accept via a callback function passed into exec() .
Usually, Node. js allows single-threaded, non-blocking performance but running a single thread in a CPU cannot handle increasing workload hence the child_process module can be used to spawn child processes. The child processes communicate with each other using a built-in messaging system.
So instead of exec
which is for running a program without doing any complex stdio interaction, use child_process.spawn
which will give you access to the npm process's stdio and you can call child.stdin.write(username + "\n")
on the child's stdin
file (and similar for the password). That might be sufficient to get things to proceed, but sometimes when a program expects user interactive input, emulating that programmatically can be tricky (thus the existence of things like expect).
I think npm
(via the "read" npm module) is reading from stdin without echoing, in which case this should work. If, however, it's directly reading from the tty device, writing to stdin won't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With