doc: fix inconsistencies in CJS code snippets

Signed-off-by: Antoine du Hamel <duhamelantoine1995@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63199
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
Reviewed-By: Ulises Gascón <ulisesgascongonzalez@gmail.com>
This commit is contained in:
Antoine du Hamel authored and GitHub committed 2026-05-10 14:16:15 +00:00
1 parent e15f90559b
commit ccab9ac506
15 files changed
+11 -137

No files matched your search

-5
View File
@@ -591,7 +591,6 @@ the error passed to the callback will be an `AbortError`:
```cjs
const { fork } = require('node:child_process');
const process = require('node:process');
if (process.argv[2] === 'child') {
setTimeout(() => {
@@ -933,7 +932,6 @@ Example of a long-running process, by detaching and also ignoring its parent
```cjs
const { spawn } = require('node:child_process');
const process = require('node:process');
const subprocess = spawn(process.argv[0], ['child_program.js'], {
detached: true,
@@ -1077,7 +1075,6 @@ pipes between the parent and child. The value is one of the following:
```cjs
const { spawn } = require('node:child_process');
const process = require('node:process');
// Child will use parent's stdios.
spawn('prg', [], { stdio: 'inherit' });
@@ -1833,7 +1830,6 @@ process to wait for the child process to exit before exiting itself.
```cjs
const { spawn } = require('node:child_process');
const process = require('node:process');
const subprocess = spawn(process.argv[0], ['child_program.js'], {
detached: true,
@@ -2289,7 +2285,6 @@ the child and the parent processes.
```cjs
const { spawn } = require('node:child_process');
const process = require('node:process');
const subprocess = spawn(process.argv[0], ['child_program.js'], {
detached: true,
-3
View File
@@ -49,7 +49,6 @@ if (cluster.isPrimary) {
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
const process = require('node:process');
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
@@ -318,7 +317,6 @@ if (cluster.isPrimary) {
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
const process = require('node:process');
if (cluster.isPrimary) {
@@ -541,7 +539,6 @@ if (cluster.isPrimary) {
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
const process = require('node:process');
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
-6
View File
@@ -1682,7 +1682,6 @@ setImmediate(() => {
```
```cjs
'use strict';
const { eventLoopUtilization } = require('node:perf_hooks');
const { spawnSync } = require('node:child_process');
@@ -2132,7 +2131,6 @@ setTimeout(() => {}, 1000);
```
```cjs
'use strict';
const async_hooks = require('node:async_hooks');
const {
performance,
@@ -2202,7 +2200,6 @@ await timedImport('some-module');
<!-- eslint-disable no-global-assign -->
```cjs
'use strict';
const {
performance,
PerformanceObserver,
@@ -2259,7 +2256,6 @@ createServer((req, res) => {
```
```cjs
'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const http = require('node:http');
@@ -2301,7 +2297,6 @@ createServer((socket) => {
```
```cjs
'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const net = require('node:net');
const obs = new PerformanceObserver((items) => {
@@ -2335,7 +2330,6 @@ promises.resolve('localhost');
```
```cjs
'use strict';
const { PerformanceObserver } = require('node:perf_hooks');
const dns = require('node:dns');
const obs = new PerformanceObserver((items) => {
+2 -51
View File
@@ -13,6 +13,8 @@ Node.js process.
import process from 'node:process';
```
<!-- eslint-disable no-restricted-syntax -->
```cjs
const process = require('node:process');
```
@@ -62,8 +64,6 @@ console.log('This message is displayed first.');
```
```cjs
const process = require('node:process');
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code: ', code);
});
@@ -120,8 +120,6 @@ process.on('exit', (code) => {
```
```cjs
const process = require('node:process');
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});
@@ -143,8 +141,6 @@ process.on('exit', (code) => {
```
```cjs
const process = require('node:process');
process.on('exit', (code) => {
setTimeout(() => {
console.log('This will not run');
@@ -221,8 +217,6 @@ process.on('rejectionHandled', (promise) => {
```
```cjs
const process = require('node:process');
const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
unhandledRejections.set(promise, reason);
@@ -305,7 +299,6 @@ console.log('This will not run.');
```
```cjs
const process = require('node:process');
const fs = require('node:fs');
process.on('uncaughtException', (err, origin) => {
@@ -394,8 +387,6 @@ nonexistentFunc();
```
```cjs
const process = require('node:process');
process.on('uncaughtExceptionMonitor', (err, origin) => {
MyMonitoringTool.logSync(err, origin);
});
@@ -445,8 +436,6 @@ somePromise.then((res) => {
```
```cjs
const process = require('node:process');
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
// Application specific logging, throwing an error, or other logic here
@@ -473,8 +462,6 @@ const resource = new SomeResource();
```
```cjs
const process = require('node:process');
function SomeResource() {
// Initially set the loaded status to a rejected promise
this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
@@ -526,8 +513,6 @@ process.on('warning', (warning) => {
```
```cjs
const process = require('node:process');
process.on('warning', (warning) => {
console.warn(warning.name); // Print the warning name
console.warn(warning.message); // Print the warning message
@@ -663,8 +648,6 @@ process.on('SIGTERM', handle);
```
```cjs
const process = require('node:process');
// Begin reading from stdin so the process does not exit.
process.stdin.resume();
@@ -767,8 +750,6 @@ process.addUncaughtExceptionCaptureCallback((err) => {
```
```cjs
const process = require('node:process');
process.addUncaughtExceptionCaptureCallback((err) => {
console.error('Caught exception:', err.message);
return true; // Indicates exception was handled
@@ -1218,8 +1199,6 @@ process.debugPort = 5858;
```
```cjs
const process = require('node:process');
process.debugPort = 5858;
```
@@ -1356,8 +1335,6 @@ process.on('warning', (warning) => {
```
```cjs
const process = require('node:process');
process.on('warning', (warning) => {
console.warn(warning.name); // 'Warning'
console.warn(warning.message); // 'Something happened!'
@@ -1449,8 +1426,6 @@ process.on('warning', (warning) => {
```
```cjs
const process = require('node:process');
process.on('warning', (warning) => {
console.warn(warning.name);
console.warn(warning.message);
@@ -1866,8 +1841,6 @@ if (someConditionNotMet()) {
```
```cjs
const process = require('node:process');
// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
@@ -2409,8 +2382,6 @@ if (process.getegid) {
```
```cjs
const process = require('node:process');
if (process.getegid) {
console.log(`Current gid: ${process.getegid()}`);
}
@@ -2439,8 +2410,6 @@ if (process.geteuid) {
```
```cjs
const process = require('node:process');
if (process.geteuid) {
console.log(`Current uid: ${process.geteuid()}`);
}
@@ -2469,8 +2438,6 @@ if (process.getgid) {
```
```cjs
const process = require('node:process');
if (process.getgid) {
console.log(`Current gid: ${process.getgid()}`);
}
@@ -2500,8 +2467,6 @@ if (process.getgroups) {
```
```cjs
const process = require('node:process');
if (process.getgroups) {
console.log(process.getgroups()); // [ 16, 21, 297 ]
}
@@ -2530,8 +2495,6 @@ if (process.getuid) {
```
```cjs
const process = require('node:process');
if (process.getuid) {
console.log(`Current uid: ${process.getuid()}`);
}
@@ -2736,8 +2699,6 @@ kill(process.pid, 'SIGHUP');
```
```cjs
const process = require('node:process');
process.on('SIGHUP', () => {
console.log('Got SIGHUP signal.');
});
@@ -3853,8 +3814,6 @@ if (process.getegid && process.setegid) {
```
```cjs
const process = require('node:process');
if (process.getegid && process.setegid) {
console.log(`Current gid: ${process.getegid()}`);
try {
@@ -3898,8 +3857,6 @@ if (process.geteuid && process.seteuid) {
```
```cjs
const process = require('node:process');
if (process.geteuid && process.seteuid) {
console.log(`Current uid: ${process.geteuid()}`);
try {
@@ -3943,8 +3900,6 @@ if (process.getgid && process.setgid) {
```
```cjs
const process = require('node:process');
if (process.getgid && process.setgid) {
console.log(`Current gid: ${process.getgid()}`);
try {
@@ -3988,8 +3943,6 @@ if (process.getgroups && process.setgroups) {
```
```cjs
const process = require('node:process');
if (process.getgroups && process.setgroups) {
try {
process.setgroups([501]);
@@ -4032,8 +3985,6 @@ if (process.getuid && process.setuid) {
```
```cjs
const process = require('node:process');
if (process.getuid && process.setuid) {
console.log(`Current uid: ${process.getuid()}`);
try {
-2
View File
@@ -61,7 +61,6 @@ console.log(query.all());
```
```cjs
'use strict';
const { DatabaseSync } = require('node:sqlite');
const database = new DatabaseSync(':memory:');
@@ -327,7 +326,6 @@ database.loadExtension('./base64.dylib', 'sqlite3_base64_init');
```
```cjs
'use strict';
const { DatabaseSync } = require('node:sqlite');
const database = new DatabaseSync(':memory:', { allowExtension: true });
-1
View File
@@ -851,7 +851,6 @@ test('spies on a function', () => {
```
```cjs
'use strict';
const assert = require('node:assert');
const { mock, test } = require('node:test');
-2
View File
@@ -326,8 +326,6 @@ collect();
```
```cjs
'use strict';
const { Session } = require('node:inspector');
const session = new Session();
session.connect();
-3
View File
@@ -107,7 +107,6 @@ stream.pipe(process.stdout);
```js
// Print heap snapshot to the console
const v8 = require('node:v8');
const process = require('node:process');
const stream = v8.getHeapSnapshot();
stream.pipe(process.stdout);
```
@@ -1313,8 +1312,6 @@ objects during deserialization of the snapshot. For example, if the `entry.js`
contains the following script:
```cjs
'use strict';
const fs = require('node:fs');
const zlib = require('node:zlib');
const path = require('node:path');
-1
View File
@@ -38,7 +38,6 @@ wasi.start(instance);
```
```cjs
'use strict';
const { readFile } = require('node:fs/promises');
const { WASI } = require('node:wasi');
const { argv, env } = require('node:process');
-51
View File
@@ -14,8 +14,6 @@ import worker_threads from 'node:worker_threads';
```
```cjs
'use strict';
const worker_threads = require('node:worker_threads');
```
@@ -57,8 +55,6 @@ export default function parseJSAsync(script) {
```
```cjs
'use strict';
const {
Worker,
isMainThread,
@@ -141,8 +137,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const {
Worker,
isMainThread,
@@ -182,8 +176,6 @@ console.log(isInternalThread); // true
```cjs
// loader.js
'use strict';
const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread); // true
```
@@ -196,8 +188,6 @@ console.log(isInternalThread); // false
```cjs
// main.js
'use strict';
const { isInternalThread } = require('node:worker_threads');
console.log(isInternalThread); // false
```
@@ -225,8 +215,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const { Worker, isMainThread } = require('node:worker_threads');
if (isMainThread) {
@@ -288,8 +276,6 @@ console.log(typedArray2);
```
```cjs
'use strict';
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
@@ -339,8 +325,6 @@ isMarkedAsUntransferable(pooledBuffer); // Returns true.
```
```cjs
'use strict';
const { markAsUntransferable, isMarkedAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
@@ -384,8 +368,6 @@ try {
```
```cjs
'use strict';
const { markAsUncloneable } = require('node:worker_threads');
const anyObject = { foo: 'bar' };
@@ -460,8 +442,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
@@ -553,9 +533,6 @@ channel.onmessage = channel.close;
```
```cjs
'use strict';
const process = require('node:process');
const {
postMessageToThread,
threadId,
@@ -621,8 +598,6 @@ console.log(receiveMessageOnPort(port2));
```
```cjs
'use strict';
const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });
@@ -678,8 +653,6 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
```
```cjs
'use strict';
const { Worker, SHARE_ENV } = require('node:worker_threads');
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
.once('exit', () => {
@@ -759,8 +732,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
@@ -828,8 +799,6 @@ import { locks } from 'node:worker_threads';
```
```cjs
'use strict';
const { locks } = require('node:worker_threads');
```
@@ -868,8 +837,6 @@ await locks.request('my_resource', async (lock) => {
```
```cjs
'use strict';
const { locks } = require('node:worker_threads');
locks.request('my_resource', async (lock) => {
@@ -903,8 +870,6 @@ for (const pending of snapshot.pending) {
```
```cjs
'use strict';
const { locks } = require('node:worker_threads');
locks.query().then((snapshot) => {
@@ -954,8 +919,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const {
isMainThread,
BroadcastChannel,
@@ -1064,8 +1027,6 @@ port2.postMessage({ foo: 'bar' });
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
@@ -1119,8 +1080,6 @@ port1.close();
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
@@ -1254,8 +1213,6 @@ port2.postMessage(circularData);
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
@@ -1305,8 +1262,6 @@ port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
```
```cjs
'use strict';
const { MessageChannel } = require('node:worker_threads');
const { port1, port2 } = new MessageChannel();
@@ -1569,8 +1524,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const assert = require('node:assert');
const {
Worker, MessageChannel, MessagePort, isMainThread, parentPort,
@@ -1893,8 +1846,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
@@ -2231,8 +2182,6 @@ if (isMainThread) {
```
```cjs
'use strict';
const {
Worker,
isMainThread,
-2
View File
@@ -51,7 +51,6 @@ const {
createReadStream,
createWriteStream,
} = require('node:fs');
const process = require('node:process');
const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream');
@@ -92,7 +91,6 @@ const {
createReadStream,
createWriteStream,
} = require('node:fs');
const process = require('node:process');
const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream/promises');
-1
View File
@@ -501,7 +501,6 @@ force V8 optimizations and check the counters.
```js
// Flags: --expose-internals --no-warnings --allow-natives-syntax
'use strict';
const common = require('../common');
const { internalBinding } = require('internal/test/binding');
@@ -646,7 +646,6 @@ outside the `main` function has side effects. In general, prefer putting
the code inside the `main` function if it's more than just declaration.
```js
'use strict';
const common = require('../common.js');
const { Buffer } = require('node:buffer');
@@ -698,8 +697,6 @@ The `bench` object returned by `createBenchmark` implements
benchmark HTTP servers.
```js
'use strict';
const common = require('../common.js');
const bench = common.createBenchmark(main, {
-6
View File
@@ -43,7 +43,6 @@ changes.
Let's analyze this basic test from the Node.js test suite:
```js
'use strict'; // 1
const common = require('../common'); // 2
const fixtures = require('../common/fixtures'); // 3
@@ -71,7 +70,6 @@ server.listen(0, () => { // 14
### **Lines 1-3**
```js
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
```
@@ -184,7 +182,6 @@ avoid the use of extra variables and the corresponding assertions. Let's
explain this with a real test from the test suite.
```js
'use strict';
require('../common');
const assert = require('node:assert');
const http = require('node:http');
@@ -218,7 +215,6 @@ const server = http.createServer((req, res) => {
This test could be greatly simplified by using `common.mustCall` like this:
```js
'use strict';
const common = require('../common');
const http = require('node:http');
@@ -288,8 +284,6 @@ test followed by the flags. For example, to allow a test to require some of the
A test that would require `internal/freelist` could start like this:
```js
'use strict';
// Flags: --expose-internals
require('../common');
+9
View File
@@ -21,6 +21,15 @@ export default [
selector: `CallExpression[callee.name="require"][arguments.0.type="Literal"]:matches(${builtin.map((name) => `[arguments.0.value="${name}"]`).join(',')}),ImportDeclaration:matches(${builtin.map((name) => `[source.value="${name}"]`).join(',')})`,
message: 'Use `node:` prefix.',
},
{
selector: 'Program>ExpressionStatement:first-child[expression.value="use strict"]',
message: 'Do not include "use strict" statement',
},
{
selector: 'VariableDeclarator[id.name="process"][init.callee.name="require"]' +
'[init.arguments.0.value="node:process"]',
message: 'Use global "process" in CJS snippets',
},
],
'no-undef': 'off',
'no-unused-expressions': 'off',