### Start REPL Server with Custom Prompt (CJS)
Source: https://nodejs.org/docs/latest-v22.x/api/repl.json
Starts a REPL server instance using the input prompt specified as a string. This example uses the CommonJS syntax.
```cjs
const repl = require('node:repl');
// a Unix style prompt
repl.start('$ ');
```
--------------------------------
### Start REPL Server with Custom Prompt (MJS)
Source: https://nodejs.org/docs/latest-v22.x/api/repl.json
Starts a REPL server instance using the input prompt specified as a string. This example uses the ES Module syntax.
```mjs
import repl from 'node:repl';
// a Unix style prompt
repl.start('$ ');
```
--------------------------------
### Create and Run a Simple HTTP Server
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
This example demonstrates how to create a basic HTTP server in Node.js that responds with 'Hello, World!'. Ensure Node.js is installed and accessible from your terminal.
```javascript
const http = 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!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```
--------------------------------
### Create and Bind UDP4 Server
Source: https://nodejs.org/docs/latest-v22.x/api/dgram.json
This example demonstrates how to create a UDP4 socket, set up event listeners for errors, incoming messages, and when the server starts listening, and then bind it to a specific port. This is a common pattern for setting up a UDP server.
```mjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.error(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
```
```cjs
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.error(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
```
--------------------------------
### Primary and Worker Process Example (MJS)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Demonstrates how to set up a primary process to fork worker processes and handle basic HTTP requests. Workers will exit themselves after starting.
```mjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
import process from 'node:process';
const numCPUs = availableParallelism();
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('fork', (worker) => {
console.log('worker is dead:', worker.isDead());
});
cluster.on('exit', (worker, code, signal) => {
console.log('worker is dead:', worker.isDead());
});
} else {
// Workers can share any TCP connection. In this case, it is an HTTP server.
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Current process\n ${process.pid}`);
process.kill(process.pid);
}).listen(8000);
}
```
--------------------------------
### Cluster Output Example
Source: https://nodejs.org/docs/latest-v22.x/api/cluster.json
Shows the expected console output when running the cluster example, indicating the primary process and the started worker processes.
```console
$ node server.js
Primary 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started
```
--------------------------------
### repl.start([options])
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Starts a REPL session with optional configuration.
```APIDOC
## repl.start([options])
### Description
Starts a REPL session. The `options` object can be used to customize the REPL's behavior.
### Parameters
#### Optional Parameters
- **options** (Object) - Configuration options for the REPL session.
- **prompt** (string) - The prompt to display to the user. Defaults to `'> '`.
- **input** (ReadableStream) - The input stream. Defaults to `process.stdin`.
- **output** (WritableStream) - The output stream. Defaults to `process.stdout`.
- **terminal** (boolean) - If `true`, the REPL will assume it is running in a terminal and use terminal-specific features. Defaults to `process.stdout.isTTY`.
- **eval** (Function) - A function to use for evaluating input. Defaults to the standard JavaScript `eval`.
- **useColors** (boolean) - If `true`, the REPL will use colors for output. Defaults to `hasColors()` if available.
- **useGlobal** (boolean) - If `true`, the REPL will use the global object for evaluation. Defaults to `false`.
- **ignoreUndefined** (boolean) - If `true`, `undefined` results will not be printed. Defaults to `false`.
- **breakEvalOnSigint** (boolean) - If `true`, evaluating code will be terminated when `SIGINT` is received. Defaults to `false`.
- **defaultEval** (Function) - A function to use for default evaluation. Defaults to the standard JavaScript `eval`.
- **preview** (boolean) - If `true`, the REPL will show a preview of the evaluated expression. Defaults to `true` in newer versions.
### Request Example
```javascript
const repl = require('repl');
const options = {
prompt: 'my-repl> ',
useColors: true
};
repl.start(options);
```
### Response
Returns a `repl.REPLServer` instance.
```
--------------------------------
### Get Node.js Version (CommonJS)
Source: https://nodejs.org/docs/latest-v22.x/api/process.json
Require the `version` property from the `node:process` module to get the Node.js version string. This example uses CommonJS modules.
```cjs
const { version } = require('node:process');
console.log(`Version: ${version}`);
// Version: v14.8.0
```
--------------------------------
### repl.start()
Source: https://nodejs.org/docs/latest-v22.x/api/repl.json
The repl.start() method creates and starts a REPLServer instance. It can accept a string to set 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(options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
// mjs
import repl from 'node:repl';
// a Unix style prompt
repl.start('$ ');
```
```javascript
// cjs
const repl = require('node:repl');
// a Unix style prompt
repl.start('$ ');
```
### Response
#### Success Response (200)
None explicitly documented.
#### Response Example
None explicitly documented.
```
--------------------------------
### Get Node.js Version (ESM)
Source: https://nodejs.org/docs/latest-v22.x/api/process.json
Import the `version` property from the `node:process` module to get the Node.js version string. This example uses ECMAScript modules.
```mjs
import { version } from 'node:process';
console.log(`Version: ${version}`);
// Version: v14.8.0
```
--------------------------------
### HTTP Server and Client Example
Source: https://nodejs.org/docs/latest-v22.x/api/http.json
This example demonstrates setting up an HTTP proxy server and making a CONNECT request through it to Google.
```APIDOC
## HTTP Proxy Server and Client Example
### Description
This code snippet illustrates the creation of an HTTP proxy server using Node.js's `http` and `net` modules. It then demonstrates how to make a `CONNECT` request to this proxy to establish a tunnel to `www.google.com` and retrieve its content.
### Server Setup
```javascript
const http = require('http');
const net = require('net');
const proxy = http.createServer((req, clientSocket, head) => {
// Connect to an origin server
const { port, hostname } = new URL(`http://${req.url}`);
const serverSocket = net.connect(port || 80, hostname, () => {
clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
serverSocket.write(head);
serverSocket.pipe(clientSocket);
clientSocket.pipe(serverSocket);
});
});
proxy.listen(1337, '127.0.0.1', () => {
console.log('Proxy server listening on 127.0.0.1:1337');
});
```
### Client Request
```javascript
// Make a request to a tunneling proxy
const options = {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80',
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('Connected to proxy!');
// Make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
```
```
--------------------------------
### repl.start([options])
Source: https://nodejs.org/docs/latest-v22.x/api/repl.json
Starts a REPL server with the given options. The `preview` option is available since v13.4.0/v12.17.0. The `terminal` option follows the default description in all cases and `useColors` checks `hasColors()` if available since v12.0.0.
```APIDOC
## repl.start([options])
### Description
Starts a REPL server instance. Allows configuration via an options object.
### Method
```
repl.start([options])
```
### Parameters
#### Query Parameters
- **options** (object) - Optional - Configuration options for the REPL server. Options include `preview`, `terminal`, and `useColors`.
```
--------------------------------
### Get Execution Async ID in Node.js (mjs)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Demonstrates how to use executionAsyncId() in ECMAScript modules to get the current asynchronous execution ID. Requires no special setup.
```mjs
import { executionAsyncId } from 'node:async_hooks';
import fs from 'node:fs';
console.log(executionAsyncId()); // 1 - bootstrap
const path = '.';
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});
```
--------------------------------
### Creating an HTTP/2 Server and Handling Streams
Source: https://nodejs.org/docs/latest-v22.x/api/http2.json
This example demonstrates how to create an HTTP/2 server, listen for incoming streams, and respond with a file. It also shows how to send trailers with the response.
```APIDOC
## Create HTTP/2 Server and Handle Streams
### Description
Creates an HTTP/2 server that listens for streams and responds to them with a file. It also handles the `wantTrailers` event to send custom trailers.
### Method
```javascript
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});
```
### Language
```javascript
const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});
```
```
--------------------------------
### Node.js Startup Snapshot API Example
Source: https://nodejs.org/docs/latest-v22.x/api/v8.json
Example demonstrating the use of v8.startupSnapshot to add custom serialization and deserialization callbacks for a BookShelf class. This allows compressing book data during snapshot creation and decompressing it upon deserialization.
```cjs
'use strict';
const fs = require('node:fs');
const zlib = require('node:zlib');
const path = require('node:path');
const assert = require('node:assert');
const v8 = require('node:v8');
class BookShelf {
storage = new Map();
// Reading a series of files from directory and store them into storage.
constructor(directory, books) {
for (const book of books) {
this.storage.set(book, fs.readFileSync(path.join(directory, book)));
}
}
static compressAll(shelf) {
for (const [ book, content ] of shelf.storage) {
shelf.storage.set(book, zlib.gzipSync(content));
}
}
static decompressAll(shelf) {
for (const [ book, content ] of shelf.storage) {
shelf.storage.set(book, zlib.gunzipSync(content));
}
}
}
// __dirname here is where the snapshot script is placed
// during snapshot building time.
const shelf = new BookShelf(__dirname, [
'book1.en_US.txt',
'book1.es_ES.txt',
'book2.zh_CN.txt',
]);
assert(v8.startupSnapshot.isBuildingSnapshot());
// On snapshot serialization, compress the books to reduce size.
v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf);
// On snapshot deserialization, decompress the books.
v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf);
v8.startupSnapshot.setDeserializeMainFunction((shelf) => {
// process.env and process.argv are refreshed during snapshot
// deserialization.
const lang = process.env.BOOK_LANG || 'en_US';
const book = process.argv[1];
const name = `${book}.${lang}.txt`;
console.log(shelf.storage.get(name));
}, shelf);
```
--------------------------------
### Read Last 10 Bytes of a File
Source: https://nodejs.org/docs/latest-v22.x/api/fs.json
Example of reading a specific byte range from a file using `createReadStream` with `start` and `end` options. The `start` and `end` options are inclusive.
```mjs
import { open } from 'node:fs/promises';
const fd = await open('sample.txt');
fd.createReadStream({ start: 90, end: 99 });
```
--------------------------------
### Create an HTTP/2 Server with RespondWithFile
Source: https://nodejs.org/docs/latest-v22.x/api/http2.json
This example demonstrates how to create an HTTP/2 server that responds to streams by serving a file. It includes handling trailers, which are sent after the response body.
```javascript
import { createServer } from 'node:http2';
const server = createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});
```
```cjs
const http2 = require('node:http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain; charset=utf-8' },
{ waitForTrailers: true });
stream.on('wantTrailers', () => {
stream.sendTrailers({ ABC: 'some value to send' });
});
});
```
--------------------------------
### Start and Stop GC Profiling in Node.js (CJS)
Source: https://nodejs.org/docs/latest-v22.x/api/v8.json
Use the `GCProfiler` class to start and stop collecting GC data. This example demonstrates starting the profiler, waiting for a second, and then stopping it to log the collected statistics. Requires Node.js v18.15.0 or later.
```cjs
const { GCProfiler } = require('node:v8');
const profiler = new GCProfiler();
profiler.start();
setTimeout(() => {
console.log(profiler.stop());
}, 1000);
```
--------------------------------
### Example .env File Content
Source: https://nodejs.org/docs/latest-v22.x/api/environment_variables.json
Demonstrates the basic structure of a .env file with key-value pairs.
```text
MY_VAR_A = "my variable A"
MY_VAR_B = "my variable B"
```
--------------------------------
### Start and Stop GC Profiling in Node.js (MJS)
Source: https://nodejs.org/docs/latest-v22.x/api/v8.json
Use the `GCProfiler` class to start and stop collecting GC data. This example demonstrates starting the profiler, waiting for a second, and then stopping it to log the collected statistics. Requires Node.js v19.6.0 or later.
```mjs
import { GCProfiler } from 'node:v8';
const profiler = new GCProfiler();
profiler.start();
setTimeout(() => {
console.log(profiler.stop());
}, 1000);
```
--------------------------------
### https.request() Example
Source: https://nodejs.org/docs/latest-v22.x/api/https.json
Demonstrates making a basic HTTPS GET request to an encrypted Google server.
```APIDOC
## https.request()
### Description
Makes a request to a secure web server.
### Method
`https.request(options, callback)`
### Parameters
#### options
- `options` (Object | string | URL) - Configuration for the request. Can include TLS options like `ca`, `cert`, `key`, `rejectUnauthorized`, etc., and standard HTTP options like `hostname`, `port`, `path`, `method`.
- If `options` is a string, it's parsed with `new URL()`.
- If `options` is a `URL` object, it's converted to an ordinary `options` object.
#### callback
- `callback` (Function) - A function that is called when the response is received. It receives a `response` object (an instance of `http.IncomingMessage`).
### Returns
- An instance of the `http.ClientRequest` class, which is a writable stream.
### Request Example (mjs)
```javascript
import { request } from 'node:https';
import process from 'node:process';
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
};
const req = request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
```
### Request Example (cjs)
```javascript
const https = require('node:https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
```
### Additional TLS Options
The following options from `tls.connect()` are also accepted:
`ca`, `cert`, `ciphers`, `clientCertEngine` (deprecated), `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`.
```
--------------------------------
### Install Build Tools
Source: https://nodejs.org/docs/latest-v22.x/api/n-api.json
Commands to install necessary C/C++ toolchains for native addon development.
```bash
xcode-select --install
```
```bash
npm install --global windows-build-tools
```
--------------------------------
### https.request() Example
Source: https://nodejs.org/docs/latest-v22.x/api/https.json
Demonstrates making a basic GET request to a secure server using https.request().
```APIDOC
## https.request()
### Description
Makes a request to a secure web server.
### Method
POST, GET, PUT, DELETE, etc. (configurable via options)
### Endpoint
Configurable via options.hostname, options.path, etc.
### Parameters
#### Path Parameters
None explicitly defined for the method itself, but used within the request path.
#### Query Parameters
None explicitly defined for the method itself, but can be part of the request path.
#### Request Body
Optional, can be written to the returned ClientRequest stream for POST/PUT requests.
### Request Example
```javascript
import { request } from 'node:https';
import process from 'node:process';
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
};
const req = request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
```
### Response
#### Success Response (200)
- **statusCode** (number) - The HTTP status code of the response.
- **headers** (object) - The response headers.
- Response body (stream) - Data from the server.
#### Response Example
```javascript
// Response body will be streamed and can be processed as it arrives.
// Example: writing to stdout
res.on('data', (d) => {
process.stdout.write(d);
});
```
```
--------------------------------
### Run Executable (Windows)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Example of how to run the prepared single executable application on Windows.
```console
$ .\hello.exe world
```
--------------------------------
### Create a TLS Server with Options
Source: https://nodejs.org/docs/latest-v22.x/api/tls.json
Illustrates creating a TLS server using provided options for key and certificate management. This is useful for setting up secure communication endpoints. Ensure certificate files exist.
```mjs
import { createServer } from 'node:tls';
import { readFileSync } from 'node:fs';
const options = {
key: readFileSync('server-key.pem'),
cert: readFileSync('server-cert.pem'),
// This is necessary only if the client uses a self-signed certificate.
ca: [ readFileSync('client-cert.pem') ],
};
const server = createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
```
```cjs
const { createServer } = require('node:tls');
const { readFileSync } = require('node:fs');
const options = {
key: readFileSync('server-key.pem'),
cert: readFileSync('server-cert.pem'),
// This is necessary only if the client uses a self-signed certificate.
ca: [ readFileSync('client-cert.pem') ],
};
const server = createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
```
--------------------------------
### Get File Extension using path.extname()
Source: https://nodejs.org/docs/latest-v22.x/api/path.json
Use path.extname() to get the extension of a path, starting from the last period. Returns an empty string if no extension is found. A TypeError is thrown if the path is not a string.
```javascript
path.extname('index.html');
// Returns: '.html'
```
```javascript
path.extname('index.coffee.md');
// Returns: '.md'
```
```javascript
path.extname('index.');
// Returns: '.'
```
```javascript
path.extname('index');
// Returns: ''
```
```javascript
path.extname('.index');
// Returns: ''
```
```javascript
path.extname('.index.md');
// Returns: '.md'
```
--------------------------------
### Client-side example
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Provides an example of how to initiate an HTTP/2 client connection using the Core API. This example shows how to connect to a server and send a request.
```APIDOC
## Client-side example
### Description
This example demonstrates how to create an HTTP/2 client using the Core API. It connects to a specified authority (host and port) and sends a request, then processes the response.
### Method
`http2.connect(authority, [options], [listener])`
### Endpoint
`authority` (string) - The authority to connect to, e.g., 'https://localhost:8443'.
### Parameters
#### Options for `connect`
- **rejectUnauthorized** (boolean) - Optional - Whether to reject unauthorized servers. Defaults to true.
#### Listener for `connect`
- **session** (ClientSession) - The client session object.
### Request Example
```javascript
import { connect } from 'node:http2';
const client = connect('https://localhost:8443');
client.on('error', (err) => console.error(err));
const stream = client.request({
':path': '/about',
});
let data = '';
stream.on('data', (chunk) => {
data += chunk;
});
stream.on('end', () => {
console.log(data);
});
stream.end();
```
### Response
#### Success Response
- **data** (string) - The response body received from the server.
#### Response Example
```javascript
console.log(data);
```
```
--------------------------------
### method
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Only valid for request obtained from http.Server. The request method as a string. Read only. Examples: 'GET', 'DELETE'.
```APIDOC
## method
### Description
**Only valid for request obtained from http.Server.**
The request method as a string. Read only. Examples: 'GET', 'DELETE'.
```
--------------------------------
### Build and Run Node.js with Startup Snapshot
Source: https://nodejs.org/docs/latest-v22.x/api/v8.json
Commands to build a Node.js process with a custom startup snapshot and then run it. The entry.js script defines serialization and deserialization logic for custom objects.
```console
$ node --snapshot-blob snapshot.blob --build-snapshot entry.js
# This launches a process with the snapshot
$ node --snapshot-blob snapshot.blob
```
--------------------------------
### Get Global Object
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Retrieves the global object. This function is available starting from Node-API version 1.
```c
napi_status napi_get_global(napi_env env, napi_value* result)
```
--------------------------------
### Create a 'Hello, World!' Web Server
Source: https://nodejs.org/docs/latest-v22.x/api/synopsis.json
This JavaScript code creates a basic HTTP server that responds with 'Hello, World!'. Ensure Node.js is installed.
```javascript
const http = 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!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```
--------------------------------
### Trace Synchronous Function Calls (CJS)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Traces a synchronous function call, publishing start, end, and potentially error events. Events are only published if subscribers are present before the trace starts. This example uses the CommonJS module system.
```cjs
const diagnostics_channel = require('node:diagnostics_channel');
const channels = diagnostics_channel.tracingChannel('my-channel');
channels.traceSync(() => {
// Do something
}, {
some: 'thing',
});
```
--------------------------------
### Creating an HTTPS Server
Source: https://nodejs.org/docs/latest-v22.x/api/https.json
Examples of how to create an HTTPS server using certificate and key files, or a PFX file.
```mjs
// curl -k https://localhost:8000/
import { createServer } from 'node:https';
import { readFileSync } from 'node:fs';
const options = {
key: readFileSync('private-key.pem'),
cert: readFileSync('certificate.pem'),
};
createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
```cjs
// curl -k https://localhost:8000/
const https = require('node:https');
const fs = require('node:fs');
const options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem'),
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
```mjs
import { createServer } from 'node:https';
import { readFileSync } from 'node:fs';
const options = {
pfx: readFileSync('test_cert.pfx'),
passphrase: 'sample',
};
createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
```cjs
const https = require('node:https');
const fs = require('node:fs');
const options = {
pfx: fs.readFileSync('test_cert.pfx'),
passphrase: 'sample',
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
--------------------------------
### Trace Synchronous Function Calls (MJS)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Traces a synchronous function call, publishing start, end, and potentially error events. Events are only published if subscribers are present before the trace starts. This example uses the MJS module system.
```mjs
import diagnostics_channel from 'node:diagnostics_channel';
const channels = diagnostics_channel.tracingChannel('my-channel');
channels.traceSync(() => {
// Do something
}, {
some: 'thing',
});
```
--------------------------------
### Enable and Collect CPU Profile with Inspector Session
Source: https://nodejs.org/docs/latest-v22.x/api/inspector.json
This example demonstrates how to use the CPU profiler domain to start and stop profiling. The collected profile data is then written to a file. Make sure to connect the session before enabling and starting the profiler.
```mjs
import { Session } from 'node:inspector/promises';
import fs from 'node:fs';
const session = new Session();
session.connect();
await session.post('Profiler.enable');
await session.post('Profiler.start');
// Invoke business logic under measurement here...
// some time later...
const { profile } = await session.post('Profiler.stop');
// Write profile to disk, upload, etc.
fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
```
--------------------------------
### Creating an HTTP/2 Server
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
This example demonstrates how to create a basic HTTP/2 server using the compatibility API. It handles requests and sends a simple response.
```APIDOC
## Creating an HTTP/2 Server
### Description
This example demonstrates how to create a basic HTTP/2 server using the compatibility API. It handles requests and sends a simple response.
### Method
```javascript
import { createServer } from 'node:http2';
```
### Endpoint
N/A (Server creation)
### Request Example
```javascript
const server = createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
```
### Response
#### Success Response (200)
- **Content-Type** (string) - The type of content being sent.
- **X-Foo** (string) - A custom header example.
#### Response Example
```json
{
"response": "ok"
}
```
```
```APIDOC
## Creating an HTTP/2 Server (CommonJS)
### Description
This example demonstrates how to create a basic HTTP/2 server using the compatibility API with CommonJS modules.
### Method
```javascript
const http2 = require('node:http2');
```
### Endpoint
N/A (Server creation)
### Request Example
```javascript
const server = http2.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('ok');
});
```
### Response
#### Success Response (200)
- **Content-Type** (string) - The type of content being sent.
- **X-Foo** (string) - A custom header example.
#### Response Example
```json
{
"response": "ok"
}
```
```
--------------------------------
### Get Active Resources Info in Node.js (cjs)
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
This CommonJS example demonstrates `getActiveResourcesInfo()`, showing the active resources before and after scheduling a timer.
```cjs
const { getActiveResourcesInfo } = require('node:process');
const { setTimeout } = require('node:timers');
console.log('Before:', getActiveResourcesInfo());
setTimeout(() => {}, 1000);
console.log('After:', getActiveResourcesInfo());
// Prints:
// Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
// After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]
```
--------------------------------
### replServer.displayPrompt()
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Prepares the REPL instance for user input by printing the prompt and resuming input. It handles multi-line input and can preserve cursor placement.
```APIDOC
## replServer.displayPrompt()
### Description
Prepares the REPL instance for user input by printing the configured prompt to a new line in the output and resuming input to accept new input. When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. When `preserveCursor` is `true`, the cursor placement will not be reset to `0`.
This method is primarily intended to be called from within the action function for commands registered using the `replServer.defineCommand()` method.
### Parameters
#### Optional Parameters
- **preserveCursor** (boolean) - If `true`, the cursor placement will not be reset to `0`.
### Request Example
```javascript
replServer.displayPrompt();
```
### Response
This method does not return a value.
```
--------------------------------
### Retrieving HTTP Response Status Message
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Get the HTTP response status message (reason phrase) for responses from `http.ClientRequest`. Example: 'OK'.
```javascript
response.statusMessage
```
--------------------------------
### Iterate over MIME parameter names (mjs)
Source: https://nodejs.org/docs/latest-v22.x/api/util.json
Use `params.keys()` to get an iterator for MIME parameter names. This example shows how to iterate and log each name.
```mjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// bar
```
--------------------------------
### Node-API Example: Hello World Addon
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
This C++ code demonstrates a basic addon using Node-API. It replaces the V8 or nan APIs with Node-API functions for ABI stability. Ensure you have Node-API headers included.
```cpp
// hello.cc using Node-API
#include
namespace demo {
napi_value Method(napi_env env, napi_callback_info args) {
napi_value greeting;
napi_status status;
status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
if (status != napi_ok) return nullptr;
return greeting;
}
napi_value init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
if (status != napi_ok) return nullptr;
status = napi_set_named_property(env, exports, "hello", fn);
if (status != napi_ok) return nullptr;
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
} // namespace demo
```
--------------------------------
### Get Performance Entries by Name (cjs)
Source: https://nodejs.org/docs/latest-v22.x/api/perf_hooks.json
Retrieve PerformanceEntry objects by their name and optionally by type using getEntriesByName. This example uses the CommonJS syntax.
```cjs
const {
performance,
PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntries());
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');
```
--------------------------------
### Get Inspector URL
Source: https://nodejs.org/docs/latest-v22.x/api/inspector.json
Retrieve the URL of the active inspector. Returns `undefined` if no inspector is active. Examples show usage with and without specifying a host/port.
```console
$ node --inspect -p 'inspector.url()'
Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
For help, see: https://nodejs.org/learn/getting-started/debugging
ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
$ node --inspect=localhost:3000 -p 'inspector.url()'
Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
For help, see: https://nodejs.org/learn/getting-started/debugging
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
$ node -p 'inspector.url()'
undefined
```
--------------------------------
### server.listen([port[, host[, backlog]]][, callback])
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Starts a TCP server listening for connections on the specified port and host. This is the most common way to start a network server.
```APIDOC
## server.listen([port[, host[, backlog]]][, callback])
### Description
Starts a TCP server listening for connections on the specified port and host. This is the most common way to start a network server.
### Method
server.listen
### Parameters
#### Path Parameters
- **port** (number) - The port to listen on. Optional.
- **host** (string) - The host to listen on. Optional.
- **backlog** (number) - Common parameter of [`server.listen()`][] functions. Optional.
- **callback** (Function) - Description not available.
### Example
```javascript
// Example usage would go here, demonstrating how to call this method with port and host.
```
```
--------------------------------
### Get Trigger Async ID Examples
Source: https://nodejs.org/docs/latest-v22.x/api/async_hooks.json
Demonstrates `triggerAsyncId()` which returns the ID of the resource that initiated the current callback. This differs from `executionAsyncId()` by indicating causality.
```js
const server = net.createServer((conn) => {
// The resource that caused (or triggered) this callback to be called
// was that of the new connection. Thus the return value of triggerAsyncId()
// is the asyncId of "conn".
async_hooks.triggerAsyncId();
}).listen(port, () => {
// Even though all callbacks passed to .listen() are wrapped in a nextTick()
// the callback itself exists because the call to the server's .listen()
// was made. So the return value would be the ID of the server.
async_hooks.triggerAsyncId();
});
```
--------------------------------
### Restrict access with the --permission flag
Source: https://nodejs.org/docs/latest-v22.x/api/permissions.json
Example of the error output when attempting to access a restricted resource after starting the process with the --permission flag.
```console
$ node --permission index.js
Error: Access to this API has been restricted
at node:internal/main/run_main_module:23:47 {
code: 'ERR_ACCESS_DENIED',
permission: 'FileSystemRead',
resource: '/home/user/index.js'
}
```
--------------------------------
### Define Package Entry Points with 'exports' (Export Patterns)
Source: https://nodejs.org/docs/latest-v22.x/api/packages.json
This example shows how to use export patterns within the 'exports' field to define entry points for entire folders, including subpaths with and without extensions. This approach also ensures backward compatibility.
```json
{
"name": "my-package",
"exports": {
".": "./lib/index.js",
"./lib": "./lib/index.js",
"./lib/*": "./lib/*.js",
"./lib/*.js": "./lib/*.js",
"./feature": "./feature/index.js",
"./feature/*": "./feature/*.js",
"./feature/*.js": "./feature/*.js",
"./package.json": "./package.json"
}
}
```
--------------------------------
### Node.js execArgv Example
Source: https://nodejs.org/docs/latest-v22.x/api/process.json
Illustrates how process.execArgv returns Node.js-specific command-line options.
```bash
node --icu-data-dir=./foo --require ./bar.js script.js --version
```
```json
["--icu-data-dir=./foo", "--require", "./bar.js"]
```
```js
['/usr/local/bin/node', 'script.js', '--version']
```
--------------------------------
### URL Properties
Source: https://nodejs.org/docs/latest-v22.x/api/all.json
Details various properties of the URL object, including search, username, password, hostname, port, pathname, and hash, with examples of how to get and set them.
```APIDOC
## URL Properties
### `search`
#### Description
Gets and sets the serialized query portion of the URL.
#### Example
```javascript
const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// Prints ?123
myURL.search = 'abc=xyz';
console.log(myURL.href);
// Prints https://example.org/abc?abc=xyz
```
Any invalid URL characters appearing in the value assigned the `search` property will be percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the `url.parse()` and `url.format()` methods would produce.
#### Type
`string`
### `username`
#### Description
Gets and sets the username portion of the URL.
#### Example
```javascript
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// Prints abc
myURL.username = '123';
console.log(myURL.href);
// Prints https://123:xyz@example.com/
```
Any invalid URL characters appearing in the value assigned the `username` property will be percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the `url.parse()` and `url.format()` methods would produce.
#### Type
`string`
### `password`
#### Description
Gets and sets the password portion of the URL.
#### Example
```javascript
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// Prints xyz
myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:123@example.com/
```
Any invalid URL characters appearing in the value assigned the `password` property will be percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the `url.parse()` and `url.format()` methods would produce.
#### Type
`string`
### `hostname`
#### Description
Gets and sets the host name portion of the URL.
#### Example
```javascript
const myURL = new URL('https://user:pass@example.com:8080/path/to/file?query=string#hash');
console.log(myURL.hostname);
// Prints example.com
myURL.hostname = 'example.org';
console.log(myURL.href);
// Prints https://user:pass@example.org:8080/path/to/file?query=string#hash
```
#### Type
`string`
### `port`
#### Description
Gets and sets the port number of the URL.
#### Example
```javascript
const myURL = new URL('https://user:pass@example.com:8080/path/to/file?query=string#hash');
console.log(myURL.port);
// Prints 8080
myURL.port = 443;
console.log(myURL.href);
// Prints https://user:pass@example.com:443/path/to/file?query=string#hash
```
#### Type
`string`
### `pathname`
#### Description
Gets and sets the path portion of the URL.
#### Example
```javascript
const myURL = new URL('https://user:pass@example.com:8080/path/to/file?query=string#hash');
console.log(myURL.pathname);
// Prints /path/to/file
myURL.pathname = '/path/to/newfile';
console.log(myURL.href);
// Prints https://user:pass@example.com:8080/path/to/newfile?query=string#hash
```
#### Type
`string`
### `hash`
#### Description
Gets and sets the fragment identifier of the URL.
#### Example
```javascript
const myURL = new URL('https://user:pass@example.com:8080/path/to/file?query=string#hash');
console.log(myURL.hash);
// Prints #hash
myURL.hash = '#new-hash';
console.log(myURL.href);
// Prints https://user:pass@example.com:8080/path/to/file?query=string#new-hash
```
#### Type
`string`
```
--------------------------------
### Get Performance Entries by Name (mjs)
Source: https://nodejs.org/docs/latest-v22.x/api/perf_hooks.json
Retrieve PerformanceEntry objects by their name and optionally by type using getEntriesByName. This example uses the ES Module syntax.
```mjs
import { performance, PerformanceObserver } from 'node:perf_hooks';
const obs = new PerformanceObserver((perfObserverList, observer) => {
console.log(perfObserverList.getEntries());
/**
* [
* PerformanceEntry {
* name: 'test',
* entryType: 'mark',
* startTime: 81.465639,
* duration: 0,
* detail: null
* },
* PerformanceEntry {
* name: 'meow',
* entryType: 'mark',
* startTime: 81.860064,
* duration: 0,
* detail: null
* }
* ]
*/
performance.clearMarks();
performance.clearMeasures();
observer.disconnect();
});
obs.observe({ type: 'mark' });
performance.mark('test');
performance.mark('meow');
```