Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 685
Eli Avatar asked Feb 20 '15 20:02

Eli


People also ask

What does exec () do in Nodejs?

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

What is Child_process in node JS?

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.


1 Answers

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.

like image 69
Peter Lyons Avatar answered Oct 19 '22 02:10

Peter Lyons