Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Command-line arguments

Command-line arguments are the words you type after the file name when starting a program: node app.js posts.json --short. They tell the program what to work on without changing its code. Arguments are available through process — a global Node.js object that describes the running program. It does not need to be imported.

process.argv

All arguments live in the process.argv array. Create the file app.js in the project root:

console.log(process.argv);

Run it with arguments:

node app.js hello 42

The terminal shows an array of four strings: the path to the node program, the path to app.js, then 'hello' and '42'.

Only your arguments

The first two items are rarely needed, so they are cut off with slice(2):

const args = process.argv.slice(2);
 
console.log(`Arguments received: ${args.length}`);
console.log(args);

node app.js hello 42 prints "Arguments received: 2" and the array [ 'hello', '42' ]. Note that 42 arrived as a string. All arguments are strings; numbers are obtained with Number().

A default value

An argument may be missing. A fallback is given with the ?? operator:

const title = process.argv[2] ?? 'Untitled';
 
console.log(`New post: ${title}`);

node app.js "Hello, Node.js" prints "New post: Hello, Node.js", and running without an argument prints "New post: Untitled". The quotes make a phrase with spaces arrive as one argument.

Flags

Arguments that start with -- are usually called flags. To check whether a flag was passed, use includes():

const args = process.argv.slice(2);
const isDraft = args.includes('--draft');
 
console.log(isDraft ? 'Saving a draft' : 'Publishing the post');

node app.js --draft prints "Saving a draft". For flags with values, such as --limit 10, there is the built-in parseArgs function — the lesson on command-line tools covers it.

Other facts about the program

PropertyWhat it holds
process.argvLaunch arguments
process.versionNode.js version, for example v22.12.0
process.platformSystem: win32, linux, darwin
process.pidProcess number in the system
process.cwd()Folder the program was started from

Common mistake

If you take process.argv[0] hoping for the first argument, you get the path to node:

const wrong = process.argv[0];
const right = process.argv[2];
 
console.log(wrong.includes('node'), right !== undefined);

User arguments start at index 2. To avoid confusion, write process.argv.slice(2) right away.

Thanks for reading!

Donate to the site — we work hard for you.