5
votes

I am learning how to use node.js, but am having trouble parsing command-line arguments. The following line:

node test.js --input=in.txt

Gives a parsing error when the code reaches this command:

var fileName = JSONparse.(process.argv[2]);

Results in the error:

 undefined
--input=in.txt 

Syntax error: Unexpected number

What I am trying to do is create an optional variable for the input file. If it is not specified in the command-line, it should resolve to 'a.txt'.

I have not found an easy way of creating default parameters, or use identifiers such as '--input=' to not have to worry about the order in which arguments are passed (I know it does not matter in this case with one argument).

3
Incidentally, Syntax error is because the JS syntax is bad. There is no JSONparse, and even if there was, JSONparse.( doesn't make sense; . is to access a member, so you need an identifier after .; ( doesn't work. Perhaps you meant JSON.parse(process.argv[2]), but that doesn't make sense either since the string is not JSON.Jacob
You are right @Jacob, I did mean JSON.parse. However:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Pablo Prado

3 Answers

1
votes

Vorpal.js is a framework I made for building interactive CLIs in Node. As part of this, it has a built-in API for easy command parsing.

0
votes

Best option: use an existing command line parser. The yargs module works pretty well.

If you want to roll your own, here's the approach I'd take. First, create an object with all your defaults:

var opts = { 
  inputStream: process.stdin,
  verbose: false
};

...then just loop through the args, replacing the options as you go. If an option wasn't present, then the defaults will be used:

for (var i = 2; i < process.argv.length; i++) {
  var arg = process.argv[i];
  var keyValue = arg.split('=');  
  var key = keyValue[0], value = keyValue[1];
  if (key === '--input' || key === '-i') {
      opts.inputStream = fs.createReadStream(value);
  }
  if (key === '---verbose' || key === '-v')  {
      opts.verbose = true;
  }
  // etc.
}
0
votes

If you want to parse something, it should be a stringified JSON object or parsing results in error. It is important to know that all the command line arguments in node js are strings

let fileName = 'a.txt'

process.argv.slice(2).forEach((arg) => {
  if(arg.indexOf('--input') !== -1){
    if(arg.indexOf('=') !== -1){
      fileName = arg.split("=")[1].trim()
    } else {
      console.log('Error in providing command line argument')
    }
  }
})

console.log("File Name is ",fileName)

for node index output will be

File Name is a.txt

for node index --input=hello.txt, the output will be

File Name is hello.txt