Question
How to Pass Command Line Arguments in Node.js
Question
I have a web server written in Node.js, and I want to start it with a specific folder provided from the command line. For example, I run it like this:
node server.js folder
In this command, server.js contains my server code, and folder is the value I want to pass into the program.
Node.js help shows that scripts can receive arguments:
node -h
# Usage: node [options] script.js [arguments]
How can I access those command line arguments inside JavaScript in a Node.js program?
Short Answer
By the end of this page, you will understand how Node.js receives command line arguments, how to read them with process.argv, how to ignore the built-in entries that Node adds automatically, and how to use those values safely in real programs such as servers, scripts, and automation tools.
Concept
In Node.js, command line arguments are available through the global process object, specifically process.argv.
argv stands for argument vector. It is an array of strings containing everything typed after the node command when the program starts.
For a command like:
node server.js folder
process.argv usually looks like this:
[
'/path/to/node',
'/path/to/server.js',
'folder'
]
This means:
process.argv[0]is the path to the Node.js executableprocess.argv[1]is the path to the script fileprocess.argv[2]is the first user-provided argumentprocess.argv[3]is the second user-provided argument, and so on
This matters because many Node.js programs are controlled from the terminal:
- starting a server with a custom folder
- passing a port number
- enabling debug mode
- providing filenames for scripts
- supplying environment-specific options
Mental Model
Think of process.argv as the list of words written on a note handed to your program when it starts.
If you launch Node.js with:
node server.js folder
your program receives a note that looks like this:
- which Node executable started it
- which script file was launched
- the extra value you typed:
folder
Your program can read that note and decide what to do next.
A useful shortcut is to think:
- first two items = system information
- everything after that = your actual inputs
Syntax and Examples
The core syntax is:
process.argv
To get the first custom argument:
const folder = process.argv[2];
console.log(folder);
If you run:
node server.js images
the output will be:
images
Example: reading multiple arguments
const args = process.argv.slice(2);
console.log(args);
Running:
node server.js images 3000 true
gives something like:
[ 'images', '3000', 'true' ]
Example: using an argument with a fallback
Step by Step Execution
Consider this code:
const folder = process.argv[2] || 'public';
const port = Number(process.argv[3]) || 3000;
console.log('Folder:', folder);
console.log('Port:', port);
Now run:
node server.js uploads 8080
Step by step
- Node starts the program.
- It builds the
process.argvarray. - The array will look roughly like this:
[
'/usr/bin/node',
'/your/path/server.js',
'uploads',
'8080'
]
process.argv[2]is'uploads', sofolderbecomes'uploads'.process.argv[3]is , so becomes .
Real World Use Cases
Command line arguments are common in real Node.js work.
1. Start a server with a specific directory
node server.js uploads
Useful for serving different folders in development.
2. Pass a custom port
node server.js public 5000
Helpful when running multiple services locally.
3. Process a file
node convert.js input.json output.csv
Many scripts take input and output filenames this way.
4. Enable a mode or flag
node app.js --debug
This can turn on verbose logging or development behavior.
5. Batch automation
node backup.js ./data ./backups
Scripts used in deployment, backups, imports, and reports often rely on command line arguments.
Real Codebase Usage
In real projects, developers often use process.argv in a few common patterns.
Guard clauses for required input
const folder = process.argv[2];
if (!folder) {
console.error('Usage: node server.js <folder>');
process.exit(1);
}
This stops the program early if required input is missing.
Parsing all user arguments at once
const args = process.argv.slice(2);
This is cleaner than repeatedly remembering that the first custom argument starts at index 2.
Basic flag checking
const args = process.argv.slice(2);
const debugMode = args.includes('--debug');
Useful for optional behavior.
Validation
Common Mistakes
Mistake 1: Using the wrong index
Beginners often expect the first custom argument at index 0.
Broken code:
const folder = process.argv[0];
console.log(folder);
Why it is wrong:
process.argv[0]is the Node executable pathprocess.argv[1]is the script path- your first custom value starts at
process.argv[2]
Correct code:
const folder = process.argv[2];
Mistake 2: Forgetting that arguments are strings
Broken code:
const port = process.argv[3];
console.log(port + 1);
If port is '3000', the output becomes , not .
Comparisons
| Approach | What it does | Best for | Example |
|---|---|---|---|
process.argv[2] | Reads one argument by position | Very simple scripts | node app.js uploads |
process.argv.slice(2) | Gets all custom arguments | Scripts with multiple inputs | node app.js a b c |
Manual flag check with includes() | Detects optional flags | Small utilities | node app.js --debug |
CLI library (commander, yargs) | Parses named options and help text |
Cheat Sheet
Core facts
- Use
process.argvto read command line arguments in Node.js process.argvis an array of stringsprocess.argv[0]= Node executable pathprocess.argv[1]= script pathprocess.argv[2]= first user argument
Most common patterns
const firstArg = process.argv[2];
const args = process.argv.slice(2);
Default value
const folder = process.argv[2] || 'public';
Convert to number
const port = Number(process.argv[3]);
Validate input
if (!process.[]) {
.();
process.();
}
FAQ
How do I get the first command line argument in Node.js?
Use process.argv[2]. The first two entries are reserved for the Node executable and the script path.
Why does process.argv[0] not contain my argument?
Because process.argv[0] is the path to the Node.js executable, not your custom input.
How do I get all user-provided arguments?
Use:
const args = process.argv.slice(2);
This removes the first two built-in entries.
Are Node.js command line arguments always strings?
Yes. If you need a number or boolean, you must convert it yourself.
How do I pass an argument with spaces?
Wrap it in quotes in the terminal:
node server.js "my folder"
Should I use process.argv or a library?
Use process.argv for small scripts. Use a CLI library when you need named options, help messages, aliases, or more complex parsing.
Can I pass multiple arguments to a Node.js script?
Yes. Example:
Mini Project
Description
Build a small Node.js script that starts a simple HTTP server using values passed from the command line. This project demonstrates how to read arguments, apply default values, validate input, and use those values in a practical program.
Goal
Create a server that accepts a folder name and port from the command line, then displays them in the HTTP response.
Requirements
- Read a folder name from the command line
- Read a port number from the command line
- Use default values if arguments are missing
- Validate that the port is a valid number
- Start an HTTP server and show the chosen values in the response
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.