Node.js Command Line Interface (CLI)

Subject: Node.js

Node.js comes with a powerful Command Line Interface (CLI) that allows you to run scripts, inspect environments, manage packages, and interact directly with JavaScript using REPL. In this topic, we'll explore how to use the Node.js CLI effectively.

1. Running JavaScript Files

You can execute a .js file using the node command followed by the filename.

app.js

Output:

Explanation: This command tells Node.js to execute the app.js file.

2. Using Node.js REPL

REPL (Read-Eval-Print Loop) allows you to test JavaScript directly from the command line.

Try inside REPL:

Explanation: REPL is useful for testing small snippets and debugging without creating a file.

3. Using Command Line Arguments

You can pass command-line arguments to a Node.js script using process.argv. args.js

Run it like this:

Output:

Explanation: process.argv is an array that includes command-line arguments. The first two items are reserved for Node’s path and the script path.

4. Check Node and npm Version

Output:

Explanation: Use these commands to verify that Node.js and npm are installed.

5. Evaluate JavaScript with -e Option

Use the -e flag to run one-liners directly from the command line.

Output:

6. Run a Script with Custom Environment Variables

On Unix/Linux/macOS:

env.js

Output:

On Windows (CMD):

7. Other Useful CLI Flags

  • --inspect: Enable debugging mode
  • --watch: Automatically restart script on file changes
  • --trace-warnings: Print stack traces for warnings

Example:

8. Exit REPL or Node CLI

  • Press Ctrl + C twice
  • Or type .exit and press Enter

Key Takeaways

  • The Node.js CLI allows you to run JavaScript files, test code in REPL, pass arguments, and set environment variables.
  • process.argv is used to handle command-line arguments.
  • Use node -e for quick one-liner executions.
  • REPL is a built-in interactive shell for experimenting with JavaScript.
  • You can debug scripts using --inspect and auto-reload using --watch.
Next : Node.js vs Browser