TankofVines
TankofVines

Reputation: 1167

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. 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().

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

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?

Upvotes: 4

Views: 4369

Answers (1)

Joe
Joe

Reputation: 42577

Your problem is elsewhere. (Caveat: node 0.6.12)

I ran a test using this as 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"]

Upvotes: 2

Related Questions