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.
In Node. js, as in C and many related environments, all command-line arguments received by the shell are given to the process in an array called argv (short for 'argument values'). There you have it - an array containing any arguments you passed in.
Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.
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(" "))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With