与命令行客户端进行交互

我必须执行一些我想用一组给定的参数执行的命令行程序。

问题是,那些命令行程序在某个时刻要求用户名和密码。 根据他们的文档,不可能将这些作为附加parameter passing,但必须手动input。

如何使用node.js以编程方式input这些参数?

所以基本上我要问用户一次他/她的凭据,然后每次询问时,自动input。

我能够从命令行读取用户名和密码,但我无法将其传递给其他程序。

这是我目前的做法

// get username/password using readline // execute next script var exec = require('child_process').exec; exec( 'someCommandClient -with Parameters', function( err , stdout, stderr ){ // error handling if( err ){ console.log( err ); return } // XXX here we should react on being prompted for username and password }); 

我认为你可以尝试nexpect (或类似的模块,有一个bash expect -like支持)

为了简化你的代码,当你想要查询用户的数据时,我build议使用readline-sync模块 ,而不是使用本地的。

如果要与subprocess交互,则不能使用child_process.exec,而必须使用child_process.spawn(前者等待subprocess退出以调用callback)

然后将用户名或密码传递给subprocess,您必须写入标准inputstreamhttp://nodejs.org/api/child_process.html#child_process_child_stdin

像这样的东西应该做的工作

 var child = require('child_process').spawn('someprocess'); child.stdout.on('data', function(data) { if (data === 'Login: ') child.stdin.write('Sirko'); });