Question

How to Pass Command Line Arguments in Node.js

javascriptnode.jsargumentscommand-line-arguments

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 executable
  • process.argv[1] is the path to the script file
  • process.argv[2] is the first user-provided argument
  • process.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:

  1. which Node executable started it
  2. which script file was launched
  3. 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
Take Quiz

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

  1. Node starts the program.
  2. It builds the process.argv array.
  3. The array will look roughly like this:
[
  '/usr/bin/node',
  '/your/path/server.js',
  'uploads',
  '8080'
]
  1. process.argv[2] is 'uploads', so folder becomes 'uploads'.
  2. process.argv[3] is '8080', so Number('8080') becomes 8080.
  3. The program prints:
Folder: uploads
Port: 8080

What if no values are passed?

If you run:

node server.js

then:

  • process.argv[2] is undefined, so folder becomes 'public'
  • process.argv[3] is undefined, so port becomes 3000

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.

Take Quiz

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 path
  • process.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

ApproachWhat it doesBest forExample
process.argv[2]Reads one argument by positionVery simple scriptsnode app.js uploads
process.argv.slice(2)Gets all custom argumentsScripts with multiple inputsnode app.js a b c
Manual flag check with includes()Detects optional flagsSmall utilitiesnode app.js --debug
CLI library (commander, yargs)Parses named options and help textLarger command line toolsnode app.js --port 3000

Positional arguments vs named arguments

TypeExampleProsCons
Positionalnode app.js uploads 3000Simple and shortHarder to read as arguments grow
Namednode app.js --folder uploads --port 3000Clear and flexibleUsually needs extra parsing logic or a library

process.argv vs environment variables

OptionExampleUse when
Command line argumentnode app.js uploadsThe value changes per command run
Environment variablePORT=3000 node app.jsThe value is part of the environment or deployment setup

Both are common in Node.js, and many apps use both together.

Take Quiz

Cheat Sheet

Core facts

  • Use process.argv to read command line arguments in Node.js
  • process.argv is an array of strings
  • process.argv[0] = Node executable path
  • process.argv[1] = script path
  • process.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.

Take Quiz

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
Take Quiz

Keep learning

Related questions

View more