Automatic writing text to the console using Node.j

2019-02-26 02:22发布

问题:

I need to clone GitHub repository using SSH and Node.js script:

var exec = require('child_process').exec;

exec('git clone git@github.com:jquery/jquery.git',
    function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    }
);

If github.com not in known_hosts file, SSH forcing to enter "yes" on the question "Are you sure you want to continue connecting (yes/no)?".

How can I automate the input of this text?

P.S. I know about StrictHostKeyChecking=no, but I need to clone repository without changing SSH config.

回答1:

Sure, that is entirely possible. When you call child_process.exec, it actually returns a ChildProcess Object. It contains an .stdin object which is an implementation of a Writable Stream, which you can pipe to / write to. Documentation on ChildProcess.stdin, also on Writable Stream.

Here is some example code that relates to your question:

var exec = require('child_process').exec;

var cmd = exec('git clone git@github.com:jquery/jquery.git', function (error, stdout, stderr) {
    // ...
});

cmd.stdin.write("yes");


回答2:

You could pass in yes prior to your git clone command.

exec('yes | git clone git@github.com:jquery/jquery.git'...