Node.js wait function in nexpect module does not working

I wrote a code for testing scp transmission. This is the code.

var async = require('async'),
    nexpect = require('nexpect'),
    arg = {
    'host' : '192.168.0.3',
    'username' : 'root',
    'password' : 'rootpwd',
    'path' : '~'
    },
    file_list = ['a.txt', 'b.txt', 'c.txt'];

function scpFileTransfer(arg, callback) {
    nexpect.spawn('scp ' + arg.file + ' ' + arg.username + '@' + arg.host + ':' + arg.path, { stream: 'stderr' })
        .wait(/password/)
        .sendline(arg.password)
        .run(function (err) {
            if(err) console.log(err);
            else console.log('from ' + arg.file + ' to ' + arg.username + '@' + arg.host + ':' + arg.path + ' success!');
            callback();
        }
    );
}

async.eachSeries(file_list, function(item, callback) {
    arg.file = item;
    scpFileTransfer(arg, function () {
        callback();
    });
}, function (err) {
    if(err) console.trace(err);
    else console.log('success');
});

I expected output like this,

from a.txt to root@192.168.0.3:~ success!
from b.txt to root@192.168.0.3:~ success!
from c.txt to root@192.168.0.3:~ success! 

But output was different with my expectation. My node.js module was waiting command line input. How can I run my code without command line input?

I solved this problem by myself.

For transmission with scp in node.js, it needs redirection about stdout stream.

So, I tried redirection about /dev/stdout using fs.readSync function.

But my program died with 'unknown error'.

This code is new scpFileTransfer function using 'expect' program neither nexpect module nor redirection.

function scpFileTransfer(arg, callback) {
    var buf = new Buffer(256),
        len = 0,
        scp;
    len += buf.write(   'set timeout -1\n' +
                        'spawn scp ' + arg.file + ' ' + arg.username + '@' + arg.host + ':' + arg.path + '\n' +
                        'expect -exact "password: "\n' +
                        'send -- "' + arg.password + '\r"\n' +
                        'expect {\$\s*} { interact }\n');
    fs.writeFileSync('./.scp_login.exp', buf.toString('utf8', 0, len));

    scp = spawn('expect', ['-f', '.scp_login.exp']);
    scp.stdout.on('data', function (data) {
        console.log(data.toString('utf8', 0, len));
    });
    scp.stderr.on('data', function (data) {
        console.log('stderr: ' + data);
    });
    scp.on('exit', function (code) {
        fs.unlink('./.scp_login.exp', function (err) {
            if(err) throw err;
        });
        callback();
    });
}

If you run this code in your environment, you should check whether 'expect' program is installed or not.

If not, you can install by followed commands.


Ubuntu - sudo apt-get install expect

CentOS - yum install expect

Mac OS X - (Already installed in os.)


Thanks.