nodejs
  1. nodejs-command-line-options

Node.js Command Line Options

In Node.js, you can use command-line options to set flags or values that can modify the behavior of your script. In this tutorial, we'll discuss how to use command-line options in Node.js and provide examples.

Syntax

The syntax for using command-line options in Node.js is as follows:

node [options] [script.js] [arguments]

The options are preceded by hyphens and can be a single character or a whole word. The arguments are any additional values that you want to pass to your script.

Example

Let's say we have a script called "hello.js" that takes a command-line option "-u" and a required argument "name". Here's how we can implement it:

const argv = require('minimist')(process.argv.slice(2));

if(argv.u) {
  console.log(`Hello, ${argv.name.toUpperCase()}!`);
} else {
  console.log(`Hello, ${argv.name}!`);
}

Now, we can run the script using the following command:

node hello.js --name="John" -u

Output

When we run the example code above, the output will be:

Hello, JOHN!

This is because we passed the "-u" flag to the script, which converted the name argument to uppercase before printing it to the console.

Explanation

In the example above, we used the "minimist" package to parse the command-line options passed to the script. We checked for the "u" flag and, if present, converted the "name" argument to uppercase before printing it to the console.

Use

Command-line options are useful when you want to modify the behavior of your script dynamically without changing the code. They can also allow users to interact with your script in a more controlled manner.

Important Points

  • Command-line options must be prefixed with a hyphen and can be a single character or a whole word.
  • You can use any command-line argument to modify the behavior of your script.
  • Always validate user inputs that are passed through command-line arguments to prevent security issues.

Summary

In this tutorial, we discussed how to use command-line options in Node.js and provided an example. We covered the syntax, example, output, explanation, use, important points, and summary of command-line options in Node.js. With this knowledge, you can build scripts that are more flexible and easier to interact with from the command line.

Published on: