9

I'm new to Node and I'm trying to write a command-line tool in Node that would allow you to pass a string in as an argument.

I saw that Node seems to break each word passed in as an array when using process.argv. I was wondering if the best way to grab the string is to loop through the array to construct the string or if there was a different option?

So let's say I have a simple program that takes a string and simply console.logs it out. It would look something like this.

> node index.js This is a sentence.
> This is a sentence.
michaellee
  • 1,282
  • 3
  • 17
  • 25
  • 1
    Possible duplicate of [How do I pass command line arguments to node.js?](http://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-node-js) – whostolemyhat May 12 '16 at 14:17
  • 1
    IMO it's not a duplicate, since this question is specifically about passing a multi-word parameter as single one, not parsing parameters in general. – MayaLekova May 12 '16 at 14:23
  • Hey @whostolemyhat I could see how this could be seen as a duplicate, but I already knew how to pass command line arguments in node.js, just didn't know how to pass an entire string as an argument without it being broken up word by word. – michaellee May 12 '16 at 14:24

4 Answers4

12

You can surround the sentence in quotes, i.e.

> node index.js "This is a sentence."

Another option is to join the text in your program:

process.argv.shift()  // skip node.exe
process.argv.shift()  // skip name of js file

console.log(process.argv.join(" "))
MayaLekova
  • 540
  • 3
  • 12
  • 1
    Thanks so much @MayaLekova, this seems to work for me. Also thanks for the comments regarding `.shift()` :) – michaellee May 12 '16 at 14:21
1

Another solution that doesn't require quotes or modifying process.argv:

const [ node, file, ...args ] = process.argv;
const string = args.join(' ');
console.log(string);

Output:

> node index.js This is a sentence
> This is a sentence

If you want to know more about the way I've used the spread operator (...) here, read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Rest_in_Object_Destructuring

Turbotailz
  • 181
  • 1
  • 4
0

The above answer uses excessive code!
Instead of shifting it twice use Array.prototype.splice.

// Removes elements from offset of 0
process.argv.splice(0, 2);

// Print the text as usually!
console.log(process.argv.join(' '));

Summary of the code

  • Remove first 2 elements from the array.
  • Join them using the [Backspace] delimeter.
0

if you are up for using npm package. Then use minimist. Become easy to deal with command line arguments. Check out their npmjs webpage for example. Hope this will help you.

var args=require('minimist')(process.argv.slice(2),{string:"name"});
console.log('Hello ' +args.name);

output is..

node app.js --name=test
Hello test
R.Sarkar
  • 344
  • 2
  • 8