javascriptnode.jsbashstdin

node.js how to show stdin input with child_process.exec


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...


Solution

  • 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.