How do I pass command line arguments to a Node.js program?

General Tech Bugs & Fixes 2 years ago

0 4 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (4)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this:

$ node server.js folder

here server.js is my server code. Node.js help says this is possible:

$ node -h
Usage: node [options] script.js [arguments]

How would I access those arguments in JavaScript? Somehow I was not able to find this information on the web.

 

profilepic.png
manpreet 2 years ago

The arguments are stored in process.argv

process.argv is an array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.

 

// print process.argv
process.argv.forEach(function (val, index, array) {
  console.log(index + ': ' + val);
});

This will generate:

$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

0 views   0 shares

profilepic.png
manpreet 2 years ago

To normalize the arguments like a regular javascript function would receive, I do this in my node.js shell scripts:

var args = process.argv.slice(2);

Note that the first arg is usually the path to nodejs, and the second arg is the location of the script you're executing.


0 views   0 shares

profilepic.png
manpreet 2 years ago
const args = process.argv;
console.log(args);

This returns:

$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.