简体   繁体   中英

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] ?

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);

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM