如何调用CLI并响应Node.js中的提示

时间:2016-10-25 15:11:04

标签: node.js prompt

我正在编写一个在linux上调用openssl的node.js程序。

var cmd = 'openssl req -new -sha256 -key delegation.key -out delegation.csr';

这会引发一系列用户输入提示:

Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

我希望我的node.js程序自动填写答案并点击每个的“回车”键。

TX!

1 个答案:

答案 0 :(得分:0)

使用 child_process

var childprocess = require('child_process');
var openssl = childprocess.spawn('openssl', ['req','-new','-sha256','-key','delegation.key','-out','delegation.csr']);
openssl.stdout.setEncoding('utf8');

var current = '';
openssl.stdout.on("data", function(data) {
    current += data;
    if (current[current.length-1] == '\n') {

        // Handle text in "current" (this is what openssl has written)

        // if we should reply {

            var reply = 'MY REPLY TO WHAT IS IN CURRENT';

            childProcess.stdin.write(reply + '\n');

        // } else {
            // (if we are finished - have no more replies)
            // openssl.stdin.end();
        // }
        current = '';
    }
});