Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass a string as an argument to Node from the command-line?

Tags:

node.js

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.
like image 512
michaellee Avatar asked May 12 '16 14:05

michaellee


People also ask

Which object holds arguments pass through a node command?

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.

How do you execute terminal commands in node?

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.


1 Answers

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(" "))
like image 64
MayaLekova Avatar answered Nov 04 '22 16:11

MayaLekova