简体   繁体   English

如何使用child_process.exec访问node.js子进程中的命令行参数?

[英]How to access command line arguments in a node.js child process using child_process.exec?

I am trying to write a test script in node.js for another node.js script that is executed via command line with arguments. 我试图在node.js中为另一个node.js脚本编写测试脚本,该脚本通过带参数的命令行执行。 When the script is executed in the terminal the arguments are accessible using process.argv[2], process.argv[3], etc. However, those arguments are not present when the script is executed in the test script using child_process.exec(). 当在终端中执行脚本时,可以使用process.argv [2],process.argv [3]等访问参数。但是,当使用child_process.exec在测试脚本中执行脚本时,这些参数不存在( )。

target.js target.js

var arguments = {
    arg1: process.argv[2],
    arg2: process.argv[3]
};

console.log(arguments.arg1);
// This outputs '100' when target.js is executed from terminal

test.js test.js

var cp = require('child_process');

cp.exec('node target.js 100 200',
    function (err, stdout, stderr) {
        if (err) {
            console.log(err);
        }

        console.log(stdout);
        // process.argv[2] is undefined when executed as a child process
});

Any suggestions on how to get the same behavior when executing via child_process as I do when I execute it from the terminal? 关于如何在通过child_process执行时获得相同行为的任何建议,就像我从终端执行时一样?

Your problem is elsewhere. 你的问题在别处。 (Caveat: node 0.6.12) (警告:节点0.6.12)

I ran a test using this as a.js : 我使用它作为a.js运行测试:

console.log(JSON.stringify(process.argv));

And using your launcher below: 并使用下面的启动器:

var cp = require('child_process');

cp.exec('node a.js 100 200',
function (err, stdout, stderr) {
    if (err) {
        console.log(err);
    }

    console.log(stdout);
});

I get identical expected output: 我得到相同的预期输出:

joe@toad:~/src$ node a.js 100 200
["node","/home/joe/src/a.js","100","200"]
joe@toad:~/src$ node b.js
["node","/home/joe/src/a.js","100","200"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM