使用nodejs执行子进程

时间:2014-07-22 08:35:44

标签: node.js

我正在尝试使用nodejs建立一个emulater 像这样使用comamnd line iam

C:\Program Files\Genymobile\Genymotion>player --vm-name "Samsung Galaxy Note 2 - 4.3 - API 18 - 720x1280"

我希望在nodejs中执行此操作 我的代码

var exec = require('child_process').execFile,
    child;

var getVms = function () {

    var device = 'Samsung Galaxy Note 2'
    var version ='4.3'    
    //command = process.env.GENY
       command = "C:\Program Files\Genymobile\Genymotion"
    command += "\\player"
    command += " --vm-name"
    command += " \"" + device + " - " + version + " - API 18 - 720x1280"+"\"";
console.log(command)
        var child = exec(command);
        child.stdout.on('data', function(data) {
            console.log('stdout:---------------------- ' + data);
        });
        child.stderr.on('data', function(data) {
            console.log('stdout err:---------------------- ' + data);
        });
        child.on('close', function(code) {
            console.log('closing code:---------------------------- ' + code);
        });
}
getVms();

但是我得到了输出

closing code:---------------------------- -1

用我的代码错误的emulator.whats

1 个答案:

答案 0 :(得分:2)

如果您想执行文件,也可以尝试spawn。你应该知道参数是作为数组传递的。试试这个:

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

exports.getVms = function (req, res) {
    process.chdir("C:\\Program Files\\Genymobile\\Genymotion");
    var execCmd = './player';
    var args = ["--vm-name", " \"" + device + " - " + version + " - API 18 - 720x1280"+"\""];
    var spw = spawn(execCmd, args);

    spw.stdout.on('data', function (data) {
        var str = data.toString()
        res.send(str);
    });

    spw.stderr.on('data', function (data) {
        console.log('ps stderr: ' + data);
        res.send(500);
    });

    spw.on('close', function (code) {
        console.log('process exit code ' + code);
    });
}