Skip to content

Commit

Permalink
chore(content): use as 100% new codebox (nodejs#6437)
Browse files Browse the repository at this point in the history
chore(content): use à 100% new codebox
  • Loading branch information
AugustinMauroy authored Mar 8, 2024
1 parent e590baa commit 6d79e91
Show file tree
Hide file tree
Showing 13 changed files with 606 additions and 49 deletions.
21 changes: 19 additions & 2 deletions pages/en/about/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,25 @@ scalable network applications. In the following "hello world" example, many
connections can be handled concurrently. Upon each connection, the callback is
fired, but if there is no work to be done, Node.js will sleep.

```js
const http = require('node:http');
```cjs
const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```

```mjs
import { createServer } from 'node:http';

const hostname = '127.0.0.1';
const port = 3000;
Expand Down
8 changes: 7 additions & 1 deletion pages/en/learn/asynchronous-work/the-nodejs-event-emitter.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,18 @@ This module, in particular, offers the `EventEmitter` class, which we'll use to

You initialize that using

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

const eventEmitter = new EventEmitter();
```

```mjs
import EventEmitter from 'node:events';

const eventEmitter = new EventEmitter();
```

This object exposes, among many others, the `on` and `emit` methods.

- `emit` is used to trigger an event
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,31 @@ 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.

```js
const readline = require('node:readline').createInterface({
```cjs
const readline = require('node:readline');

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

rl.question(`What's your name?`, name => {
console.log(`Hi ${name}!`);
rl.close();
});
```

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

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

readline.question(`What's your name?`, name => {
rl.question(`What's your name?`, name => {
console.log(`Hi ${name}!`);
readline.close();
rl.close();
});
```

Expand All @@ -38,7 +54,7 @@ A more complete and abstract solution is provided by the [Inquirer.js package](h

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

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

const questions = [
Expand All @@ -54,6 +70,22 @@ inquirer.prompt(questions).then(answers => {
});
```

```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.
14 changes: 7 additions & 7 deletions pages/en/learn/diagnostics/memory/using-gc-traces.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ and what is the outcome.

For the proposal of this guide, we'll use this script:

```js
```mjs
// script.mjs

import os from 'os';
import os from 'node:os';

let len = 1_000_000;
const entries = new Set();
Expand Down Expand Up @@ -246,10 +246,10 @@ our entries, we could use a file.
Let's modify our script a bit:

```js
```mjs
// script-fix.mjs
import os from 'os';
import fs from 'fs/promises';
import os from 'node:os';
import fs from 'node:fs/promises';
let len = 1_000_000;
const fileName = `entries-${Date.now()}`;
Expand Down Expand Up @@ -332,8 +332,8 @@ v8.setFlagsFromString('--notrace-gc');
In Node.js, you can use [performance hooks][] to trace
garbage collection.
```js
const { PerformanceObserver } = require('perf_hooks');
```cjs
const { PerformanceObserver } = require('node:perf_hooks');
// Create a performance observer
const obs = new PerformanceObserver(list => {
Expand Down
23 changes: 20 additions & 3 deletions pages/en/learn/getting-started/introduction-to-nodejs.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,33 @@ In Node.js the new ECMAScript standards can be used without problems, as you don

The most common example Hello World of Node.js is a web server:

```js
const http = require('node:http');
```cjs
const { createServer } = require('node:http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```

```mjs
import { createServer } from 'node:http';

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
res.end('Hello World');
});

server.listen(port, hostname, () => {
Expand Down
14 changes: 13 additions & 1 deletion pages/en/learn/getting-started/security-best-practices.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ it correctly.
Ensure that the WebServer handles socket errors properly, for instance, when a
server is created without an error handler, it will be vulnerable to DoS

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

const server = net.createServer(function (socket) {
Expand All @@ -55,6 +55,18 @@ const server = net.createServer(function (socket) {
server.listen(5000, '0.0.0.0');
```

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

const server = net.createServer(function (socket) {
// socket.on('error', console.error) // this prevents the server to crash
socket.write('Echo server\r\n');
socket.pipe(socket);
});

server.listen(5000, '0.0.0.0');
```

If a _bad request_ is performed the server could crash.

An example of a DoS attack that is not caused by the request's contents is
Expand Down
12 changes: 11 additions & 1 deletion pages/en/learn/manipulating-files/nodejs-file-paths.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Given a path, you can extract information out of it using those methods:

### Example

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

const notes = '/users/joe/notes.txt';
Expand All @@ -32,6 +32,16 @@ path.basename(notes); // notes.txt
path.extname(notes); // .txt
```

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

const notes = '/users/joe/notes.txt';

path.dirname(notes); // /users/joe
path.basename(notes); // notes.txt
path.extname(notes); // .txt
```

You can get the file name without the extension by specifying a second argument to `basename`:

```js
Expand Down
59 changes: 55 additions & 4 deletions pages/en/learn/manipulating-files/nodejs-file-stats.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Every file comes with a set of details that we can inspect using Node.js. In par

You call it passing a file path, and once Node.js gets the file details it will call the callback function you pass, with 2 parameters: an error message, and the file stats:

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

fs.stat('/Users/joe/test.txt', (err, stats) => {
Expand All @@ -21,9 +21,20 @@ fs.stat('/Users/joe/test.txt', (err, stats) => {
});
```

```mjs
import fs from 'node:fs/promises';

fs.stat('/Users/joe/test.txt', (err, stats) => {
if (err) {
console.error(err);
}
// we have access to the file stats in `stats`
});
```

Node.js also provides a sync method, which blocks the thread until the file stats are ready:

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

try {
Expand All @@ -33,6 +44,16 @@ try {
}
```

```mjs
import fs from 'node:fs/promises';

try {
const stats = fs.statSync('/Users/joe/test.txt');
} catch (err) {
console.error(err);
}
```

The file information is included in the stats variable. What kind of information can we extract using the stats?

**A lot, including:**
Expand All @@ -43,7 +64,7 @@ The file information is included in the stats variable. What kind of information

There are other advanced methods, but the bulk of what you'll use in your day-to-day programming is this.

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

fs.stat('/Users/joe/test.txt', (err, stats) => {
Expand All @@ -59,9 +80,25 @@ fs.stat('/Users/joe/test.txt', (err, stats) => {
});
```

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

fs.stat('/Users/joe/test.txt', (err, stats) => {
if (err) {
console.error(err);
return;
}

stats.isFile(); // true
stats.isDirectory(); // false
stats.isSymbolicLink(); // false
stats.size; // 1024000 //= 1MB
});
```

You can also use promise-based `fsPromises.stat()` method offered by the `fs/promises` module if you like:

```js
```cjs
const fs = require('node:fs/promises');

async function example() {
Expand All @@ -78,4 +115,18 @@ async function example() {
example();
```

```mjs
import fs from 'node:fs/promises';

try {
const stats = await fs.stat('/Users/joe/test.txt');
stats.isFile(); // true
stats.isDirectory(); // false
stats.isSymbolicLink(); // false
stats.size; // 1024000 //= 1MB
} catch (err) {
console.log(err);
}
```

You can read more about the `fs` module in the [official documentation](https://nodejs.org/api/fs.html).
Loading

0 comments on commit 6d79e91

Please sign in to comment.