### Output from starting the server Source: https://nodejs.org/dist/latest/docs/api/async_hooks.html This is the output produced by the async_hooks example when the server starts. It shows the sequence of init, before, after, and destroy calls, and the executionAsyncId value logged after a timeout. ```text TCPSERVERWRAP(5): trigger: 1 execution: 1 TickObject(6): trigger: 5 execution: 1 before: 6 Timeout(7): trigger: 6 execution: 6 after: 6 destroy: 6 before: 7 >>> 7 TickObject(8): trigger: 7 execution: 7 after: 7 before: 8 after: 8 ``` -------------------------------- ### session.post('Profiler.start', callback) Source: https://nodejs.org/dist/latest/docs/api/inspector.json Starts the CPU Profiler via the DevTools protocol. This is part of the example usage for the CPU profiler. ```APIDOC ## Method: session.post('Profiler.start', callback) ### Description Starts the CPU Profiler via the DevTools protocol. This is part of the example usage for the CPU profiler. ### Method POST ### Endpoint Profiler.start ### Parameters - **callback** (Function) - Optional callback function. ### Request Example ```js session.post('Profiler.start', () => { // ... }); ``` ### Response No response body is documented. ``` -------------------------------- ### ESM example using createTagStore Source: https://nodejs.org/dist/latest/docs/api/sqlite.html Complete example using import { Database } from 'node:sqlite' to create a tag store, insert data with run, retrieve with get and all. ```javascript import { Database } from 'node:sqlite'; const db = new Database(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ] ``` -------------------------------- ### v8.startHeapProfile() basic usage in ES modules Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a heap profile and returns a SyncHeapProfileHandle. This example uses import v8 from 'node:v8' and calls handle.stop() to get the profile. ```mjs import v8 from 'node:v8'; const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` -------------------------------- ### CPU profiler example Source: https://nodejs.org/dist/latest/docs/api/inspector.json Shows how to use the CPU Profiler via the inspector session: enable, start, stop, and write the profile to disk. ```javascript const inspector = require('node:inspector'); const fs = require('node:fs'); const session = new inspector.Session(); session.connect(); session.post('Profiler.enable', () => { session.post('Profiler.start', () => { // Invoke business logic under measurement here... // some time later... session.post('Profiler.stop', (err, { profile }) => { // Write profile to disk, upload, etc. if (!err) { fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile)); } }); }); }); ``` -------------------------------- ### CommonJS example using createTagStore Source: https://nodejs.org/dist/latest/docs/api/sqlite.html Complete example using require('node:sqlite') to create a tag store, insert data with run, retrieve with get and all. ```javascript const { Database } = require('node:sqlite'); const db = new Database(':memory:'); const sql = db.createTagStore(); db.exec('CREATE TABLE users (id INT, name TEXT)'); // Using the 'run' method to insert data. // The tagged literal is used to identify the prepared statement. sql.run`INSERT INTO users VALUES (1, 'Alice')`; sql.run`INSERT INTO users VALUES (2, 'Bob')`; // Using the 'get' method to retrieve a single row. const name = 'Alice'; const user = sql.get`SELECT * FROM users WHERE name = ${name}`; console.log(user); // { id: 1, name: 'Alice' } // Using the 'all' method to retrieve all rows. const allUsers = sql.all`SELECT * FROM users ORDER BY id`; console.log(allUsers); // [ // { id: 1, name: 'Alice' }, // { id: 2, name: 'Bob' } // ] ``` -------------------------------- ### Example benchmark using suite and bench Source: https://nodejs.org/dist/latest/docs/api/bench.html Example benchmark saved as benchmark.mjs. It defines a suite named 'URL' with a bench named 'construct' that measures URL construction. The bench uses 30 samples and a parameter input set to 'short'. The benchmark manually starts and ends the timing, and throws an error if the result is unexpected. ```javascript import { bench, suite } from 'node:bench'; suite('URL', () => { const input = 'https://example.com/a?b=c'; bench('construct', { samples: 30, params: { input: 'short' }, }, (b) => { const operations = 10_000; let totalLength = 0; b.start(); for (let i = 0; i < operations; i++) { totalLength += new URL(input).href.length; } b.end(operations); if (totalLength !== operations * input.length) { throw new Error('Unexpected URL result'); } }); }); ``` -------------------------------- ### v8.startHeapProfile() with custom parameters in ES modules Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a heap profile with custom parameters: sampleInterval, stackDepth, forceGC, and includeObjectsCollectedByMajorGC. Uses import v8 from 'node:v8' and calls handle.stop() to get the profile. ```mjs import v8 from 'node:v8'; const handle = v8.startHeapProfile({ sampleInterval: 1024, stackDepth: 8, forceGC: true, includeObjectsCollectedByMajorGC: true, }); const profile = handle.stop(); console.log(profile); ``` -------------------------------- ### repl.start() Source: https://nodejs.org/dist/latest/docs/api/repl.json Creates and starts a REPLServer instance. If options is a string, it specifies the input prompt. ```APIDOC ## repl.start() ### Description Creates and starts a `repl.REPLServer` instance. If `options` is a string, it specifies the input prompt. ### Method `repl.start()` ### Parameters #### Options (object or string) - **options** (object) - Optional - Configuration options for the REPL server. - **prompt** (string) - Optional - The input prompt to display. - **ignoreErrors** (boolean) - Optional - If `true`, prevents the REPL from emitting errors. - **eval** (function) - Optional - Custom evaluation function. - **writer** (function) - Optional - Custom writer function. - **terminal** (boolean) - Optional - If `true`, the REPL uses terminal mode. - **useGlobal** (boolean) - Optional - If `true`, uses the global object. - **useColors** (boolean) - Optional - If `true`, enables color output. - **historySize** (number) - Optional - Maximum number of history entries. - **removeHistoryDuplicates** (boolean) - Optional - If `true`, removes duplicate history entries. - **history** (array) - Optional - Initial history array. - **breakEvalOnSigint** (boolean) - Optional - If `true`, breaks evaluation on SIGINT. - **preview** (boolean) - Optional - If `true`, enables preview. - **replMode** (string) - Optional - Mode for the REPL: `'strict'`, `'sloppy'`, or `'default'`. - **forceFlush** (boolean) - Optional - If `true`, forces flushing of output. - **errorHandler** (function) - Optional - Custom error handler. The function receives an error and can return a value to handle the error. Possible return values: - `'ignore'` - Skip all remaining error handling. - `'unhandled'` - Treat the exception as fully unhandled, passing it to process-wide exception handlers. ### Return Returns: `repl.REPLServer` - The created REPL server instance. ### Example ```js import repl from 'node:repl'; // a Unix style prompt repl.start('$ '); ``` ```js const repl = require('node:repl'); // a Unix style prompt repl.start('$ '); ``` ``` -------------------------------- ### Start CPU profile with v8.startCpuProfile Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a CPU profile with sampleInterval of 1 ms and maxBufferSize of 10,000 samples. Returns a SyncCPUProfileHandle that supports the `using` syntax. Stops the profile and logs the result. ```cjs const handle = v8.startCpuProfile({ sampleInterval: 1, maxBufferSize: 10_000 }); const profile = handle.stop(); console.log(profile); ``` -------------------------------- ### v8.startHeapProfile() basic usage in CommonJS Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a heap profile and returns a SyncHeapProfileHandle. The handle supports the `using` syntax. This example uses require('node:v8') and calls handle.stop() to get the profile. ```cjs const v8 = require('node:v8'); const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` -------------------------------- ### repl.start([options]) Source: https://nodejs.org/dist/latest/docs/api/repl.json Starts a REPL server with the provided options. This method is used to create a REPL instance programmatically. ```APIDOC ## repl.start([options]) ### Description Starts a REPL server with the provided options. ### Method start ### Parameters #### Options - **options** (Object) - Optional - Configuration options for the REPL server. ### Returns - **repl.REPLServer** - The created REPL server instance. ### Example ```js const repl = require('repl'); repl.start({ prompt: '> ' }); ``` ``` -------------------------------- ### response.socket example (CommonJS) Source: https://nodejs.org/dist/latest/docs/api/http2.html Shows how to use response.socket to get the remote address and port. This example uses require syntax. ```javascript const http2 = require('node:http2'); const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` -------------------------------- ### response.socket example (ES modules) Source: https://nodejs.org/dist/latest/docs/api/http2.html Shows how to use response.socket to get the remote address and port. This example uses import syntax. ```javascript import { createServer } from 'node:http2'; const server = createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); ``` -------------------------------- ### v8.startCpuProfile([options]) Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a CPU profile and returns a SyncCPUProfileHandle object. This API supports the `using` syntax for automatic resource management. ```APIDOC ## v8.startCpuProfile([options]) ### Description Starts a CPU profile and returns a SyncCPUProfileHandle object. This API supports the `using` syntax for automatic resource management. ### Method Function ### Signature `startCpuProfile([options])` ### Parameters #### Options (Object, Optional) - **sampleInterval** (number) - Optional - Requested sampling interval in milliseconds. Default: `0`. - **maxBufferSize** (integer) - Optional - Maximum number of samples to keep before older entries are discarded. Default: `4294967295`. ### Returns - **SyncCPUProfileHandle** - A handle to the started CPU profile. ### Example ```cjs const handle = v8.startCpuProfile({ sampleInterval: 1, maxBufferSize: 10_000 }); const profile = handle.stop(); console.log(profile); ``` ``` -------------------------------- ### repl.start(options) Source: https://nodejs.org/dist/latest/docs/api/repl.json Starts a REPL server instance. This method is used to create a REPLServer instance with the provided options. ```APIDOC ## repl.start(options) ### Description Starts a REPL server instance. The options parameter can be an object or a string. When a string is provided, it is treated as the prompt. This method is the primary way to create a REPLServer instance. ### Method start ### Parameters #### Options Object - **prompt** (string) - Optional - The prompt to display for the REPL session - **input** (stream.Readable) - Optional - The readable stream to use as input - **output** (stream.Writable) - Optional - The writable stream to use as output - **terminal** (boolean) - Optional - Whether the stream is a terminal - **useColors** (boolean) - Optional - Whether to use ANSI colors - **useGlobal** (boolean) - Optional - Whether to use the global scope ### Example ```mjs import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); ``` ```cjs const repl = require('node:repl'); const options = { useColors: true }; const firstInstance = repl.start(options); ``` ``` -------------------------------- ### getCallSites() CJS example Source: https://nodejs.org/dist/latest/docs/api/util.html Uses require('node:util') to get getCallSites and logs the same call site properties. This is the CommonJS equivalent of the ESM example. ```javascript const { getCallSites } = require('node:util'); function exampleFunction() { const callSites = getCallSites(); console.log('Call Sites:'); callSites.forEach((callSite, index) => { console.log(`CallSite ${index + 1}:`); console.log(`Function Name: ${callSite.functionName}`); console.log(`Script Name: ${callSite.scriptName}`); console.log(`Line Number: ${callSite.lineNumber}`); console.log(`Column Number: ${callSite.columnNumber}`); }); // CallSite 1: // Function Name: exampleFunction // Script Name: /home/example.js // Line Number: 5 // Column Number: 26 // CallSite 2: // Function Name: anotherFunction // Script Name: /home/example.js // Line Number: 22 // Column Number: 3 // ... } // A function to simulate another stack layer function anotherFunction() { exampleFunction(); } anotherFunction(); ``` -------------------------------- ### repl.start(options) Source: https://nodejs.org/dist/latest/docs/api/repl.json Creates and starts a REPL instance with the specified options. This method is the primary entry point for programmatically launching a REPL session. ```APIDOC ## repl.start(options) ### Description Creates and starts a REPL instance using the provided options. This is the primary method for programmatically launching a Node.js REPL session. ### Method start ### Signature `repl.start(options)` ### Parameters #### Options - **prompt** (string) - Optional - The input prompt to display. Default: `'> '` (with a trailing space). - **input** (stream.Readable) - Optional - The `Readable` stream from which REPL input will be read. Default: `process.stdin`. - **output** (stream.Writable) - Optional - The `Writable` stream to which REPL output will be written. Default: `process.stdout`. - **terminal** (boolean) - Optional - If `true`, specifies that the `output` should be treated as a TTY terminal. Default: checking the value of the `isTTY` property on the `output` stream upon instantiation. - **eval** (Function) - Optional - The function to be used when evaluating each given line of input. Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines. - **useColors** (boolean) - Optional - If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect. Default: checking color support on the `output` stream if the REPL instance's `terminal` value is `true`. - **useGlobal** (boolean) - Optional - If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`. Default: `false`. - **ignoreUndefined** (boolean) - Optional - If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. Default: `false`. - **writer** (Function) - Optional - The function to invoke for each command that gets evaluated. Default: `util.inspect()`. - **completer** (Function) - Optional - An optional function used for custom Tab auto completion. See the custom completion section for more details. - **replMode** {symbol} - Optional - A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode, default mode, or a hybrid ("magic") mode. Acceptable values are: `repl.REPL_MODE_SLOPPY`, `repl.REPL_MODE_STRICT`, and `repl.REPL_MODE_MAGIC` (deprecated). Default: `repl.REPL_MODE_SLOPPY`. - **breakEvalOnSigint** {boolean} - Optional - Stop evaluating the current piece of code when `SIGINT` is received, such as when Ctrl+C is pressed. This cannot be used together with a custom `eval` function. **Default:** `false`. - **preview** {boolean} - Optional - If `true`, the REPL uses tab completion and interactive exploration to provide previews for input. **Default:** `true` unless `terminal` is `false`. If `false`, the preview feature is disabled. This option is not available in the built-in Node.js REPL. ``` -------------------------------- ### Start Node.js REPL and execute JavaScript Source: https://nodejs.org/dist/latest/docs/api/repl.json Shows how to start the Node.js REPL by running the node binary without arguments. Demonstrates defining an array, inspecting it, and using forEach to print elements. ```console $ node > const a = [1, 2, 3]; undefined > a [ 1, 2, 3 ] > a.forEach((v) => { ... console.log(v); ... }); 1 2 3 ``` -------------------------------- ### v8.startHeapProfile([options]) Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a heap profile and returns a handle. The options include sampleInterval for the average sampling interval in bytes. ```APIDOC ## v8.startHeapProfile([options]) ### Description Starts a heap profile and returns a handle. The options include sampleInterval for the average sampling interval in bytes. ### Method Function ### Signature `startHeapProfile([options])` ### Parameters #### Options (Object, Optional) - **sampleInterval** (number) - Optional - The average sampling interval in bytes. Default: `524288` (512 KiB). ### Returns - **SyncHeapProfileHandle** - A handle to the started heap profile. ### Example (No example provided in source.) ``` -------------------------------- ### Read last 10 bytes of a file using start and end options Source: https://nodejs.org/dist/latest/docs/api/fs.html Example that reads the last 10 bytes of a 100-byte file by setting start to 90 and end to 99. Both start and end are inclusive and zero-based. ```javascript import { createReadStream } from 'node:fs'; createReadStream('sample.txt', { start: 90, end: 99 }); ``` -------------------------------- ### Create REPLServer instances with repl.start() and new (ES modules) Source: https://nodejs.org/dist/latest/docs/api/repl.json Shows two ways to create a REPLServer instance: using repl.start(options) and using new repl.REPLServer(options). Calling repl.REPLServer() without the new keyword throws a TypeError (see DEP0185). ```mjs import repl from 'node:repl'; const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -------------------------------- ### Get and set mime.subtype property Source: https://nodejs.org/dist/latest/docs/api/util.html Demonstrates getting and setting the subtype portion of a MIME. Changing the subtype updates the serialized MIME. Both ESM and CommonJS examples are provided. ```javascript import { MIMEType } from 'node:util'; const myMIME = new MIMEType('text/ecmascript'); console.log(myMIME.subtype); // Prints: ecmascript myMIME.subtype = 'javascript'; console.log(myMIME.subtype); // Prints: javascript console.log(String(myMIME)); // Prints: text/javascript ``` ```javascript const { MIMEType } = require('node:util'); const myMIME = new MIMEType('text/ecmascript'); console.log(myMIME.subtype); // Prints: ecmascript myMIME.subtype = 'javascript'; console.log(myMIME.subtype); // Prints: javascript console.log(String(myMIME)); // Prints: text/javascript ``` -------------------------------- ### Get and set mime.type property Source: https://nodejs.org/dist/latest/docs/api/util.html Demonstrates getting and setting the type portion of a MIME. Changing the type updates the serialized MIME. Both ESM and CommonJS examples are provided. ```javascript import { MIMEType } from 'node:util'; const myMIME = new MIMEType('text/javascript'); console.log(myMIME.type); // Prints: text myMIME.type = 'application'; console.log(myMIME.type); // Prints: application console.log(String(myMIME)); // Prints: application/javascript ``` ```javascript const { MIMEType } = require('node:util'); const myMIME = new MIMEType('text/javascript'); console.log(myMIME.type); // Prints: text myMIME.type = 'application'; console.log(myMIME.type); // Prints: application console.log(String(myMIME)); // Prints: application/javascript ``` -------------------------------- ### Create REPLServer instances with repl.start() and new (CommonJS) Source: https://nodejs.org/dist/latest/docs/api/repl.json Shows two ways to create a REPLServer instance: using repl.start(options) and using new repl.REPLServer(options). Calling repl.REPLServer() without the new keyword throws a TypeError (see DEP0185). ```cjs const repl = require('node:repl'); const options = { useColors: true }; const firstInstance = repl.start(options); const secondInstance = new repl.REPLServer(options); ``` -------------------------------- ### Heap profiler example Source: https://nodejs.org/dist/latest/docs/api/inspector.json Shows how to use the Heap Profiler: connect, listen for heap snapshot chunks, take a snapshot, and write it to a file. ```javascript const inspector = require('node:inspector'); const fs = require('node:fs'); const session = new inspector.Session(); const fd = fs.openSync('profile.heapsnapshot', 'w'); session.connect(); session.on('HeapProfiler.addHeapSnapshotChunk', (m) => { fs.writeSync(fd, m.params.chunk); }); session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => { console.log('HeapProfiler.takeHeapSnapshot done:', err, r); session.disconnect(); fs.closeSync(fd); }); ``` -------------------------------- ### Exports targets must be relative URLs (package.json) Source: https://nodejs.org/dist/latest/docs/api/packages.json Shows a valid "exports" map with targets starting with './', and commented-out incorrect examples that start with '/', 'file:///', or '../'. These are invalid because targets must be relative URLs starting with './'. ```json // package.json { "name": "my-package", "exports": { ".": "./dist/main.js", // Correct "./feature": "./lib/feature.js", // Correct // "./origin-relative": "/dist/main.js", // Incorrect: Must start with ./ // "./absolute": "file:///dev/null", // Incorrect: Must start with ./ // "./outside": "../common/util.js" // Incorrect: Must start with ./ } } ``` -------------------------------- ### v8.startHeapProfile([options]) Source: https://nodejs.org/dist/latest/docs/api/v8.json Starts a heap profile and returns a SyncHeapProfileHandle object. This API supports the `using` syntax. Optional parameters allow customization of the sampling interval, stack depth, and garbage collection behavior. ```APIDOC ## v8.startHeapProfile([options]) ### Description Starts a heap profile and returns a `SyncHeapProfileHandle` object. This API supports `using` syntax. ### Method `startHeapProfile` ### Parameters #### Optional Parameters - **sampleInterval** (number) - Optional - The average sampling interval in bytes. Default: `524288` (512 KiB). - **stackDepth** (integer) - Optional - The maximum stack depth for samples. Default: `16`. - **forceGC** (boolean) - Optional - Force garbage collection before taking the profile. Default: `false`. - **includeObjectsCollectedByMajorGC** (boolean) - Optional - Include objects collected by major GC. Default: `false`. - **includeObjectsCollectedByMinorGC** (boolean) - Optional - Include objects collected by minor GC. Default: `false`. ### Return Value Returns: {SyncHeapProfileHandle} ### Example ```cjs const v8 = require('node:v8'); const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` ```mjs import v8 from 'node:v8'; const handle = v8.startHeapProfile(); const profile = handle.stop(); console.log(profile); ``` With custom parameters: ```cjs const v8 = require('node:v8'); const handle = v8.startHeapProfile({ sampleInterval: 1024, stackDepth: 8, forceGC: true, includeObjectsCollectedByMajorGC: true, }); const profile = handle.stop(); console.log(profile); ``` ```mjs import v8 from 'node:v8'; const handle = v8.startHeapProfile({ sampleInterval: 1024, stackDepth: 8, forceGC: true, includeObjectsCollectedByMajorGC: true, }); const profile = handle.stop(); console.log(profile); ``` ``` -------------------------------- ### Start CPU profile with await using Source: https://nodejs.org/dist/latest/docs/api/worker_threads.json Starts a CPU profile using the await using syntax, which automatically stops the profile and discards it when the scope exits. The profile is not retained. ```cjs const { Worker } = require('node:worker_threads'); const w = new Worker(` const { parentPort } = require('node:worker_threads'); parentPort.on('message', () => {}); `, { eval: true }); w.on('online', async () => { // Stop profile automatically when return and profile will be discarded await using handle = await w.startCpuProfile(); }); ``` -------------------------------- ### Start and stop heap profile with Worker (MJS) Source: https://nodejs.org/dist/latest/docs/api/worker_threads.json Starts a heap profile on a worker thread and stops it to get the profile. Uses the 'online' event to trigger the profile. The worker is terminated after stopping the profile. ```mjs import { Worker } from 'node:worker_threads'; const worker = new Worker(` const { parentPort } = require('node:worker_threads'); parentPort.on('message', () => {}); `, { eval: true }); worker.on('online', async () => { const handle = await worker.startHeapProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` -------------------------------- ### server.listen(options[, callback]) Source: https://nodejs.org/dist/latest/docs/api/net.json Starts a server listening based on the provided options object. Supports handle, port, path, exclusive, readableAll, writableAll, and signal options. If no handle, port, or path is specified, an error is thrown. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening based on the provided options object. If `handle` is specified, the server adopts that pre-bound socket. If `port` is specified, it behaves like `server.listen([port[, host[, backlog]]][, callback])`. If `path` is specified, it behaves like `server.listen(path[, backlog][, callback])`. If none is specified, an error is thrown. ### Method listen ### Parameters #### Options - **handle** (net.Server) - Optional - Pre-bound socket handle. - **port** (number) - Optional - Port number to listen on. - **path** (string) - Optional - Path for IPC server. - **exclusive** (boolean) - Optional - If true, the handle is not shared; default is false. - **readableAll** (boolean) - Optional - Makes the server accessible for all users. - **writableAll** (boolean) - Optional - Makes the server accessible for all users. - **signal** (AbortSignal) - Optional - Abort signal to close the server. - **callback** (Function) - Optional - Callback function. ### Request Example ```js server.listen({ host: 'localhost', port: 80, exclusive: true, }); ``` ### Response #### Returns - **net.Server** - The server instance. ### Notes - Using the `signal` option to destroy a long-lived server as a resource cleanup mechanism is deprecated. The `signal` option remains appropriate for cancellation, externally propagated aborts, and timeouts. - If `exclusive` is true and the underlying handle is shared, the first `backlog` passed to the master process will be used. - Starting an IPC server as root may cause the server path to be inaccessible for unprivileged users. Using `readableAll` and `writableAll` will make the server accessible for all users. - If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the server. ### Example with signal ```js const controller = new AbortController(); server.listen({ host: 'localhost', port: 80, signal: controller.signal, }); // Later, when you want to close the server. controller.abort(); ``` ``` -------------------------------- ### Start and stop heap profile with Worker (CJS) Source: https://nodejs.org/dist/latest/docs/api/worker_threads.json Starts a heap profile on a worker thread and stops it to get the profile. Uses the 'online' event to trigger the profile. The worker is terminated after stopping the profile. ```cjs const { Worker } = require('node:worker_threads'); const worker = new Worker(` const { parentPort } = require('worker_threads'); parentPort.on('message', () => {}); `, { eval: true }); worker.on('online', async () => { const handle = await worker.startHeapProfile(); const profile = await handle.stop(); console.log(profile); worker.terminate(); }); ``` -------------------------------- ### Get the reserved root directory with vfs.vfsBase() Source: https://nodejs.org/dist/latest/docs/api/vfs.json Returns the directory that holds the mount points of every mounted virtual file system, which is path.join(os.devNull, 'vfs'). Reading it lists what is mounted; see 'The reserved root directory'. The example creates a virtual file system, mounts it, and then uses fs.readdirSync() on vfs.vfsBase() to list mount points and checks that the mount point starts with the base path. ```cjs const vfs = require('node:vfs'); const fs = require('node:fs'); const myVfs = vfs.create(); const mountPoint = myVfs.mount(); fs.readdirSync(vfs.vfsBase()); // The name of every mount point in it mountPoint.startsWith(vfs.vfsBase()); // true ``` -------------------------------- ### request.getHeaderNames() example Source: https://nodejs.org/dist/latest/docs/api/http.html Shows how to get an array of unique outgoing header names. All header names are returned lowercase. ```javascript request.setHeader('Foo', 'bar'); request.setHeader('Cookie', ['foo=bar', 'bar=baz']); const headerNames = request.getHeaderNames(); // headerNames === ['foo', 'cookie'] ``` -------------------------------- ### wasi.start(instance) Source: https://nodejs.org/dist/latest/docs/api/wasi.json Attempts to begin execution of the given WebAssembly instance as a WASI command by invoking its `_start()` export. Throws an exception if the instance does not have a `_start()` export, has an `_initialize()` export, lacks a `memory` export, or if `start()` is called more than once. ```APIDOC ## Method: wasi.start(instance) ### Description Attempt to begin execution of `instance` as a WASI command by invoking its `_start()` export. If `instance` does not contain a `_start()` export, or if `instance` contains an `_initialize()` export, then an exception is thrown. `start()` requires that `instance` exports a `WebAssembly.Memory` named `memory`. If `instance` does not have a `memory` export an exception is thrown. If `start()` is called more than once, an exception is thrown. ### Parameters - **instance** (WebAssembly.Instance) - Required - The WebAssembly instance to start. ### Example ```js wasi.start(instance); ``` ``` -------------------------------- ### SEA configuration file example Source: https://nodejs.org/dist/latest/docs/api/single-executable-applications.json Example JSON configuration for generating a single executable application with the --build-sea flag. Shows all top-level fields including main, mainFormat, executable, output, disableExperimentalSEAWarning, useSnapshot, useCodeCache, useVfs, vfsArchive, execArgv, execArgvExtension, and assets. Paths are relative to the current working directory if not absolute. The Node.js binary version used to produce the blob must match the one it is injected into. ```json { "main": "/path/to/bundled/script.js", "mainFormat": "commonjs", // Default: "commonjs", options: "commonjs", "module" "executable": "/path/to/node/binary", // Optional, if not specified, uses the current Node.js binary "output": "/path/to/write/the/generated/executable", "disableExperimentalSEAWarning": true, // Default: false "useSnapshot": false, // Default: false "useCodeCache": true, // Default: false "useVfs": true, // Default: false "vfsArchive": "/path/to/assets.zip", // Optional "execArgv": ["--no-warnings", "--max-old-space-size=4096"], // Optional "execArgvExtension": "env", // Default: "env", options: "none", "env", "cli" "assets": { // Optional "a.dat": "/path/to/a.dat", "b.txt": "/path/to/b.txt" } } ``` -------------------------------- ### URL.origin Source: https://nodejs.org/dist/latest/docs/api/url.json Gets the read-only serialization of the URL's origin. For example, for 'https://example.org/foo/bar?baz', the origin is 'https://example.org'. ```APIDOC ## URL.origin ### Description Gets the read-only serialization of the URL's origin. ### Type `{string}` ### Example ```js const myURL = new URL('https://example.org/foo/bar?baz'); console.log(myURL.origin); // Prints https://example.org ``` ```js const idnURL = new URL('https://測試'); console.log(idnURL.origin); // Prints https://xn--g6w251d console.log(idnURL.hostname); // Prints xn--g6w251d ``` ``` -------------------------------- ### Create and adopt a net.BoundSocket for a server Source: https://nodejs.org/dist/latest/docs/api/net.json Creates a new net.BoundSocket, reserves a port synchronously, and adopts it as a server via listen(). The port is printed before adoption. This example uses the default options (no host or path specified). ```mjs import net from 'node:net'; const bound = new net.BoundSocket(); const { port } = bound.address(); console.log(`Reserved port ${port} for server`); const server = net.createServer(); server.listen(bound); // Adopt as a server, or pass to new net.Socket() instead. ``` -------------------------------- ### Read-only mime.essence property Source: https://nodejs.org/dist/latest/docs/api/util.html Gets the essence of the MIME (type/subtype). It is read-only; use mime.type or mime.subtype to alter it. Both ESM and CommonJS examples are provided. ```javascript import { MIMEType } from 'node:util'; const myMIME = new MIMEType('text/javascript;key=value'); console.log(myMIME.essence); // Prints: text/javascript myMIME.type = 'application'; console.log(myMIME.essence); // Prints: application/javascript console.log(String(myMIME)); // Prints: application/javascript;key=value ``` ```javascript const { MIMEType } = require('node:util'); const myMIME = new MIMEType('text/javascript;key=value'); console.log(myMIME.essence); // Prints: text/javascript myMIME.type = 'application'; console.log(myMIME.essence); // Prints: application/javascript console.log(String(myMIME)); // Prints: application/javascript;key=value ``` -------------------------------- ### server.listen() Source: https://nodejs.org/dist/latest/docs/api/http.html Starts the server listening for connections. ```APIDOC ## server.listen() ### Description Starts the server listening for connections. ### Method listen ``` -------------------------------- ### Build and launch a Node.js startup snapshot Source: https://nodejs.org/dist/latest/docs/api/v8.json Commands to build and launch a Node.js process with a custom startup snapshot. The first command builds the snapshot from entry.js, the second launches a process using the snapshot. ```console $ node --snapshot-blob snapshot.blob --build-snapshot entry.js # This launches a process with the snapshot $ node --snapshot-blob snapshot.blob ``` -------------------------------- ### Use PerformanceObserver to get entries by type (CommonJS) Source: https://nodejs.org/dist/latest/docs/api/perf_hooks.json Same example as the ESM version but using require() syntax. Demonstrates the same workflow with CommonJS modules. ```cjs const { performance, PerformanceObserver, } = require('node:perf_hooks'); const obs = new PerformanceObserver((perfObserverList, observer) => { console.log(perfObserverList.getEntriesByType('mark')); /** * [ * PerformanceEntry { * name: 'test', * entryType: 'mark', * startTime: 55.897834, * duration: 0, * detail: null * }, * PerformanceEntry { * name: 'meow', * entryType: 'mark', * startTime: 56.350146, * duration: 0, * detail: null * } * ] */ performance.clearMarks(); performance.clearMeasures(); observer.disconnect(); }); obs.observe({ type: 'mark' }); performance.mark('test'); performance.mark('meow'); ``` -------------------------------- ### server.listen(options[, callback]) Source: https://nodejs.org/dist/latest/docs/api/net.json Starts a server listening using an options object. Supports properties like backlog, exclusive, handle, host, and ipv6Only. The handle option allows adopting a pre-bound BoundSocket. ```APIDOC ## server.listen(options[, callback]) ### Description Starts a server listening using an options object. The options object supports properties such as `backlog`, `exclusive`, `handle`, `host`, and `ipv6Only`. When `handle` is provided, the server adopts the already-bound socket and listens on it, ignoring `host`, `port`, and `path`. Adoption consumes the bound socket. ### Method listen ### Endpoint server.listen(options[, callback]) ### Parameters #### Path Parameters - **options** (Object) - Required - Supports the following properties: - **backlog** (number) - Optional - Common parameter of `server.listen()` functions. - **exclusive** (boolean) - Optional - Default: `false`. - **handle** (net.BoundSocket) - Optional - A pre-bound `BoundSocket`. The server adopts the already-bound socket and listens on it, ignoring `host`, `port`, and `path`. Adoption consumes the bound socket. - **host** (string) - Optional - Host name or IP address. - **ipv6Only** (boolean) - Optional - For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support. Default: `false`. - **callback** (Function) - Optional - Callback function. ### Response No response body is specified. ``` -------------------------------- ### server.closeIdleConnections() example Source: https://nodejs.org/dist/latest/docs/api/http.html Closes all connections not sending a request or waiting for a response. Starting with Node.js 19.0.0, it's not needed with server.close but is safe for backwards compatibility. The example creates a server, listens on port 8000, and after 10 seconds closes the server and idle connections. ```javascript const http = require('node:http'); const server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'Hello World!', })); }); server.listen(8000); // Close the server after 10 seconds setTimeout(() => { server.close(() => { console.log('server on port 8000 closed successfully'); }); // Closes idle connections, such as keep-alive connections. Server will close // once remaining active connections are terminated server.closeIdleConnections(); }, 10000); ``` -------------------------------- ### async_hooks example with init, before, after, destroy hooks Source: https://nodejs.org/dist/latest/docs/api/async_hooks.html This example creates an async_hooks hook that logs the lifecycle events of asynchronous resources. It uses fs.writeSync to write to stdout, and starts a TCP server to trigger the hooks. The output shows the sequence of init, before, after, and destroy calls. ```javascript import async_hooks from 'node:async_hooks'; import fs from 'node:fs'; import net from 'node:net'; import { stdout } from 'node:process'; const { fd } = stdout; let indent = 0; async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(indent); fs.writeSync( fd, `${indentStr}${type}(${asyncId}):` + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`); }, }).enable(); net.createServer(() => {}).listen(8080, () => { // Let's wait 10ms before logging the server started. setTimeout(() => { console.log('>>>', async_hooks.executionAsyncId()); }, 10); }); ``` ```javascript const async_hooks = require('node:async_hooks'); const fs = require('node:fs'); const net = require('node:net'); const { fd } = process.stdout; let indent = 0; async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(indent); fs.writeSync( fd, `${indentStr}${type}(${asyncId}):` + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`); }, }).enable(); net.createServer(() => {}).listen(8080, () => { // Let's wait 10ms before logging the server started. setTimeout(() => { console.log('>>>', async_hooks.executionAsyncId()); }, 10); }); ``` -------------------------------- ### vfs.create(provider, options) Source: https://nodejs.org/dist/latest/docs/api/vfs.json Convenience factory equivalent to new VirtualFileSystem(provider, options). Creates a new VirtualFileSystem instance with an optional provider and options. ```APIDOC ## vfs.create(provider, options) ### Description Convenience factory equivalent to `new VirtualFileSystem(provider, options)`. Creates a new VirtualFileSystem instance. ### Method Factory function ### Parameters - `provider` (VirtualProvider) - Optional - The provider to use. Default: `new MemoryProvider()`. - `options` (Object) - Optional - `emitExperimentalWarning` (boolean) - Optional - Whether to emit the experimental warning when the instance is created. Default: `true`. ### Returns - {VirtualFileSystem} ### Example ```cjs const vfs = require('node:vfs'); // Default in-memory provider const memoryVfs = vfs.create(); // Explicit provider const realVfs = vfs.create(new vfs.RealFSProvider('/tmp/vfs-root')); ``` ```