Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make process.argv print only the arguments (and not the path or node command)

It says it all in the title! I am making a very big project (involving AppleScript and iMessage) and the script has been tested and it opens terminal and will run: node ~/Desktop/chatbot [argument]. Currently, all it does is pass me this: [ '/usr/local/bin/node', '~/Desktop/chatbot', '[argument]' ]. How do I get it to pass me only [argument]?

like image 648
Mikey Avatar asked Nov 03 '25 05:11

Mikey


2 Answers

How do I get it to pass me only [argument]?

You don't. That's how it is designed. You can safely just ignore the [0] and the [1] elements of that array and just start looking at [2]. If you really want to make an array with those elements removed, you can .slice(2):

let args = process.argv.slice(2);
console.log(args);

Or if all you want is the first command line argument, you can get that directly:

let arg = process.argv[2];
console.log(arg);
like image 64
jfriend00 Avatar answered Nov 05 '25 18:11

jfriend00


The first two arguments are always node and the file/file path that you are trying to run.

If you only want to get the arguments passed other than node and file path, just ignore the first two values and retrieve them like:

for(var i = 2; i < process.argv.length; i++) {
  console.log(process.argv[i]);
}
like image 20
Muhammad Usman Avatar answered Nov 05 '25 18:11

Muhammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!