Skip to content

Commit 56cdefb

Browse files
AugustinMauroyCopilotruyadorno
authored
content(learn cli): make up to date (#7307)
* content(learn cli): WIP * content(learn cli): introduce * content(learn cli): add link * content(learn cli): fix link * content(learn cli): add shebang link * content(learn cli): clarify process global object * content(learn cli): fix * fix: code format * fix typo Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Signed-off-by: Augustin Mauroy <augustin.mauroy@outlook.fr> * rephrase sentences Co-authored-by: Ruy Adorno <ruyadorno@google.com> Signed-off-by: Augustin Mauroy <augustin.mauroy@outlook.fr> --------- Signed-off-by: Augustin Mauroy <augustin.mauroy@outlook.fr> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Ruy Adorno <ruyadorno@google.com>
1 parent d687927 commit 56cdefb

5 files changed

+93
-84
lines changed

apps/site/pages/en/learn/command-line/accept-input-from-the-command-line-in-nodejs.md

Lines changed: 1 addition & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais
88

99
How to make a Node.js CLI program interactive?
1010

11-
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.
11+
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.
1212

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

4949
If you need to require a password, it's best not to echo it back, but instead show a `*` symbol.
50-
51-
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.
52-
53-
A more complete and abstract solution is provided by the [Inquirer.js package](https://github.com/SBoudrias/Inquirer.js).
54-
55-
You can install it using `npm install inquirer`, and then you can replicate the above code like this:
56-
57-
```cjs
58-
const inquirer = require('inquirer');
59-
60-
const questions = [
61-
{
62-
type: 'input',
63-
name: 'name',
64-
message: "What's your name?",
65-
},
66-
];
67-
68-
inquirer.prompt(questions).then(answers => {
69-
console.log(`Hi ${answers.name}!`);
70-
});
71-
```
72-
73-
```mjs
74-
import inquirer from 'inquirer';
75-
76-
const questions = [
77-
{
78-
type: 'input',
79-
name: 'name',
80-
message: "What's your name?",
81-
},
82-
];
83-
84-
inquirer.prompt(questions).then(answers => {
85-
console.log(`Hi ${answers.name}!`);
86-
});
87-
```
88-
89-
Inquirer.js lets you do many things like asking multiple choices, having radio buttons, confirmations, and more.
90-
91-
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.

apps/site/pages/en/learn/command-line/how-to-read-environment-variables-from-nodejs.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ USER_ID=239482 USER_KEY=foobar node app.js
1616

1717
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.
1818

19-
> Note: `process` does not require a "require", it's automatically available.
19+
> Note: `process` does not need to be imported, it is a global object in Node.js.
2020
2121
Here is an example that accesses the `USER_ID` and `USER_KEY` environment variables, which we set in above code.
2222

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

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

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

3232
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`.
3333

@@ -57,3 +57,10 @@ node --env-file=.env --env-file=.development.env app.js
5757
```
5858

5959
> Note: if the same variable is defined in the environment and in the file, the value from the environment takes precedence.
60+
61+
In case you want to optionally read from a `.env` file, it's possible to avoid
62+
throwing an error if the file is missing using the `--env-file-if-exists` flag.
63+
64+
```bash
65+
node --env-file-if-exists=.env app.js
66+
```

apps/site/pages/en/learn/command-line/how-to-use-the-nodejs-repl.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
---
22
title: How to use the Node.js REPL
33
layout: learn
4-
authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais, vaishnav-mk
4+
authors: flaviocopes, MylesBorins, fhemberger, LaRuaNa, ahmadawais, vaishnav-mk, AugustinMauyroy
55
---
66

77
# How to use the Node.js REPL
88

9+
## What is the Node.js REPL?
10+
11+
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.
12+
13+
## How to use the Node.js REPL
14+
915
The `node` command is the one we use to run our Node.js scripts:
1016

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

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

115-
```js
121+
```cjs
116122
const repl = require('node:repl');
117123
```
118124

125+
```mjs
126+
import repl from 'node:repl';
127+
```
128+
119129
Using the repl variable we can perform various operations.
120130
To start the REPL command prompt, type in the following line
121131

apps/site/pages/en/learn/command-line/output-to-the-command-line-using-nodejs.md

Lines changed: 21 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
22
title: Output to the command line using Node.js
33
layout: learn
4-
authors: flaviocopes, potch, MylesBorins, fhemberger, LaRuaNa, amiller-gh, ahmadawais
4+
authors: flaviocopes, potch, MylesBorins, fhemberger, LaRuaNa, amiller-gh, ahmadawais, AugustinMauroy
55
---
66

77
# Output to the command line using Node.js
88

99
### Basic output using the console module
1010

11-
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.
11+
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.
1212

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

@@ -21,6 +21,7 @@ You can pass multiple variables to `console.log`, for example:
2121
```js
2222
const x = 'x';
2323
const y = 'y';
24+
2425
console.log(x, y);
2526
```
2627

@@ -168,44 +169,31 @@ It will not appear in the console, but it will appear in the error log.
168169

169170
### Color the output
170171

171-
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.
172-
173-
Example:
174-
175-
```js
176-
console.log('\x1b[33m%s\x1b[0m', 'hi!');
177-
```
178-
179-
You can try that in the Node.js REPL, and it will print `hi!` in yellow.
172+
> **NOTE**
173+
> This part of the resource is designed with version 22.11 which notes `styleText` as ‘Active development’.
180174
181-
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.
175+
In many cases, you will be tempted to paste certain text to get a nice output at the terminal.
182176

183-
You install it with `npm install chalk`, then you can use it:
177+
There is a `styleText` function provided by the `node:util` module. Let's discover how to use it.
184178

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

188-
console.log(chalk.yellow('hi!'));
181+
```mjs
182+
import { styleText } from 'node:util';
189183
```
190184

191-
Using `chalk.yellow` is much more convenient than trying to remember the escape codes, and the code is much more readable.
192-
193-
Check the project link posted above for more usage examples.
194-
195-
### Create a progress bar
196-
197-
[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`
185+
```cjs
186+
const { styleText } = require('node:util');
187+
```
198188

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

201191
```js
202-
const ProgressBar = require('progress');
203-
204-
const bar = new ProgressBar(':bar', { total: 10 });
205-
const timer = setInterval(() => {
206-
bar.tick();
207-
if (bar.complete) {
208-
clearInterval(timer);
209-
}
210-
}, 100);
192+
console.log(
193+
styleText(['red'], 'This is red text ') +
194+
styleText(['green, bold'], 'and this is green bold text ') +
195+
'this is normal text'
196+
);
211197
```
198+
199+
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)

apps/site/pages/en/learn/command-line/run-nodejs-scripts-from-the-command-line.md

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ If your main Node.js application file is `app.js`, you can call it by typing:
1414
node app.js
1515
```
1616

17-
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:
17+
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:
1818

1919
```js
2020
#!/usr/bin/node
@@ -48,12 +48,58 @@ node -e "console.log(123)"
4848

4949
## Restart the application automatically
5050

51-
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.
52-
To use this feature, you need to pass the `--watch' flag to nodejs.
51+
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.
52+
To use this feature, you need to pass the `--watch` flag to Node.js.
5353

5454
```bash
5555
node --watch app.js
5656
```
5757

5858
So when you change the file, the application will restart automatically.
59-
Read the [`--watch` flag documentation](https://nodejs.org/docs/latest/api/cli.html#--watch).
59+
Read the [`--watch` flag documentation](https://nodejs.org/docs/latest-v22.x/api/cli.html#--watch).
60+
61+
## Run a task with Node.js
62+
63+
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.
64+
65+
### Using the `--run` flag
66+
67+
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`:
68+
69+
```json
70+
{
71+
"type": "module",
72+
"scripts": {
73+
"start": "node app.js",
74+
"dev": "node --run -- --watch",
75+
"test": "node --test"
76+
}
77+
}
78+
```
79+
80+
You can run the `test` script using the `--run` flag:
81+
82+
```bash
83+
node --run test
84+
```
85+
86+
### Passing arguments to the command
87+
88+
Let's explain the `dev` key in the `scripts` object of the `package.json` file.
89+
90+
The syntax `-- --another-argument` is used to pass arguments to the command. In this case, the `--watch` argument is passed to the `dev` script.
91+
92+
```bash
93+
node --run dev
94+
```
95+
96+
### Environment variables
97+
98+
The `--run` flag sets specific environment variables that can be useful for your scripts:
99+
100+
- `NODE_RUN_SCRIPT_NAME`: The name of the script being run.
101+
- `NODE_RUN_PACKAGE_JSON_PATH`: The path to the `package.json` file being processed.
102+
103+
### Intentional limitations
104+
105+
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.

0 commit comments

Comments
 (0)