Node.js — Command Line
process.argv
// script.js
const args = process.argv.slice(2);
console.log('Arguments:', args);
node script.js hello world
# Arguments: [ 'hello', 'world' ]
Command-Line Arguments
const args = process.argv.slice(2);
const command = args[0];
const options = args.slice(1);
switch (command) {
case 'greet':
console.log(`Hello, ${options[0]}!`);
break;
case 'add':
console.log(options.reduce((a, b) => Number(a) + Number(b), 0));
break;
}
Environment Variables
console.log(process.env.NODE_ENV);
console.log(process.env.HOME);
NODE_ENV=production node app.js
Process Object
| Property | Description |
|---|---|
| process.argv | Command-line arguments |
| process.env | Environment variables |
| process.cwd() | Current directory |
| process.exit() | Exit process |
| process.version | Node.js version |
Mini Practice
- Access command-line arguments
- Use environment variables
- Build a simple CLI tool
- Handle different commands
Up Next
Continue with Modules — CommonJS and ES Modules.
Related Topics
Frequently Asked Questions about Command Line
What is Command Line in Node.js?
Command Line is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Command Line?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Command Line.
Why is Command Line important in Node.js?
Command Line is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.