0
0
Node.jsframework~3 mins

Why process.argv for command line arguments in Node.js? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could run the same script with different inputs without ever opening the code again?

The Scenario

Imagine you want to run a Node.js script that greets a user by name, but you have to change the code every time to update the name.

You open the file, change the name inside the code, save it, and run it again.

The Problem

This manual way is slow and annoying because you must edit the code each time.

It also makes your script less flexible and harder to reuse for different inputs.

The Solution

Using process.argv lets your script accept input directly from the command line when you run it.

This means you can pass different names or options without changing the code.

Before vs After
Before
const name = 'Alice';
console.log(`Hello, ${name}!`);
After
const name = process.argv[2];
console.log(`Hello, ${name}!`);
What It Enables

You can create flexible scripts that take different inputs easily, making your programs more powerful and reusable.

Real Life Example

Imagine a script that backs up files. Instead of hardcoding the folder path, you pass it as a command line argument so you can back up any folder without changing the code.

Key Takeaways

Manually changing code for input is slow and error-prone.

process.argv lets scripts read input from the command line.

This makes scripts flexible, reusable, and easier to run with different data.