【问题标题】:Problems reading stdin in node child process在节点子进程中读取标准输入的问题
【发布时间】:2015-11-12 14:04:29
【问题描述】:

我正在尝试使用节点 child_process 模块在 Windows 中执行命令。问题是有问题的应用程序(Windows 中的 ftp 命令行)提示输入用户名和密码。我尝试通过以下方式向命令提供询问的信息:

var ftp = spawn('ftp',['<<ip of server>>']); 
var authenticated = false;
var commandsSended = false;

ftp.stdin.write("debug\n");
ftp.stdin.write(os.EOL);

ftp.stdout.on("data", function(data) {
    console.log("FTPService: " + data.toString());
    if(data.toString().indexOf("226 Transfer complete") > -1) {
        ftp.stdin.write('bye\n');
    } else if(data.toString().indexOf("Gebruiker") > -1) {
        ftp.stdin.write("<<username of server>>");
        ftp.stdin.write(os.EOL);
    } else if(data.toString().indexOf("Wachtwoord") > -1) {
        ftp.stdin.write("<<password of server>>");
        ftp.stdin.write(os.EOL);
        authenticated = true;
    }
    if(authenticated && !commandsSended) {
        ftp.stdin.write("put " + filePath + " " + newName + "\n");
        commandsSended = true;
    }
});

ftp.on('exit', function(code) {
    if(code > 0) {
        console.log("FTPService closed with error " + code);
    } else {
        console.log("FTPService closed without error");
    }
});

这不会导致错误,但根本不起作用。在linux中我没有问题,因为我可以将登录信息作为命令的参数发送。我知道 nodejs 有它自己的模块,但我需要让它与命令行一起工作(还需要执行其他命令,这也会导致需要填写提示)。

【问题讨论】:

    标签: node.js process stdin


    【解决方案1】:

    开发 Node 应用程序的一个好习惯是尝试使您的应用程序尽可能混合。当我说混合时,我的意思是它应该在它支持的各种操作系统上以相同且无缝的方式运行。在您的情况下,这意味着放弃对 Windows 或 Linux 内置的第三方 FTP 的支持,并使用专门为 Node 构建的 FTP 客户端包。

    Node 有很多 FTP 客户端包,这里有一个正在积极开发的包:node-ftp。 另一个获得更多支持的是jsftp,它允许您连接到原始 FTP 套接字连接并将任意 FTP 命令写入服务器。

    【讨论】:

    • 感谢您的回答。我明白你的意思。我确实同意,但事实是我试图通过它与 Windows 中的 ftp 命令行工具一起工作来证明概念。因为还有其他命令需要以相同的方式执行。在 linux 中我也遇到了同样的问题,但我可以通过在参数中传递身份验证信息来解决 ftp 的情况。但是使用另一个命令(具有不同目的)我可能会遇到与 Windows 中相同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2019-12-05
    • 2020-11-23
    • 1970-01-01
    • 2011-02-17
    相关资源
    最近更新 更多