Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Building Command Line Interface Apps | Section
Fondamentaux de Node.js

bookBuilding Command Line Interface Apps

Glissez pour afficher le menu

What Are CLI Applications?

Command Line Interface (CLI) applications are tools that allow users to communicate with software through command-line instructions. They offer speed, efficiency, and automation capabilities, making them ideal for various tasks.

Benefits of CLI Applications:

  • Quick Execution of Tasks: CLI apps are lightning-fast when it comes to task execution. You can accomplish tasks with just a few keystrokes;
  • Automation Potential: They are automation-friendly, enabling you to create scripts and automate repetitive tasks effortlessly;
  • Suitable for Server Environments: CLI apps are well-suited for server environments, where graphical interfaces may not be available or practical.

In previous chapters, you might recall encountering the terminal while running Node apps. It is that CLI we are talking about.

Understanding the process.argv

When you fire up a Node.js script (by typing node app) in the command line, the process.argv array becomes your trusty sidekick. It carries the arguments you provide along with the command. This array is like a treasure chest with:

  • Element 0: The path to the Node.js executable;
  • Element 1: The path to the script being executed;
  • Elements 2 and beyond: Any additional arguments provided by the user.

You've got the theory, and now it's time to witness it in action. Launch the same Node script on your local machine and witness the magic.

Have you ever wondered where Node.js resides on your computer? Now you can find out with a single line of code:

console.log(process.argv);

CLI App Example

The true power lies in how we wield these arguments in the scripts. Behold an example script that calculates the sum of numbers we provide as arguments:

const args = process.argv.slice(2);
const sum = args.reduce((total, num) => total + parseFloat(num), 0);
console.log('Sum:', sum);

We're running the script and witnessing the magic unfold before our eyes.

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 29

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 29
some-alt