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
Command line arguments are one of the simplest ways to make a script configurable without editing the source code each time.
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
const folder = process.argv[2] || 'public';
console.log(`Serving folder: ${folder}`);
If no folder is passed, the program uses public by default.
Example: a simple server setup
const http = require('http');
const folder = process.argv[2] || 'public';
const port = Number(process.argv[3]) || 3000;
const server = http.createServer((req, res) => {
res.end(`Serving folder: ${folder} on port ${port}`);
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Run it like this:
node server.js assets 4000
This makes the server configurable from the command line.
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'8080', soNumber('8080')becomes8080.- The program prints:
Folder: uploads
Port: 8080
What if no values are passed?
If you run:
node server.js
then:
process.argv[2]isundefined, sofolderbecomes'public'process.argv[3]isundefined, soportbecomes3000
Output:
Folder: public
Port: 3000
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
const port = Number(process.argv[3]);
if (Number.isNaN(port)) {
console.error('Port must be a number');
process.exit(1);
}
Real programs validate user input before using it.
When projects grow
For simple scripts, process.argv is enough. For larger CLI tools, developers often use libraries such as yargs, commander, or minimist to support named options like --port=3000. Even then, the idea still starts with command line arguments being passed into the program.
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 '30001', not 3001.
Correct code:
const port = Number(process.argv[3]);
console.log(port + 1);
Mistake 3: Not handling missing arguments
Broken code:
const folder = process.argv[2];
console.log(folder.toUpperCase());
If no argument is passed, this can fail because folder is undefined.
Correct code:
const folder = process.argv[2] || 'public';
console.log(folder.toUpperCase());
Mistake 4: Not validating numeric input
Broken code:
const port = Number(process.argv[3]);
If the user enters abc, port becomes NaN.
Better:
const port = Number(process.argv[3]);
if (Number.isNaN(port)) {
console.error('Please provide a valid numeric port.');
process.exit(1);
}
Mistake 5: Forgetting to quote values with spaces
If a folder name contains spaces, this can be split into multiple arguments unless quoted.
Example:
node server.js my folder
This becomes two arguments: my and folder.
Use quotes instead:
node server.js "my folder"
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 | Larger command line tools | node app.js --port 3000 |
Positional arguments vs named arguments
| Type | Example | Pros | Cons |
|---|---|---|---|
| Positional | node app.js uploads 3000 | Simple and short | Harder to read as arguments grow |
| Named | node app.js --folder uploads --port 3000 | Clear and flexible | Usually needs extra parsing logic or a library |
process.argv vs environment variables
| Option | Example | Use when |
|---|---|---|
| Command line argument | node app.js uploads | The value changes per command run |
| Environment variable | PORT=3000 node app.js | The value is part of the environment or deployment setup |
Both are common in Node.js, and many apps use both together.
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.argv[2]) {
console.error('Usage: node server.js <folder>');
process.exit(1);
}
Check for a flag
const args = process.argv.slice(2);
const debug = args.includes('--debug');
Important edge cases
- All arguments start as strings
- Missing arguments become
undefined - Values with spaces should be quoted in the shell
- Invalid number conversion results in
NaN
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:
node server.js uploads 3000 --debug
You can then read them from process.argv[2], process.argv[3], and so on.
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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.