Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

content(learn cli): make up to date #7307

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
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 @@ -16,7 +16,7 @@ USER_ID=239482 USER_KEY=foobar node app.js

That will pass the user `USER_ID` as **239482** and the `USER_KEY` as **foobar**. This is suitable for testing, however for production, you will probably be configuring some bash scripts to export variables.

> Note: `process` does not require a "require", it's automatically available.
> Note: `process` does not need to be imported, it is a global object in Node.js.

Here is an example that accesses the `USER_ID` and `USER_KEY` environment variables, which we set in above code.

Expand All @@ -27,7 +27,7 @@ process.env.USER_KEY; // "foobar"

In the same way you can access any custom environment variable you set.

Node.js 20 introduced **experimental** [support for .env files](https://nodejs.org/dist/latest-v20.x/docs/api/cli.html#--env-fileconfig).
Node.js 20 introduced **experimental** [support for .env files](https://nodejs.org/dist/latest-v22.x/docs/api/cli.html#--env-fileconfig).

Now, you can use the `--env-file` flag to specify an environment file when running your Node.js application. Here's an example `.env` file and how to access its variables using `process.env`.

Expand Down 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.
AugustinMauroy marked this conversation as resolved.
Show resolved Hide resolved

```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 All @@ -21,6 +21,7 @@ You can pass multiple variables to `console.log`, for example:
```js
const x = 'x';
const y = 'y';

console.log(x, y);
```

Expand Down Expand Up @@ -168,44 +169,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.

Example:

```js
console.log('\x1b[33m%s\x1b[0m', 'hi!');
```

You can try that in the Node.js REPL, and it will print `hi!` in yellow.
> **NOTE**
> This part of the resource is designed with version 22.11 which notes `styleText` as ‘Active development’.
Copy link
Member

@mikeesto mikeesto Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Chalk is extremely popular and styleText is still in development. I don't have a strong opinion - but I feel this change might be premature

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My idea behind this was to just talk about node and not the rest because the purpose of the learn section is to talk about node and not external packages.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the phrasing is odd, shouldn't mention 22.11 specifically, Learn content is always designed with LTS in mind, and it is available in LTS atm.

Copy link
Member

@marco-ippolito marco-ippolito Dec 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a PR to mark styleText as stable, so it's fine nodejs/node#56265


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.
In many cases, you will be tempted to paste certain text to get a nice output at the terminal.

You install it with `npm install chalk`, then you can use it:
There is a `styleText` function provided by the `node:util` module. Let's discover how to 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!'));
```mjs
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 @@ -14,7 +14,7 @@ If your main Node.js application file is `app.js`, you can call it by typing:
node app.js
```

Above, you are explicitly telling the shell to run your script with `node`. You can also embed this information into your JavaScript file with a "shebang" line. The "shebang" is the first line in the file, and tells the OS which interpreter to use for running the script. Below is the first line of JavaScript:
Above, you are explicitly telling the shell to run your script with `node`. You can also embed this information into your JavaScript file with a ["shebang"](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) line. The "shebang" is the first line in the file, and tells the OS which interpreter to use for running the script. Below is the first line of JavaScript:

```js
#!/usr/bin/node
Expand Down Expand Up @@ -48,12 +48,58 @@ node -e "console.log(123)"

## Restart the application automatically

As of nodejs V16, there is a built-in option to automatically restart the application when a file changes. This is useful for development purposes.
To use this feature, you need to pass the `--watch' flag to nodejs.
As of Node.js V16, there is a built-in option to automatically restart the application when a file changes. This is useful for development purposes.
To use this feature, you need to pass the `--watch` flag to Node.js.

```bash
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

Node.js provides a built-in task runner that allows you to execute specific commands defined in your `package.json` file. This can be particularly useful for automating repetitive tasks such as running tests, building your project, or linting your code.

### Using the `--run` flag

The [`--run`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--run) flag allows you to run a specified command from the `scripts` section of your `package.json` file. For example, if you have the following `package.json`:

```json
{
"type": "module",
"scripts": {
"start": "node app.js",
"dev": "node --run -- --watch",
"test": "node --test"
}
}
```

You can run the `test` script using the `--run` flag:

```bash
node --run test
```

### Passing arguments to the command

Let's explain the `dev` key in the `scripts` object of the `package.json` file.

The syntaxt `-- --another-argument` is used to pass arguments to the command. In this case, the `--watch` argument is passed to the `dev` script.
AugustinMauroy marked this conversation as resolved.
Show resolved Hide resolved

```bash
node --run dev
```

### Environment variables

The `--run` flag sets specific environment variables that can be useful for your scripts:

- `NODE_RUN_SCRIPT_NAME`: The name of the script being run.
- `NODE_RUN_PACKAGE_JSON_PATH`: The path to the `package.json` file being processed.

### Intentional limitations

The Node.js task runner is intentionally more limited compared to other task runners like `npm run` or `yarn run`. It focuses on performance and simplicity, omitting features like running `pre` or `post` scripts. This makes it suitable for straightforward tasks but may not cover all use cases.
Loading