Skip to content

Commit 9137ea6

Browse files
authored
fix: add missing ESM/CJS tabs with their examples in Learn section (#8619)
1 parent 70b57c5 commit 9137ea6

File tree

8 files changed

+298
-20
lines changed

8 files changed

+298
-20
lines changed

apps/site/pages/en/learn/asynchronous-work/event-loop-timers-and-nexttick.md

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ For example, say you schedule a timeout to execute after a 100 ms
110110
threshold, then your script starts asynchronously reading a file which
111111
takes 95 ms:
112112

113-
```js
113+
```cjs
114114
const fs = require('node:fs');
115115

116116
function someAsyncOperation(callback) {
@@ -137,6 +137,33 @@ someAsyncOperation(() => {
137137
});
138138
```
139139

140+
```mjs
141+
import fs from 'node:fs';
142+
143+
function someAsyncOperation(callback) {
144+
// Assume this takes 95ms to complete
145+
fs.readFile('/path/to/file', callback);
146+
}
147+
148+
const timeoutScheduled = Date.now();
149+
150+
setTimeout(() => {
151+
const delay = Date.now() - timeoutScheduled;
152+
153+
console.log(`${delay}ms have passed since I was scheduled`);
154+
}, 100);
155+
156+
// do someAsyncOperation which takes 95 ms to complete
157+
someAsyncOperation(() => {
158+
const startCallback = Date.now();
159+
160+
// do something that will take 10ms...
161+
while (Date.now() - startCallback < 10) {
162+
// do nothing
163+
}
164+
});
165+
```
166+
140167
When the event loop enters the **poll** phase, it has an empty queue
141168
(`fs.readFile()` has not completed), so it will wait for the number of ms
142169
remaining until the soonest timer's threshold is reached. While it is
@@ -259,7 +286,7 @@ timeout
259286
However, if you move the two calls within an I/O cycle, the immediate
260287
callback is always executed first:
261288

262-
```js
289+
```cjs
263290
// timeout_vs_immediate.js
264291
const fs = require('node:fs');
265292

@@ -273,6 +300,20 @@ fs.readFile(__filename, () => {
273300
});
274301
```
275302

303+
```mjs
304+
// timeout_vs_immediate.js
305+
import fs from 'node:fs';
306+
307+
fs.readFile(import.meta.filename, () => {
308+
setTimeout(() => {
309+
console.log('timeout');
310+
}, 0);
311+
setImmediate(() => {
312+
console.log('immediate');
313+
});
314+
});
315+
```
316+
276317
```bash
277318
$ node timeout_vs_immediate.js
278319
immediate
@@ -453,7 +494,7 @@ allowing the connection event to be fired before the listening event.
453494
Another example is extending an `EventEmitter` and emitting an
454495
event from within the constructor:
455496

456-
```js
497+
```cjs
457498
const EventEmitter = require('node:events');
458499

459500
class MyEmitter extends EventEmitter {
@@ -469,13 +510,30 @@ myEmitter.on('event', () => {
469510
});
470511
```
471512

513+
```mjs
514+
import EventEmitter from 'node:events';
515+
516+
class MyEmitter extends EventEmitter {
517+
constructor() {
518+
super();
519+
this.emit('event');
520+
}
521+
}
522+
523+
const myEmitter = new MyEmitter();
524+
myEmitter.on('event', () => {
525+
console.log('an event occurred!');
526+
});
527+
```
528+
472529
You can't emit an event from the constructor immediately
530+
473531
because the script will not have processed to the point where the user
474532
assigns a callback to that event. So, within the constructor itself,
475533
you can use `process.nextTick()` to set a callback to emit the event
476534
after the constructor has finished, which provides the expected results:
477535

478-
```js
536+
```cjs
479537
const EventEmitter = require('node:events');
480538

481539
class MyEmitter extends EventEmitter {
@@ -495,5 +553,25 @@ myEmitter.on('event', () => {
495553
});
496554
```
497555

556+
```mjs
557+
import EventEmitter from 'node:events';
558+
559+
class MyEmitter extends EventEmitter {
560+
constructor() {
561+
super();
562+
563+
// use nextTick to emit the event once a handler is assigned
564+
process.nextTick(() => {
565+
this.emit('event');
566+
});
567+
}
568+
}
569+
570+
const myEmitter = new MyEmitter();
571+
myEmitter.on('event', () => {
572+
console.log('an event occurred!');
573+
});
574+
```
575+
498576
[libuv]: https://libuv.org/
499577
[REPL]: https://nodejs.org/api/repl.html#repl_repl

apps/site/pages/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ How do you handle errors with callbacks? One very common strategy is to use what
9696

9797
If there is no error, the object is `null`. If there is an error, it contains some description of the error and other information.
9898

99-
```js
99+
```cjs
100100
const fs = require('node:fs');
101101

102102
fs.readFile('/file.json', (err, data) => {
@@ -111,6 +111,21 @@ fs.readFile('/file.json', (err, data) => {
111111
});
112112
```
113113

114+
```mjs
115+
import fs from 'node:fs';
116+
117+
fs.readFile('/file.json', (err, data) => {
118+
if (err) {
119+
// handle error
120+
console.log(err);
121+
return;
122+
}
123+
124+
// no errors, process data
125+
console.log(data);
126+
});
127+
```
128+
114129
### The problem with callbacks
115130

116131
Callbacks are great for simple cases!

apps/site/pages/en/learn/asynchronous-work/overview-of-blocking-vs-non-blocking.md

Lines changed: 74 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,15 +39,21 @@ execute **asynchronously**.
3939

4040
Using the File System module as an example, this is a **synchronous** file read:
4141

42-
```js
42+
```cjs
4343
const fs = require('node:fs');
4444

4545
const data = fs.readFileSync('/file.md'); // blocks here until file is read
4646
```
4747

48+
```mjs
49+
import fs from 'node:fs';
50+
51+
const data = fs.readFileSync('/file.md'); // blocks here until file is read
52+
```
53+
4854
And here is an equivalent **asynchronous** example:
4955

50-
```js
56+
```cjs
5157
const fs = require('node:fs');
5258

5359
fs.readFile('/file.md', (err, data) => {
@@ -57,6 +63,16 @@ fs.readFile('/file.md', (err, data) => {
5763
});
5864
```
5965

66+
```mjs
67+
import fs from 'node:fs';
68+
69+
fs.readFile('/file.md', (err, data) => {
70+
if (err) {
71+
throw err;
72+
}
73+
});
74+
```
75+
6076
The first example appears simpler than the second but has the disadvantage of
6177
the second line **blocking** the execution of any additional JavaScript until
6278
the entire file is read. Note that in the synchronous version if an error is
@@ -66,17 +82,25 @@ shown.
6682

6783
Let's expand our example a little bit:
6884

69-
```js
85+
```cjs
7086
const fs = require('node:fs');
7187

7288
const data = fs.readFileSync('/file.md'); // blocks here until file is read
7389
console.log(data);
7490
moreWork(); // will run after console.log
7591
```
7692

93+
```mjs
94+
import fs from 'node:fs';
95+
96+
const data = fs.readFileSync('/file.md'); // blocks here until file is read
97+
console.log(data);
98+
moreWork(); // will run after console.log
99+
```
100+
77101
And here is a similar, but not equivalent asynchronous example:
78102

79-
```js
103+
```cjs
80104
const fs = require('node:fs');
81105

82106
fs.readFile('/file.md', (err, data) => {
@@ -89,6 +113,19 @@ fs.readFile('/file.md', (err, data) => {
89113
moreWork(); // will run before console.log
90114
```
91115

116+
```mjs
117+
import fs from 'node:fs';
118+
119+
fs.readFile('/file.md', (err, data) => {
120+
if (err) {
121+
throw err;
122+
}
123+
124+
console.log(data);
125+
});
126+
moreWork(); // will run before console.log
127+
```
128+
92129
In the first example above, `console.log` will be called before `moreWork()`. In
93130
the second example `fs.readFile()` is **non-blocking** so JavaScript execution
94131
can continue and `moreWork()` will be called first. The ability to run
@@ -118,7 +155,7 @@ threads may be created to handle concurrent work.
118155
There are some patterns that should be avoided when dealing with I/O. Let's look
119156
at an example:
120157

121-
```js
158+
```cjs
122159
const fs = require('node:fs');
123160

124161
fs.readFile('/file.md', (err, data) => {
@@ -131,12 +168,25 @@ fs.readFile('/file.md', (err, data) => {
131168
fs.unlinkSync('/file.md');
132169
```
133170

171+
```mjs
172+
import fs from 'node:fs';
173+
174+
fs.readFile('/file.md', (err, data) => {
175+
if (err) {
176+
throw err;
177+
}
178+
179+
console.log(data);
180+
});
181+
fs.unlinkSync('/file.md');
182+
```
183+
134184
In the above example, `fs.unlinkSync()` is likely to be run before
135185
`fs.readFile()`, which would delete `file.md` before it is actually read. A
136186
better way to write this, which is completely **non-blocking** and guaranteed to
137187
execute in the correct order is:
138188

139-
```js
189+
```cjs
140190
const fs = require('node:fs');
141191

142192
fs.readFile('/file.md', (readFileErr, data) => {
@@ -154,6 +204,24 @@ fs.readFile('/file.md', (readFileErr, data) => {
154204
});
155205
```
156206

207+
```mjs
208+
import fs from 'node:fs';
209+
210+
fs.readFile('/file.md', (readFileErr, data) => {
211+
if (readFileErr) {
212+
throw readFileErr;
213+
}
214+
215+
console.log(data);
216+
217+
fs.unlink('/file.md', unlinkErr => {
218+
if (unlinkErr) {
219+
throw unlinkErr;
220+
}
221+
});
222+
});
223+
```
224+
157225
The above places a **non-blocking** call to `fs.unlink()` within the callback of
158226
`fs.readFile()` which guarantees the correct order of operations.
159227

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Because this method is invoked post-initialization, the setting of startup-relat
8080
PORT=1234
8181
```
8282

83-
```js
83+
```cjs
8484
const { loadEnvFile } = require('node:process');
8585

8686
// Loads environment variables from the default .env file
@@ -89,9 +89,23 @@ loadEnvFile();
8989
console.log(process.env.PORT); // Logs '1234'
9090
```
9191

92+
```mjs
93+
import { loadEnvFile } from 'node:process';
94+
95+
// Loads environment variables from the default .env file
96+
loadEnvFile();
97+
98+
console.log(process.env.PORT); // Logs '1234'
99+
```
100+
92101
You can also specify a custom path:
93102

94-
```js
103+
```cjs
95104
const { loadEnvFile } = require('node:process');
96105
loadEnvFile('./config/.env');
97106
```
107+
108+
```mjs
109+
import { loadEnvFile } from 'node:process';
110+
loadEnvFile('./config/.env');
111+
```

apps/site/pages/en/learn/diagnostics/memory/understanding-and-tuning-memory.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,14 @@ const heapSizeInGB = heap_size_limit / (1024 * 1024 * 1024);
3636
console.log(`${heapSizeInGB} GB`);
3737
```
3838

39+
```mjs
40+
import v8 from 'node:v8';
41+
const { heap_size_limit } = v8.getHeapStatistics();
42+
const heapSizeInGB = heap_size_limit / (1024 * 1024 * 1024);
43+
44+
console.log(`${heapSizeInGB} GB`);
45+
```
46+
3947
This will output the maximum heap size in gigabytes, which is based on your system's available memory.
4048

4149
### The Stack

0 commit comments

Comments
 (0)