无法使用交互式脚本获取child_process.spawn的输出

我不能在下面的代码中得到任何输出:

var spawn = require('child_process').spawn, script = 'ftp', child = spawn(script); child.stdout.on('data', function (data) { console.log('stdout: ' + data); }); child.stderr.on('data', function (data) { console.log('stderr: ' + data); }); child.on('close', function (code) { console.log('child process exited with code ' + code); }); 

它适用于诸如'ls','pwd'等正常脚本,但不适用于诸如'ftp','telnet'之类的交互式程序。 有什么build议么?


编辑:

以另一个脚本为例:

 #!/usr/bin/env python name = raw_input("your name>") print name 

当生成这个脚本时,我想用数据事件来获取提示“your name>”,这样我就可以input一些东西到stdin中。

问题是我没有在数据事件中,似乎没有任何事件被触发。

lscat可以通过input输出和错误stream控制。

ftptelnet可以通过tty间接控制。

该协议也是基于input/输出stream,但它更复杂。 您可以使用可用包来处理该协议。

https://github.com/chjj/pty.js

 var pty = require('pty.js'); var term = pty.spawn('ftp', [], options); term.on('data', function(data) { console.log(data); }); term.write(ftpCmd + '\r'); 

pty的作者有一些有趣的例子,他通过networking套接字转发到web,包括terminal游戏: https : //github.com/chjj/tty.js

在交互模式下,有一个命令解释器从stdin读取用户input,然后正确输出输出。 所以你必须写信给stdin来做一些事情。 例如,使用telnet命令将下列代码添加到您的代码中:

 child.stdin.write('?\n'); child.stdin.write('quit\n'); 

输出:

 stdout: Commands may be abbreviated. Commands are: ! cr mdir proxy send $ delete mget sendport site account debug mkdir put size append dir mls pwd status ascii disconnect mode quit struct bell form modtime quote system binary get mput recv sunique bye glob newer reget tenex case hash nmap rstatus trace ccc help nlist rhelp type cd idle ntrans rename user cdup image open reset umask chmod lcd passive restart verbose clear ls private rmdir ? close macdef prompt runique cprotect mdelete protect safe child process exited with code 0