Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
content(learn cli): WIP
  • Loading branch information
AugustinMauroy committed Dec 2, 2024
commit f5b45d068b395265dbbfddc3936a4226445d9f9e
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais

How to make a Node.js CLI program interactive?

Node.js since version 7 provides the [`readline` module](https://nodejs.org/api/readline.html) to perform exactly this: get input from a readable stream such as the `process.stdin` stream, which during the execution of a Node.js program is the terminal input, one line at a time.
Node.js since version 7 provides the [`readline` module](https://nodejs.org/docs/latest-v22.x/api/readline.html) to perform exactly this: get input from a readable stream such as the `process.stdin` stream, which during the execution of a Node.js program is the terminal input, one line at a time.

```cjs
const readline = require('node:readline');
Expand Down Expand Up @@ -47,45 +47,3 @@ In this callback function, we close the readline interface.
`readline` offers several other methods, please check them out on the package documentation linked above.

If you need to require a password, it's best not to echo it back, but instead show a `*` symbol.

The simplest way is to use the [`readline-sync` package](https://www.npmjs.com/package/readline-sync) which is very similar in terms of the API and handles this out of the box.

A more complete and abstract solution is provided by the [Inquirer.js package](https://github.com/SBoudrias/Inquirer.js).

You can install it using `npm install inquirer`, and then you can replicate the above code like this:

```cjs
const inquirer = require('inquirer');

const questions = [
{
type: 'input',
name: 'name',
message: "What's your name?",
},
];

inquirer.prompt(questions).then(answers => {
console.log(`Hi ${answers.name}!`);
});
```

```mjs
import inquirer from 'inquirer';

const questions = [
{
type: 'input',
name: 'name',
message: "What's your name?",
},
];

inquirer.prompt(questions).then(answers => {
console.log(`Hi ${answers.name}!`);
});
```

Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.

It's worth knowing all the alternatives, especially the built-in ones provided by Node.js, but if you plan to take CLI input to the next level, Inquirer.js is an optimal choice.
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,10 @@ node --env-file=.env --env-file=.development.env app.js
```

> Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.

But there may be a problem: if the file doesn't exist, it will return an error.
To avoid this, you can use the `--env-file-if-exists` flag.

```bash
node --env-file-if-exists=.env app.js
```
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
---
title: How to use the Node.js REPL
layout: learn
authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais, vaishnav-mk
authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais, vaishnav-mk, AugustinMauyroy
---

# How to use the Node.js REPL

## What is the Node.js REPL?

Node.js comes with a built-in REPL (Read-Eval-Print Loop) environment that allows you to execute JavaScript code interactively. The REPL is accessible through the terminal and is a great way to test out small pieces of code.

## How to use the Node.js REPL

The `node` command is the one we use to run our Node.js scripts:

```bash
Expand Down Expand Up @@ -112,10 +118,14 @@ If you type `.break` at the end of a line, the multiline mode will stop and the

We can import the REPL in a JavaScript file using `repl`.

```js
```cjs
const repl = require('node:repl');
```

```mjs
import repl from 'node:repl';
```

Using the repl variable we can perform various operations.
To start the REPL command prompt, type in the following line

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
---
title: Output to the command line using Node.js
layout: learn
authors: flaviocopes, potch, MylesBorins, fhemberger, LaRuaNa, amiller-gh, ahmadawais
authors: flaviocopes, potch, MylesBorins, fhemberger, LaRuaNa, amiller-gh, ahmadawais, AugustinMauroy
---

# Output to the command line using Node.js

### Basic output using the console module

Node.js provides a [`console` module](https://nodejs.org/api/console.html) which provides tons of very useful ways to interact with the command line.
Node.js provides a [`console` module](https://nodejs.org/docs/latest-v22.x/api/console.html) which provides tons of very useful ways to interact with the command line.

It is basically the same as the `console` object you find in the browser.

Expand Down Expand Up @@ -168,44 +168,31 @@ It will not appear in the console, but it will appear in the error log.

### Color the output

You can color the output of your text in the console by using [escape sequences](https://gist.github.com/iamnewton/8754917). An escape sequence is a set of characters that identifies a color.
> **NOTE**
> This part of the resource is designed with version 22.11 which notes `styleText` as ‘Active development’.

Example:

```js
console.log('\x1b[33m%s\x1b[0m', 'hi!');
```
In many cases, you will be tempted to paste certain text to get a nice output at the terminal.

You can try that in the Node.js REPL, and it will print `hi!` in yellow.
There is a `styleText` function provided by the `node:util` module. Let's discover how to use it.

However, this is the low-level way to do this. The simplest way to go about coloring the console output is by using a library. [Chalk](https://github.com/chalk/chalk) is such a library, and in addition to coloring it also helps with other styling facilities, like making text bold, italic or underlined.

You install it with `npm install chalk`, then you can use it:

```js
const chalk = require('chalk');
First of all, you need to import the `styleText` function from the `node:util` module:

console.log(chalk.yellow('hi!'));
```esm
import { styleText } from 'node:util';
```

Using `chalk.yellow` is much more convenient than trying to remember the escape codes, and the code is much more readable.

Check the project link posted above for more usage examples.

### Create a progress bar

[Progress](https://www.npmjs.com/package/progress) is an awesome package to create a progress bar in the console. Install it using `npm install progress`
```cjs
const { styleText } = require('node:util');
```

This snippet creates a 10-step progress bar, and every 100ms one step is completed. When the bar completes we clear the interval:
Then, you can use it to style your text:

```js
const ProgressBar = require('progress');

const bar = new ProgressBar(':bar', { total: 10 });
const timer = setInterval(() => {
bar.tick();
if (bar.complete) {
clearInterval(timer);
}
}, 100);
console.log(
styleText(['red'], 'This is red text ') +
styleText(['green, bold'], 'and this is green bold text ') +
'this is normal text'
);
```

The first argument is an array of styles, and the second argument is the text you want to style. We invite you to read [the docs](https://nodejs.org/docs/latest-v22.x/api/util.html#utilstyletextformat-text-options)
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@ node --watch app.js
```

So when you change the file, the application will restart automatically.
Read the [`--watch` flag documentation](https://nodejs.org/docs/latest/api/cli.html#--watch).
Read the [`--watch` flag documentation](https://nodejs.org/docs/latest-v22.x/api/cli.html#--watch).

## Run a task with node.js