node__assert.d.ts
The `node:assert` module provides a set of assertion functions for verifying invariants.f
N
default
An alias of ok.
c
default.AssertionError
Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class.
T
default.AssertPredicate
No documentation available
I
f
default.deepEqual
**Strict assertion mode**
An alias of deepStrictEqual.
**Legacy assertion mode**
> Stability: 3 - Legacy: Use deepStrictEqual instead.
Tests for deep equality between the `actual` and `expected` parameters. Consider
using deepStrictEqual instead. deepEqual can have
surprising results.
_Deep equality_ means that the enumerable "own" properties of child objects
are also recursively evaluated by the following rules.
f
default.deepStrictEqual
Tests for deep equality between the `actual` and `expected` parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.
f
default.doesNotMatch
Expects the `string` input not to match the regular expression.
```js
import assert from 'node:assert/strict';
assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.doesNotMatch('I will pass', /different/);
// OK
```
If the values do match, or if the `string` argument is of another type than `string`, an `AssertionError` is thrown with a `message` property set equal
to the value of the `message` parameter. If the `message` parameter is
undefined, a default error message is assigned. If the `message` parameter is an
instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `AssertionError`.
f
default.doesNotReject
Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.
If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If
the function does not return a promise, `assert.doesNotReject()` will return a
rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value) error. In both cases
the error handler is skipped.
Using `assert.doesNotReject()` is actually not useful because there is little
benefit in catching a rejection and then rejecting it again. Instead, consider
adding a comment next to the specific code path that should not reject and keep
error messages as expressive as possible.
If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation
function. See throws for more details.
Besides the async nature to await the completion behaves identically to doesNotThrow.
```js
import assert from 'node:assert/strict';
await assert.doesNotReject(
async () => {
throw new TypeError('Wrong value');
},
SyntaxError,
);
```
```js
import assert from 'node:assert/strict';
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
.then(() => {
// ...
});
```
f
default.doesNotThrow
Asserts that the function `fn` does not throw an error.
Using `assert.doesNotThrow()` is actually not useful because there
is no benefit in catching an error and then rethrowing it. Instead, consider
adding a comment next to the specific code path that should not throw and keep
error messages as expressive as possible.
When `assert.doesNotThrow()` is called, it will immediately call the `fn` function.
If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a
different type, or if the `error` parameter is undefined, the error is
propagated back to the caller.
If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation
function. See throws for more details.
The following, for instance, will throw the `TypeError` because there is no
matching error type in the assertion:
```js
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError,
);
```
However, the following will result in an `AssertionError` with the message
'Got unwanted exception...':
```js
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
);
```
If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message:
```js
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
/Wrong value/,
'Whoops',
);
// Throws: AssertionError: Got unwanted exception: Whoops
```
f
default.equal
**Strict assertion mode**
An alias of strictEqual.
**Legacy assertion mode**
> Stability: 3 - Legacy: Use strictEqual instead.
Tests shallow, coercive equality between the `actual` and `expected` parameters
using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled
and treated as being identical if both sides are `NaN`.
```js
import assert from 'node:assert';
assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(NaN, NaN);
// OK
assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
```
If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default
error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
f
default.fail
Throws an `AssertionError` with the provided error message or a default
error message. If the `message` parameter is an instance of an `Error` then
it will be thrown instead of the `AssertionError`.
```js
import assert from 'node:assert/strict';
assert.fail();
// AssertionError [ERR_ASSERTION]: Failed
assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom
assert.fail(new TypeError('need array'));
// TypeError: need array
```
Using `assert.fail()` with more than two arguments is possible but deprecated.
See below for further details.
f
default.ifError
Throws `value` if `value` is not `undefined` or `null`. This is useful when
testing the `error` argument in callbacks. The stack trace contains all frames
from the error passed to `ifError()` including the potential new frames for `ifError()` itself.
```js
import assert from 'node:assert/strict';
assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
// Create some random error frames.
let err;
(function errorFrame() {
err = new Error('test error');
})();
(function ifErrorFrame() {
assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrame
```
f
default.match
Expects the `string` input to match the regular expression.
```js
import assert from 'node:assert/strict';
assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.match('I will pass', /pass/);
// OK
```
If the values do not match, or if the `string` argument is of another type than `string`, an `AssertionError` is thrown with a `message` property set equal
to the value of the `message` parameter. If the `message` parameter is
undefined, a default error message is assigned. If the `message` parameter is an
instance of an [Error](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) then it will be thrown instead of the `AssertionError`.
f
default.notDeepEqual
**Strict assertion mode**
An alias of notDeepStrictEqual.
**Legacy assertion mode**
> Stability: 3 - Legacy: Use notDeepStrictEqual instead.
Tests for any deep inequality. Opposite of deepEqual.
```js
import assert from 'node:assert';
const obj1 = {
a: {
b: 1,
},
};
const obj2 = {
a: {
b: 2,
},
};
const obj3 = {
a: {
b: 1,
},
};
const obj4 = { __proto__: obj1 };
assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj2);
// OK
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OK
```
If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default
error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
instead of the `AssertionError`.
f
default.notDeepStrictEqual
Tests for deep strict inequality. Opposite of deepStrictEqual.
```js
import assert from 'node:assert/strict';
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK
```
If the values are deeply and strictly equal, an `AssertionError` is thrown
with a `message` property set equal to the value of the `message` parameter. If
the `message` parameter is undefined, a default error message is assigned. If
the `message` parameter is an instance of an `Error` then it will be thrown
instead of the `AssertionError`.
f
default.notEqual
**Strict assertion mode**
An alias of notStrictEqual.
**Legacy assertion mode**
> Stability: 3 - Legacy: Use notStrictEqual instead.
Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is
specially handled and treated as being identical if both sides are `NaN`.
```js
import assert from 'node:assert';
assert.notEqual(1, 2);
// OK
assert.notEqual(1, 1);
// AssertionError: 1 != 1
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
```
If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error
message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
f
default.notStrictEqual
Tests strict inequality between the `actual` and `expected` parameters as
determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
```js
import assert from 'node:assert/strict';
assert.notStrictEqual(1, 2);
// OK
assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1
assert.notStrictEqual(1, '1');
// OK
```
If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a
default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
instead of the `AssertionError`.
f
default.ok
Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`.
If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default
error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``.
Be aware that in the `repl` the error message will be different to the one
thrown in a file! See below for further details.
```js
import assert from 'node:assert/strict';
assert.ok(true);
// OK
assert.ok(1);
// OK
assert.ok();
// AssertionError: No value argument passed to `assert.ok()`
assert.ok(false, 'it\'s false');
// AssertionError: it's false
// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true
// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(typeof 123 === 'string')
assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(false)
assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)
```
```js
import assert from 'node:assert/strict';
// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)
```
f
default.rejects
Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.
If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the
function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v22.x/api/errors.html#err_invalid_return_value)
error. In both cases the error handler is skipped.
Besides the async nature to await the completion behaves identically to throws.
If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
an object where each property will be tested for, or an instance of error where
each property will be tested for including the non-enumerable `message` and `name` properties.
If specified, `message` will be the message provided by the `AssertionError` if the `asyncFn` fails to reject.
```js
import assert from 'node:assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
{
name: 'TypeError',
message: 'Wrong value',
},
);
```
```js
import assert from 'node:assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
(err) => {
assert.strictEqual(err.name, 'TypeError');
assert.strictEqual(err.message, 'Wrong value');
return true;
},
);
```
```js
import assert from 'node:assert/strict';
assert.rejects(
Promise.reject(new Error('Wrong value')),
Error,
).then(() => {
// ...
});
```
`error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to
be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the
example in throws carefully if using a string as the second argument gets considered.
N
v
default.strict
In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example,
deepEqual will behave like deepStrictEqual.
In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error
messages for objects display the objects, often truncated.
To use strict assertion mode:
```js
import { strict as assert } from 'node:assert';COPY
import assert from 'node:assert/strict';
```
Example error diff:
```js
import { strict as assert } from 'node:assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
// [
// [
// ...
// 2,
// + 3
// - '3'
// ],
// ...
// 5
// ]
```
To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also
deactivate the colors in the REPL. For more on color support in terminal environments, read the tty
`getColorDepth()` documentation.
T
default.strict.AssertionError
No documentation available
T
default.strict.AssertPredicate
No documentation available
T
default.strict.CallTrackerCall
No documentation available
T
default.strict.CallTrackerReportInformation
No documentation available
f
default.strictEqual
Tests strict equality between the `actual` and `expected` parameters as
determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
```js
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
// ^
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical
```
If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a
default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
instead of the `AssertionError`.
f
default.throws
Expects the function `fn` to throw an error.
If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
[`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable `message` and `name` properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.
If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation
fails.
Custom validation object/error instance:
```js
import assert from 'node:assert/strict';
const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
nested: true,
baz: 'text',
};
err.reg = /abc/i;
assert.throws(
() => {
throw err;
},
{
name: 'TypeError',
message: 'Wrong value',
info: {
nested: true,
baz: 'text',
},
// Only properties on the validation object will be tested for.
// Using nested objects requires all properties to be present. Otherwise
// the validation is going to fail.
},
);
// Using regular expressions to validate error properties:
assert.throws(
() => {
throw err;
},
{
// The `name` and `message` properties are strings and using regular
// expressions on those will match against the string. If they fail, an
// error is thrown.
name: /^TypeError$/,
message: /Wrong/,
foo: 'bar',
info: {
nested: true,
// It is not possible to use regular expressions for nested properties!
baz: 'text',
},
// The `reg` property contains a regular expression and only if the
// validation object contains an identical regular expression, it is going
// to pass.
reg: /abc/i,
},
);
// Fails due to the different `message` and `name` properties:
assert.throws(
() => {
const otherErr = new Error('Not found');
// Copy all enumerable properties from `err` to `otherErr`.
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
// The error's `message` and `name` properties will also be checked when using
// an error as validation object.
err,
);
```
Validate instanceof using constructor:
```js
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
Error,
);
```
Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions):
Using a regular expression runs `.toString` on the error object, and will
therefore also include the error name.
```js
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/,
);
```
Custom error validation:
The function must return `true` to indicate all internal validations passed.
It will otherwise fail with an `AssertionError`.
```js
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
// Avoid returning anything from validation functions besides `true`.
// Otherwise, it's not clear what part of the validation failed. Instead,
// throw an error about the specific validation that failed (as done in this
// example) and add as much helpful debugging information to that error as
// possible.
return true;
},
'unexpected error',
);
```
`error` cannot be a string. If a string is provided as the second
argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same
message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
a string as the second argument gets considered:
```js
import assert from 'node:assert/strict';
function throwingFirst() {
throw new Error('First');
}
function throwingSecond() {
throw new Error('Second');
}
function notThrowing() {}
// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]
// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);
// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]
```
Due to the confusing error-prone notation, avoid a string as the second
argument.
node__async_hooks.d.ts
We strongly discourage the use of the `async_hooks` API. Other APIs that can cover most of its use cases include: * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v22.x/api/async_context.html#class-asynclocalstorage) tracks async context * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processgetactiveresourcesinfo) tracks active resources The `node:async_hooks` module provides an API to track asynchronous resources. It can be accessed using: ```js import async_hooks from 'node:async_hooks'; ```c
AsyncLocalStorage
This class creates stores that stay coherent through asynchronous operations.
While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.
The following example uses `AsyncLocalStorage` to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.
```js
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
// 0: start
// 1: start
// 0: finish
// 1: finish
```
Each instance of `AsyncLocalStorage` maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
c
AsyncResource
> [!WARNING] Deno compatibility
> The AsyncResource implementation is a non-functional stub.
The class `AsyncResource` is designed to be extended by the embedder's async
resources. Using this, users can easily trigger the lifetime events of their
own resources.
The `init` hook will trigger when an `AsyncResource` is instantiated.
The following is an overview of the `AsyncResource` API.
```js
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
// AsyncResource() is meant to be extended. Instantiating a
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource(
type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
);
// Run a function in the execution context of the resource. This will
// * establish the context of the resource
// * trigger the AsyncHooks before callbacks
// * call the provided function `fn` with the supplied arguments
// * trigger the AsyncHooks after callbacks
// * restore the original execution context
asyncResource.runInAsyncScope(fn, thisArg, ...args);
// Call AsyncHooks destroy callbacks.
asyncResource.emitDestroy();
// Return the unique ID assigned to the AsyncResource instance.
asyncResource.asyncId();
// Return the trigger ID for the AsyncResource instance.
asyncResource.triggerAsyncId();
```
I
f
createHook
> [!WARNING] Deno compatibility
> The createHook implementation is a non-functional stub.
Registers functions to be called for different lifetime events of each async
operation.
The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
respective asynchronous event during a resource's lifetime.
All callbacks are optional. For example, if only resource cleanup needs to
be tracked, then only the `destroy` callback needs to be passed. The
specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section.
```js
import { createHook } from 'node:async_hooks';
const asyncHook = createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { },
});
```
The callbacks will be inherited via the prototype chain:
```js
class MyAsyncCallbacks {
init(asyncId, type, triggerAsyncId, resource) { }
destroy(asyncId) {}
}
class MyAddedCallbacks extends MyAsyncCallbacks {
before(asyncId) { }
after(asyncId) { }
}
const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
```
Because promises are asynchronous resources whose lifecycle is tracked
via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises.
f
executionAsyncId
> [!WARNING] Deno compatibility
> The executionAsyncId implementation is a non-functional stub.
```js
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()
});
```
The ID returned from `executionAsyncId()` is related to execution timing, not
causality (which is covered by `triggerAsyncId()`):
```js
const server = net.createServer((conn) => {
// Returns the ID of the server, not of the new connection, because the
// callback runs in the execution scope of the server's MakeCallback().
async_hooks.executionAsyncId();
}).listen(port, () => {
// Returns the ID of a TickObject (process.nextTick()) because all
// callbacks passed to .listen() are wrapped in a nextTick().
async_hooks.executionAsyncId();
});
```
Promise contexts may not get precise `executionAsyncIds` by default.
See the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking).
f
executionAsyncResource
Resource objects returned by `executionAsyncResource()` are most often internal
Node.js handle objects with undocumented APIs. Using any functions or properties
on the object is likely to crash your application and should be avoided.
Using `executionAsyncResource()` in the top-level execution context will
return an empty object as there is no handle or request object to use,
but having an object representing the top-level can be helpful.
```js
import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
open(new URL(import.meta.url), 'r', (err, fd) => {
console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
});
```
This can be used to implement continuation local storage without the
use of a tracking `Map` to store the metadata:
```js
import { createServer } from 'node:http';
import {
executionAsyncId,
executionAsyncResource,
createHook,
} from 'node:async_hooks';
const sym = Symbol('state'); // Private symbol to avoid pollution
createHook({
init(asyncId, type, triggerAsyncId, resource) {
const cr = executionAsyncResource();
if (cr) {
resource[sym] = cr[sym];
}
},
}).enable();
const server = createServer((req, res) => {
executionAsyncResource()[sym] = { state: req.url };
setTimeout(function() {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);
```
I
f
triggerAsyncId
```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();
});
```
Promise contexts may not get valid `triggerAsyncId`s by default. See
the section on [promise execution tracking](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html#promise-execution-tracking).
node__buffer.d.ts
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many Node.js APIs support `Buffer`s. The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and extends it with methods that cover additional use cases. Node.js APIs accept plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. While the `Buffer` class is available within the global scope, it is still recommended to explicitly reference it via an import or require statement. ```js import { Buffer } from 'node:buffer'; // Creates a zero-filled Buffer of length 10. const buf1 = Buffer.alloc(10); // Creates a Buffer of length 10, // filled with bytes which all have the value `1`. const buf2 = Buffer.alloc(10, 1); // Creates an uninitialized buffer of length 10. // This is faster than calling Buffer.alloc() but the returned // Buffer instance might contain old data that needs to be // overwritten using fill(), write(), or other functions that fill the Buffer's // contents. const buf3 = Buffer.allocUnsafe(10); // Creates a Buffer containing the bytes [1, 2, 3]. const buf4 = Buffer.from([1, 2, 3]); // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries // are all truncated using `(value & 255)` to fit into the range 0–255. const buf5 = Buffer.from([257, 257.5, -255, '1']); // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) // [116, 195, 169, 115, 116] (in decimal notation) const buf6 = Buffer.from('tést'); // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. const buf7 = Buffer.from('tést', 'latin1'); ```f
atob
Decodes a string of Base64-encoded data into bytes, and encodes those bytes
into a string using Latin-1 (ISO-8859-1).
The `data` may be any JavaScript-value that can be coerced into a string.
**This function is only provided for compatibility with legacy web platform APIs**
**and should never be used in new code, because they use strings to represent**
**binary data and predate the introduction of typed arrays in JavaScript.**
**For code running using Node.js APIs, converting between base64-encoded strings**
**and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.**
c
I
v
I
f
btoa
Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
into a string using Base64.
The `data` may be any JavaScript-value that can be coerced into a string.
**This function is only provided for compatibility with legacy web platform APIs**
**and should never be used in new code, because they use strings to represent**
**binary data and predate the introduction of typed arrays in JavaScript.**
**For code running using Node.js APIs, converting between base64-encoded strings**
**and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.**
I
v
Buffer
No documentation available
- compare
- copy
- equals
- fill
- includes
- indexOf
- lastIndexOf
- readBigInt64BE
- readBigInt64LE
- readBigUInt64BE
- readBigUInt64LE
- readBigUint64BE
- readBigUint64LE
- readDoubleBE
- readDoubleLE
- readFloatBE
- readFloatLE
- readInt16BE
- readInt16LE
- readInt32BE
- readInt32LE
- readInt8
- readIntBE
- readIntLE
- readUInt16BE
- readUInt16LE
- readUInt32BE
- readUInt32LE
- readUInt8
- readUIntBE
- readUIntLE
- readUint16BE
- readUint16LE
- readUint32BE
- readUint32LE
- readUint8
- readUintBE
- readUintLE
- reverse
- slice
- subarray
- swap16
- swap32
- swap64
- toJSON
- toString
- write
- writeBigInt64BE
- writeBigInt64LE
- writeBigUInt64BE
- writeBigUInt64LE
- writeBigUint64BE
- writeBigUint64LE
- writeDoubleBE
- writeDoubleLE
- writeFloatBE
- writeFloatLE
- writeInt16BE
- writeInt16LE
- writeInt32BE
- writeInt32LE
- writeInt8
- writeIntBE
- writeIntLE
- writeUInt16BE
- writeUInt16LE
- writeUInt32BE
- writeUInt32LE
- writeUInt8
- writeUIntBE
- writeUIntLE
- writeUint16BE
- writeUint16LE
- writeUint32BE
- writeUint32LE
- writeUint8
- writeUintBE
- writeUintLE
I
BufferConstructor
Raw data is stored in instances of the Buffer class.
A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
T
BufferEncoding
No documentation available
v
c
I
v
File
A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files.
I
v
INSPECT_MAX_BYTES
No documentation available
f
isAscii
This function returns `true` if `input` contains only valid ASCII-encoded data,
including the case in which `input` is empty.
Throws if the `input` is a detached array buffer.
f
isUtf8
This function returns `true` if `input` contains only valid UTF-8-encoded data,
including the case in which `input` is empty.
Throws if the `input` is a detached array buffer.
v
kMaxLength
No documentation available
v
kStringMaxLength
No documentation available
f
resolveObjectURL
Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using
a prior call to `URL.createObjectURL()`.
v
f
transcode
Re-encodes the given `Buffer` or `Uint8Array` instance from one character
encoding to another. Returns a new `Buffer` instance.
Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if
conversion from `fromEnc` to `toEnc` is not permitted.
Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`.
The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:
```js
import { Buffer, transcode } from 'node:buffer';
const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'
```
Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
with `?` in the transcoded `Buffer`.
T
TranscodeEncoding
No documentation available
I
T
WithImplicitCoercion
No documentation available
node__child_process.d.ts
The `node:child_process` module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability is primarily provided by the [spawn](././node__child_process.d.ts/~/spawn) function: ```js import { spawn } from 'node:child_process'; const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); ls.on('close', (code) => { console.log(`child process exited with code ${code}`); }); ``` By default, pipes for `stdin`, `stdout`, and `stderr` are established between the parent Node.js process and the spawned subprocess. These pipes have limited (and platform-specific) capacity. If the subprocess writes to stdout in excess of that limit without the output being captured, the subprocess blocks waiting for the pipe buffer to accept more data. This is identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. The command lookup is performed using the `options.env.PATH` environment variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is used. If `options.env` is set without `PATH`, lookup on Unix is performed on a default search path search of `/usr/bin:/bin` (see your operating system's manual for execvpe/execvp), on Windows the current processes environment variable `PATH` is used. On Windows, environment variables are case-insensitive. Node.js lexicographically sorts the `env` keys and uses the first one that case-insensitively matches. Only first (in lexicographic order) entry will be passed to the subprocess. This might lead to issues on Windows when passing objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. The [spawn](././node__child_process.d.ts/~/spawn) method spawns the child process asynchronously, without blocking the Node.js event loop. The [spawnSync](././node__child_process.d.ts/~/spawnSync) function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated. For convenience, the `node:child_process` module provides a handful of synchronous and asynchronous alternatives to [spawn](././node__child_process.d.ts/~/spawn) and [spawnSync](././node__child_process.d.ts/~/spawnSync). Each of these alternatives are implemented on top of [spawn](././node__child_process.d.ts/~/spawn) or [spawnSync](././node__child_process.d.ts/~/spawnSync). * [exec](././node__child_process.d.ts/~/exec): spawns a shell and runs a command within that shell, passing the `stdout` and `stderr` to a callback function when complete. * [execFile](././node__child_process.d.ts/~/execFile): similar to [exec](././node__child_process.d.ts/~/exec) except that it spawns the command directly without first spawning a shell by default. * [fork](././node__child_process.d.ts/~/fork): spawns a new Node.js process and invokes a specified module with an IPC communication channel established that allows sending messages between parent and child. * [execSync](././node__child_process.d.ts/~/execSync): a synchronous version of [exec](././node__child_process.d.ts/~/exec) that will block the Node.js event loop. * [execFileSync](././node__child_process.d.ts/~/execFileSync): a synchronous version of [execFile](././node__child_process.d.ts/~/execFile) that will block the Node.js event loop. For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, the synchronous methods can have significant impact on performance due to stalling the event loop while spawned processes complete.c
ChildProcess
Instances of the `ChildProcess` represent spawned child processes.
Instances of `ChildProcess` are not intended to be created directly. Rather,
use the [spawn](././node__child_process.d.ts/~/spawn), [exec](././node__child_process.d.ts/~/exec),[execFile](././node__child_process.d.ts/~/execFile), or [fork](././node__child_process.d.ts/~/fork) methods to create
instances of `ChildProcess`.
I
I
I
I
I
f
exec
Spawns a shell then executes the `command` within that shell, buffering any
generated output. The `command` string passed to the exec function is processed
directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
need to be dealt with accordingly:
```js
import { exec } from 'node:child_process';
exec('"/path/to/test file/test.sh" arg1 arg2');
// Double quotes are used so that the space in the path is not interpreted as
// a delimiter of multiple arguments.
exec('echo "The \\$HOME variable is $HOME"');
// The $HOME variable is escaped in the first instance, but not in the second.
```
**Never pass unsanitized user input to this function. Any input containing shell**
**metacharacters may be used to trigger arbitrary command execution.**
If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The
`error.code` property will be
the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the
process.
The `stdout` and `stderr` arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The `encoding` option
can be used to specify the character encoding used to decode the stdout and
stderr output. If `encoding` is `'buffer'`, or an unrecognized character
encoding, `Buffer` objects will be passed to the callback instead.
```js
import { exec } from 'node:child_process';
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
```
If `timeout` is greater than `0`, the parent will send the signal
identified by the `killSignal` property (the default is `'SIGTERM'`) if the
child runs longer than `timeout` milliseconds.
Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace
the existing process and uses a shell to execute the command.
If this method is invoked as its `util.promisify()` ed version, it returns
a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In
case of an error (including any error resulting in an exit code other than 0), a
rejected promise is returned, with the same `error` object given in the
callback, but with two additional properties `stdout` and `stderr`.
```js
import util from 'node:util';
import child_process from 'node:child_process';
const exec = util.promisify(child_process.exec);
async function lsExample() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();
```
If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
the error passed to the callback will be an `AbortError`:
```js
import { exec } from 'node:child_process';
const controller = new AbortController();
const { signal } = controller;
const child = exec('grep ssh', { signal }, (error) => {
console.error(error); // an AbortError
});
controller.abort();
```
f
execFile
The `child_process.execFile()` function is similar to [exec](././node__child_process.d.ts/~/exec) except that it does not spawn a shell by default. Rather, the specified
executable `file` is spawned directly as a new process making it slightly more
efficient than [exec](././node__child_process.d.ts/~/exec).
The same options as [exec](././node__child_process.d.ts/~/exec) are supported. Since a shell is
not spawned, behaviors such as I/O redirection and file globbing are not
supported.
```js
import { execFile } from 'node:child_process';
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
```
The `stdout` and `stderr` arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The `encoding` option
can be used to specify the character encoding used to decode the stdout and
stderr output. If `encoding` is `'buffer'`, or an unrecognized character
encoding, `Buffer` objects will be passed to the callback instead.
If this method is invoked as its `util.promisify()` ed version, it returns
a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In
case of an error (including any error resulting in an exit code other than 0), a
rejected promise is returned, with the same `error` object given in the
callback, but with two additional properties `stdout` and `stderr`.
```js
import util from 'node:util';
import child_process from 'node:child_process';
const execFile = util.promisify(child_process.execFile);
async function getVersion() {
const { stdout } = await execFile('node', ['--version']);
console.log(stdout);
}
getVersion();
```
**If the `shell` option is enabled, do not pass unsanitized user input to this**
**function. Any input containing shell metacharacters may be used to trigger**
**arbitrary command execution.**
If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
the error passed to the callback will be an `AbortError`:
```js
import { execFile } from 'node:child_process';
const controller = new AbortController();
const { signal } = controller;
const child = execFile('node', ['--version'], { signal }, (error) => {
console.error(error); // an AbortError
});
controller.abort();
```
T
ExecFileException
No documentation available
I
I
I
I
f
execFileSync
The `child_process.execFileSync()` method is generally identical to [execFile](././node__child_process.d.ts/~/execFile) with the exception that the method will not
return until the child process has fully closed. When a timeout has been
encountered and `killSignal` is sent, the method won't return until the process
has completely exited.
If the child process intercepts and handles the `SIGTERM` signal and
does not exit, the parent process will still wait until the child process has
exited.
If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying [spawnSync](././node__child_process.d.ts/~/spawnSync).
**If the `shell` option is enabled, do not pass unsanitized user input to this**
**function. Any input containing shell metacharacters may be used to trigger**
**arbitrary command execution.**
I
I
I
I
I
I
f
execSync
The `child_process.execSync()` method is generally identical to [exec](././node__child_process.d.ts/~/exec) with the exception that the method will not return
until the child process has fully closed. When a timeout has been encountered
and `killSignal` is sent, the method won't return until the process has
completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process
has exited.
If the process times out or has a non-zero exit code, this method will throw.
The `Error` object will contain the entire result from [spawnSync](././node__child_process.d.ts/~/spawnSync).
**Never pass unsanitized user input to this function. Any input containing shell**
**metacharacters may be used to trigger arbitrary command execution.**
I
I
I
f
fork
The `child_process.fork()` method is a special case of [spawn](././node__child_process.d.ts/~/spawn) used specifically to spawn new Node.js processes.
Like [spawn](././node__child_process.d.ts/~/spawn), a `ChildProcess` object is returned. The
returned `ChildProcess` will have an additional communication channel
built-in that allows messages to be passed back and forth between the parent and
child. See `subprocess.send()` for details.
Keep in mind that spawned Node.js child processes are
independent of the parent with exception of the IPC communication channel
that is established between the two. Each process has its own memory, with
their own V8 instances. Because of the additional resource allocations
required, spawning a large number of child Node.js processes is not
recommended.
By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative
execution path to be used.
Node.js processes launched with a custom `execPath` will communicate with the
parent process using the file descriptor (fd) identified using the
environment variable `NODE_CHANNEL_FD` on the child process.
Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the
current process.
The `shell` option available in [spawn](././node__child_process.d.ts/~/spawn) is not supported by `child_process.fork()` and will be ignored if set.
If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
the error passed to the callback will be an `AbortError`:
```js
if (process.argv[2] === 'child') {
setTimeout(() => {
console.log(`Hello from ${process.argv[2]}!`);
}, 1_000);
} else {
import { fork } from 'node:child_process';
const controller = new AbortController();
const { signal } = controller;
const child = fork(__filename, ['child'], { signal });
child.on('error', (err) => {
// This will be called with err being an AbortError if the controller aborts
});
controller.abort(); // Stops the child process
}
```
I
T
IOType
No documentation available
I
I
I
I
T
SendHandle
No documentation available
T
Serializable
No documentation available
T
SerializationType
No documentation available
f
spawn
The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults
to an empty array.
**If the `shell` option is enabled, do not pass unsanitized user input to this**
**function. Any input containing shell metacharacters may be used to trigger**
**arbitrary command execution.**
A third argument may be used to specify additional options, with these defaults:
```js
const defaults = {
cwd: undefined,
env: process.env,
};
```
Use `cwd` to specify the working directory from which the process is spawned.
If not given, the default is to inherit the current working directory. If given,
but the path does not exist, the child process emits an `ENOENT` error
and exits immediately. `ENOENT` is also emitted when the command
does not exist.
Use `env` to specify environment variables that will be visible to the new
process, the default is `process.env`.
`undefined` values in `env` will be ignored.
Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
exit code:
```js
import { spawn } from 'node:child_process';
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
```
Example: A very elaborate way to run `ps ax | grep ssh`
```js
import { spawn } from 'node:child_process';
const ps = spawn('ps', ['ax']);
const grep = spawn('grep', ['ssh']);
ps.stdout.on('data', (data) => {
grep.stdin.write(data);
});
ps.stderr.on('data', (data) => {
console.error(`ps stderr: ${data}`);
});
ps.on('close', (code) => {
if (code !== 0) {
console.log(`ps process exited with code ${code}`);
}
grep.stdin.end();
});
grep.stdout.on('data', (data) => {
console.log(data.toString());
});
grep.stderr.on('data', (data) => {
console.error(`grep stderr: ${data}`);
});
grep.on('close', (code) => {
if (code !== 0) {
console.log(`grep process exited with code ${code}`);
}
});
```
Example of checking for failed `spawn`:
```js
import { spawn } from 'node:child_process';
const subprocess = spawn('bad_command');
subprocess.on('error', (err) => {
console.error('Failed to start subprocess.');
});
```
Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
title while others (Windows, SunOS) will use `command`.
Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve
it with the `process.argv0` property instead.
If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except
the error passed to the callback will be an `AbortError`:
```js
import { spawn } from 'node:child_process';
const controller = new AbortController();
const { signal } = controller;
const grep = spawn('grep', ['ssh'], { signal });
grep.on('error', (err) => {
// This will be called with err being an AbortError if the controller aborts
});
controller.abort(); // Stops the child process
```
I
I
I
f
spawnSync
The `child_process.spawnSync()` method is generally identical to [spawn](././node__child_process.d.ts/~/spawn) with the exception that the function will not return
until the child process has fully closed. When a timeout has been encountered
and `killSignal` is sent, the method won't return until the process has
completely exited. If the process intercepts and handles the `SIGTERM` signal
and doesn't exit, the parent process will wait until the child process has
exited.
**If the `shell` option is enabled, do not pass unsanitized user input to this**
**function. Any input containing shell metacharacters may be used to trigger**
**arbitrary command execution.**
I
I
I
T
StdioNull
No documentation available
T
StdioOptions
No documentation available
T
StdioPipe
No documentation available
T
StdioPipeNamed
No documentation available
node__cluster.d.ts
> [!WARNING] Deno compatibility > All exports are non-functional stubs. Clusters of Node.js processes can be used to run multiple instances of Node.js that can distribute workloads among their application threads. When process isolation is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html) module instead, which allows running multiple application threads within a single Node.js instance. The cluster module allows easy creation of child processes that all share server ports. ```js 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('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); } ``` Running Node.js will now share port 8000 between the workers: ```console $ node server.js Primary 3596 is running Worker 4324 started Worker 4520 started Worker 6056 started Worker 5644 started ``` On Windows, it is not yet possible to set up a named pipe server in a worker.I
Address
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
I
Cluster
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
v
cluster
No documentation available
I
ClusterSettings
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
v
default
No documentation available
T
SerializationType
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
c
Worker
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
A `Worker` object contains all public information and method about a worker.
In the primary it can be obtained using `cluster.workers`. In a worker
it can be obtained using `cluster.worker`.
node__console.d.ts
The `node:console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```I
N
v
console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
I
I
console.ConsoleConstructorOptions
No documentation available
node__crypto.d.ts
The `node:crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. ```js const { createHmac } = await import('node:crypto'); const secret = 'abcdefg'; const hash = createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints: // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e ```I
I
T
BinaryLike
No documentation available
T
BinaryToTextEncoding
No documentation available
c
Certificate
> [!WARNING] Deno compatibility
> The methods are non-functional stubs.
SPKAC is a Certificate Signing Request mechanism originally implemented by
Netscape and was specified formally as part of HTML5's `keygen` element.
`` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
should not use this element anymore.
The `node:crypto` module provides the `Certificate` class for working with SPKAC
data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC
implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally.
T
CharacterEncoding
No documentation available
f
checkPrime
Checks the primality of the `candidate`.
I
f
checkPrimeSync
Checks the primality of the `candidate`.
c
Cipher
Instances of the `Cipher` class are used to encrypt data. The class can be
used in one of two ways:
* As a `stream` that is both readable and writable, where plain unencrypted
data is written to produce encrypted data on the readable side, or
* Using the `cipher.update()` and `cipher.final()` methods to produce
the encrypted data.
The [createCipheriv](././node__crypto.d.ts/~/createCipheriv) method is
used to create `Cipher` instances. `Cipher` objects are not to be created
directly using the `new` keyword.
Example: Using `Cipher` objects as streams:
```js
const {
scrypt,
randomFill,
createCipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// First, we'll generate the key. The key length is dependent on the algorithm.
// In this case for aes192, it is 24 bytes (192 bits).
scrypt(password, 'salt', 24, (err, key) => {
if (err) throw err;
// Then, we'll generate a random initialization vector
randomFill(new Uint8Array(16), (err, iv) => {
if (err) throw err;
// Once we have the key and iv, we can create and use the cipher...
const cipher = createCipheriv(algorithm, key, iv);
let encrypted = '';
cipher.setEncoding('hex');
cipher.on('data', (chunk) => encrypted += chunk);
cipher.on('end', () => console.log(encrypted));
cipher.write('some clear text data');
cipher.end();
});
});
```
Example: Using `Cipher` and piped streams:
```js
import {
createReadStream,
createWriteStream,
} from 'node:fs';
import {
pipeline,
} from 'node:stream';
const {
scrypt,
randomFill,
createCipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// First, we'll generate the key. The key length is dependent on the algorithm.
// In this case for aes192, it is 24 bytes (192 bits).
scrypt(password, 'salt', 24, (err, key) => {
if (err) throw err;
// Then, we'll generate a random initialization vector
randomFill(new Uint8Array(16), (err, iv) => {
if (err) throw err;
const cipher = createCipheriv(algorithm, key, iv);
const input = createReadStream('test.js');
const output = createWriteStream('test.enc');
pipeline(input, cipher, output, (err) => {
if (err) throw err;
});
});
});
```
Example: Using the `cipher.update()` and `cipher.final()` methods:
```js
const {
scrypt,
randomFill,
createCipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// First, we'll generate the key. The key length is dependent on the algorithm.
// In this case for aes192, it is 24 bytes (192 bits).
scrypt(password, 'salt', 24, (err, key) => {
if (err) throw err;
// Then, we'll generate a random initialization vector
randomFill(new Uint8Array(16), (err, iv) => {
if (err) throw err;
const cipher = createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
});
});
```
I
I
T
CipherCCMTypes
No documentation available
I
I
T
CipherGCMTypes
No documentation available
I
T
CipherKey
No documentation available
T
CipherMode
No documentation available
I
I
T
CipherOCBTypes
No documentation available
N
constants
No documentation available
v
constants.defaultCipherList
Specifies the active default cipher list used by the current Node.js process (colon-separated values).
v
constants.defaultCoreCipherList
Specifies the built-in default cipher list used by Node.js (colon-separated values).
v
constants.DH_CHECK_P_NOT_PRIME
No documentation available
v
constants.DH_CHECK_P_NOT_SAFE_PRIME
No documentation available
v
constants.DH_NOT_SUITABLE_GENERATOR
No documentation available
v
constants.DH_UNABLE_TO_CHECK_GENERATOR
No documentation available
v
constants.ENGINE_METHOD_ALL
No documentation available
v
constants.ENGINE_METHOD_CIPHERS
No documentation available
v
constants.ENGINE_METHOD_DH
No documentation available
v
constants.ENGINE_METHOD_DIGESTS
No documentation available
v
constants.ENGINE_METHOD_DSA
No documentation available
v
constants.ENGINE_METHOD_EC
No documentation available
v
constants.ENGINE_METHOD_NONE
No documentation available
v
constants.ENGINE_METHOD_PKEY_ASN1_METHS
No documentation available
v
constants.ENGINE_METHOD_PKEY_METHS
No documentation available
v
constants.ENGINE_METHOD_RAND
No documentation available
v
constants.ENGINE_METHOD_RSA
No documentation available
v
constants.OPENSSL_VERSION_NUMBER
No documentation available
v
constants.POINT_CONVERSION_COMPRESSED
No documentation available
v
constants.POINT_CONVERSION_HYBRID
No documentation available
v
constants.POINT_CONVERSION_UNCOMPRESSED
No documentation available
v
constants.RSA_NO_PADDING
No documentation available
v
constants.RSA_PKCS1_OAEP_PADDING
No documentation available
v
constants.RSA_PKCS1_PADDING
No documentation available
v
constants.RSA_PKCS1_PSS_PADDING
No documentation available
v
constants.RSA_PSS_SALTLEN_AUTO
Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature.
v
constants.RSA_PSS_SALTLEN_DIGEST
Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying.
v
constants.RSA_PSS_SALTLEN_MAX_SIGN
Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data.
v
constants.RSA_SSLV23_PADDING
No documentation available
v
constants.RSA_X931_PADDING
No documentation available
v
constants.SSL_OP_ALL
Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail.
v
constants.SSL_OP_ALLOW_NO_DHE_KEX
Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3
v
constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
v
constants.SSL_OP_CIPHER_SERVER_PREFERENCE
Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
v
constants.SSL_OP_CISCO_ANYCONNECT
Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER.
v
constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG
Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft.
v
constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d.
v
constants.SSL_OP_LEGACY_SERVER_CONNECT
Allows initial connection to servers that do not support RI.
v
constants.SSL_OP_NO_COMPRESSION
Instructs OpenSSL to disable support for SSL/TLS compression.
v
constants.SSL_OP_NO_ENCRYPT_THEN_MAC
Instructs OpenSSL to disable encrypt-then-MAC.
v
constants.SSL_OP_NO_QUERY_MTU
No documentation available
v
constants.SSL_OP_NO_RENEGOTIATION
Instructs OpenSSL to disable renegotiation.
v
constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
Instructs OpenSSL to always start a new session when performing renegotiation.
v
constants.SSL_OP_NO_SSLv2
Instructs OpenSSL to turn off SSL v2
v
constants.SSL_OP_NO_SSLv3
Instructs OpenSSL to turn off SSL v3
v
constants.SSL_OP_NO_TICKET
Instructs OpenSSL to disable use of RFC4507bis tickets.
v
constants.SSL_OP_NO_TLSv1
Instructs OpenSSL to turn off TLS v1
v
constants.SSL_OP_NO_TLSv1_1
Instructs OpenSSL to turn off TLS v1.1
v
constants.SSL_OP_NO_TLSv1_2
Instructs OpenSSL to turn off TLS v1.2
v
constants.SSL_OP_NO_TLSv1_3
Instructs OpenSSL to turn off TLS v1.3
v
constants.SSL_OP_PRIORITIZE_CHACHA
Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled.
v
constants.SSL_OP_TLS_ROLLBACK_BUG
Instructs OpenSSL to disable version rollback attack detection.
f
createCipheriv
Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
initialization vector (`iv`).
The `options` argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
recent OpenSSL releases, `openssl list -cipher-algorithms` will
display the available cipher algorithms.
The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
a `KeyObject` of type `secret`. If the cipher does not need
an initialization vector, `iv` may be `null`.
When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a
given IV will be.
f
createDecipheriv
Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`).
The `options` argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the
authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags
to those with the specified length.
For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
recent OpenSSL releases, `openssl list -cipher-algorithms` will
display the available cipher algorithms.
The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
a `KeyObject` of type `secret`. If the cipher does not need
an initialization vector, `iv` may be `null`.
When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a given
IV will be.
f
createDiffieHellman
Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
optional specific `generator`.
The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used.
If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
a `Buffer`, `TypedArray`, or `DataView` is expected.
If `generatorEncoding` is specified, `generator` is expected to be a string;
otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected.
f
createDiffieHellmanGroup
An alias for [getDiffieHellman](././node__crypto.d.ts/~/getDiffieHellman)
f
createECDH
Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
predefined curve specified by the `curveName` string. Use [getCurves](././node__crypto.d.ts/~/getCurves) to obtain a list of available curve names. On recent
OpenSSL releases, `openssl ecparam -list_curves` will also display the name
and description of each available elliptic curve.
f
createHash
Creates and returns a `Hash` object that can be used to generate hash digests
using the given `algorithm`. Optional `options` argument controls stream
behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
can be used to specify the desired output length in bytes.
The `algorithm` is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
On recent releases of OpenSSL, `openssl list -digest-algorithms` will
display the available digest algorithms.
Example: generating the sha256 sum of a file
```js
import {
createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
createHash,
} = await import('node:crypto');
const filename = argv[2];
const hash = createHash('sha256');
const input = createReadStream(filename);
input.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
```
f
createHmac
Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
Optional `options` argument controls stream behavior.
The `algorithm` is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
On recent releases of OpenSSL, `openssl list -digest-algorithms` will
display the available digest algorithms.
The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was
obtained from a cryptographically secure source of entropy, such as [randomBytes](././node__crypto.d.ts/~/randomBytes) or [generateKey](././node__crypto.d.ts/~/generateKey), its length should not
exceed the block size of `algorithm` (e.g., 512 bits for SHA-256).
Example: generating the sha256 HMAC of a file
```js
import {
createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
createHmac,
} = await import('node:crypto');
const filename = argv[2];
const hmac = createHmac('sha256', 'a secret');
const input = createReadStream(filename);
input.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = input.read();
if (data)
hmac.update(data);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
```
f
createPrivateKey
Creates and returns a new key object containing a private key. If `key` is a
string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above.
If the private key is encrypted, a `passphrase` must be specified. The length
of the passphrase is limited to 1024 bytes.
f
createPublicKey
Creates and returns a new key object containing a public key. If `key` is a
string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key;
otherwise, `key` must be an object with the properties described above.
If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
Because public keys can be derived from private keys, a private key may be
passed instead of a public key. In that case, this function behaves as if [createPrivateKey](././node__crypto.d.ts/~/createPrivateKey) had been called, except that the type of the
returned `KeyObject` will be `'public'` and that the private key cannot be
extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned
and it will be impossible to extract the private key from the returned object.
f
createSecretKey
Creates and returns a new key object containing a secret key for symmetric
encryption or `Hmac`.
f
createSign
Creates and returns a `Sign` object that uses the given `algorithm`. Use [getHashes](././node__crypto.d.ts/~/getHashes) to obtain the names of the available digest algorithms.
Optional `options` argument controls the `stream.Writable` behavior.
In some cases, a `Sign` instance can be created using the name of a signature
algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
algorithm names.
f
createVerify
Creates and returns a `Verify` object that uses the given algorithm.
Use [getHashes](././node__crypto.d.ts/~/getHashes) to obtain an array of names of the available
signing algorithms. Optional `options` argument controls the `stream.Writable` behavior.
In some cases, a `Verify` instance can be created using the name of a signature
algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
algorithm names.
v
crypto
No documentation available
c
Decipher
Instances of the `Decipher` class are used to decrypt data. The class can be
used in one of two ways:
* As a `stream` that is both readable and writable, where plain encrypted
data is written to produce unencrypted data on the readable side, or
* Using the `decipher.update()` and `decipher.final()` methods to
produce the unencrypted data.
The [createDecipheriv](././node__crypto.d.ts/~/createDecipheriv) method is
used to create `Decipher` instances. `Decipher` objects are not to be created
directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
```js
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
let decrypted = '';
decipher.on('readable', () => {
let chunk;
while (null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8');
}
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
// Encrypted with same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
```
Example: Using `Decipher` and piped streams:
```js
import {
createReadStream,
createWriteStream,
} from 'node:fs';
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
```
Example: Using the `decipher.update()` and `decipher.final()` methods:
```js
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv,
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
// Encrypted using same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
```
I
I
I
c
DiffieHellman
The `DiffieHellman` class is a utility for creating Diffie-Hellman key
exchanges.
Instances of the `DiffieHellman` class can be created using the [createDiffieHellman](././node__crypto.d.ts/~/createDiffieHellman) function.
```js
import assert from 'node:assert';
const {
createDiffieHellman,
} = await import('node:crypto');
// Generate Alice's keys...
const alice = createDiffieHellman(2048);
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
```
f
diffieHellman
Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
T
v
DiffieHellmanGroup
No documentation available
I
T
DSAEncoding
No documentation available
I
I
DSAKeyPairOptions
No documentation available
c
ECDH
> [!WARNING] Deno compatibility
> The `convertKey` method is a non-functional sub.
The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
key exchanges.
Instances of the `ECDH` class can be created using the [createECDH](././node__crypto.d.ts/~/createECDH) function.
```js
import assert from 'node:assert';
const {
createECDH,
} = await import('node:crypto');
// Generate Alice's keys...
const alice = createECDH('secp521r1');
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createECDH('secp521r1');
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
```
T
ECDHKeyFormat
No documentation available
I
I
I
ED25519KeyPairKeyObjectOptions
No documentation available
I
I
ED448KeyPairKeyObjectOptions
No documentation available
I
T
Encoding
No documentation available
f
generateKey
Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
```js
const {
generateKey,
} = await import('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
```
The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See [createHmac](././node__crypto.d.ts/~/createHmac) for more information.
f
generateKeyPair
> [!WARNING] Deno compatibility
> The `x448` option is not supported.
Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.
If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
behaves as if `keyObject.export()` had been called on its result. Otherwise,
the respective part of the key is returned as a `KeyObject`.
It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage:
```js
const {
generateKeyPair,
} = await import('node:crypto');
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
```
On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair.
If this method is invoked as its `util.promisify()` ed version, it returns
a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
f
generateKeyPairSync
Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
Ed25519, Ed448, X25519, X448, and DH are currently supported.
If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
behaves as if `keyObject.export()` had been called on its result. Otherwise,
the respective part of the key is returned as a `KeyObject`.
When encoding public keys, it is recommended to use `'spki'`. When encoding
private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
and to keep the passphrase confidential.
```js
const {
generateKeyPairSync,
} = await import('node:crypto');
const {
publicKey,
privateKey,
} = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
});
```
The return value `{ publicKey, privateKey }` represents the generated key pair.
When PEM encoding was selected, the respective key will be a string, otherwise
it will be a buffer containing the data encoded as DER.
f
generateKeySync
Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
```js
const {
generateKeySync,
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex')); // e89..........41e
```
The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See [createHmac](././node__crypto.d.ts/~/createHmac) for more information.
f
generatePrime
> [!WARNING] Deno compatibility
> The `safe`, `add` and `rem` option is not supported.
Generates a pseudorandom prime of `size` bits.
If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime.
The `options.add` and `options.rem` parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:
* If `options.add` and `options.rem` are both set, the prime will satisfy the
condition that `prime % add = rem`.
* If only `options.add` is set and `options.safe` is not `true`, the prime will
satisfy the condition that `prime % add = 1`.
* If only `options.add` is set and `options.safe` is set to `true`, the prime
will instead satisfy the condition that `prime % add = 3`. This is necessary
because `prime % add = 1` for `options.add > 2` would contradict the condition
enforced by `options.safe`.
* `options.rem` is ignored if `options.add` is not given.
Both `options.add` and `options.rem` must be encoded as big-endian sequences
if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`.
By default, the prime is encoded as a big-endian sequence of octets
in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
[bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
I
I
I
f
generatePrimeSync
Generates a pseudorandom prime of `size` bits.
If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime.
The `options.add` and `options.rem` parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:
* If `options.add` and `options.rem` are both set, the prime will satisfy the
condition that `prime % add = rem`.
* If only `options.add` is set and `options.safe` is not `true`, the prime will
satisfy the condition that `prime % add = 1`.
* If only `options.add` is set and `options.safe` is set to `true`, the prime
will instead satisfy the condition that `prime % add = 3`. This is necessary
because `prime % add = 1` for `options.add > 2` would contradict the condition
enforced by `options.safe`.
* `options.rem` is ignored if `options.add` is not given.
Both `options.add` and `options.rem` must be encoded as big-endian sequences
if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`.
By default, the prime is encoded as a big-endian sequence of octets
in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
[bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
f
getCipherInfo
Returns information about a given cipher.
Some ciphers accept variable length keys and initialization vectors. By default,
the `crypto.getCipherInfo()` method will return the default values for these
ciphers. To test if a given key length or iv length is acceptable for given
cipher, use the `keyLength` and `ivLength` options. If the given values are
unacceptable, `undefined` will be returned.
f
getCiphers
```js
const {
getCiphers,
} = await import('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
```
f
getCurves
```js
const {
getCurves,
} = await import('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
```
f
getDiffieHellman
Creates a predefined `DiffieHellmanGroup` key exchange object. The
supported groups are listed in the documentation for `DiffieHellmanGroup`.
The returned object mimics the interface of objects created by [createDiffieHellman](././node__crypto.d.ts/~/createDiffieHellman), but will not allow changing
the keys (with `diffieHellman.setPublicKey()`, for example). The
advantage of using this method is that the parties do not have to
generate nor exchange a group modulus beforehand, saving both processor
and communication time.
Example (obtaining a shared secret):
```js
const {
getDiffieHellman,
} = await import('node:crypto');
const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same
console.log(aliceSecret === bobSecret);
```
f
getFips
No documentation available
f
getHashes
```js
const {
getHashes,
} = await import('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
```
f
getRandomValues
A convenient alias for webcrypto.getRandomValues. This
implementation is not compliant with the Web Crypto spec, to write
web-compatible code use webcrypto.getRandomValues instead.
c
Hash
The `Hash` class is a utility for creating hash digests of data. It can be
used in one of two ways:
* As a `stream` that is both readable and writable, where data is written
to produce a computed hash digest on the readable side, or
* Using the `hash.update()` and `hash.digest()` methods to produce the
computed hash.
The [createHash](././node__crypto.d.ts/~/createHash) method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
Example: Using `Hash` objects as streams:
```js
const {
createHash,
} = await import('node:crypto');
const hash = createHash('sha256');
hash.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = hash.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
}
});
hash.write('some data to hash');
hash.end();
```
Example: Using `Hash` and piped streams:
```js
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const { createHash } = await import('node:crypto');
const hash = createHash('sha256');
const input = createReadStream('test.js');
input.pipe(hash).setEncoding('hex').pipe(stdout);
```
Example: Using the `hash.update()` and `hash.digest()` methods:
```js
const {
createHash,
} = await import('node:crypto');
const hash = createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
```
f
hash
A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data
(<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm`
is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases
of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms.
Example:
```js
import crypto from 'node:crypto';
import { Buffer } from 'node:buffer';
// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));
// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
//
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));
```
I
f
hkdf
HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set;
otherwise `err` will be `null`. The successfully generated `derivedKey` will
be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
of the input arguments specify invalid values or types.
```js
import { Buffer } from 'node:buffer';
const {
hkdf,
} = await import('node:crypto');
hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});
```
f
hkdfSync
Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The
given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.
```js
import { Buffer } from 'node:buffer';
const {
hkdfSync,
} = await import('node:crypto');
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
```
I
I
I
T
KeyFormat
No documentation available
T
KeyLike
No documentation available
c
KeyObject
> [!WARNING] Deno compatibility
> The following are non-functional stubs:
> - from
> - symmetricKeySize
> - equals
> - export
>
Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
and each kind of key exposes different functions. The [createSecretKey](././node__crypto.d.ts/~/createSecretKey), [createPublicKey](././node__crypto.d.ts/~/createPublicKey) and [createPrivateKey](././node__crypto.d.ts/~/createPrivateKey) methods are used to create `KeyObject`instances. `KeyObject`
objects are not to be created directly using the `new`keyword.
Most applications should consider using the new `KeyObject` API instead of
passing keys as strings or `Buffer`s due to improved security features.
`KeyObject` instances can be passed to other threads via `postMessage()`.
The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
be listed in the `transferList` argument.
T
KeyObjectType
No documentation available
I
I
T
KeyType
No documentation available
T
LargeNumberLike
No documentation available
T
LegacyCharacterEncoding
No documentation available
f
pbkdf2
Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by `digest` is
applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`.
The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set;
otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be
thrown if any of the input arguments specify invalid values or types.
The `iterations` argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.
The `salt` should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
```js
const {
pbkdf2,
} = await import('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
```
An array of supported digest functions can be retrieved using [getHashes](././node__crypto.d.ts/~/getHashes).
This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
f
pbkdf2Sync
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by `digest` is
applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`.
If an error occurs an `Error` will be thrown, otherwise the derived key will be
returned as a `Buffer`.
The `iterations` argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.
The `salt` should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
```js
const {
pbkdf2Sync,
} = await import('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
```
An array of supported digest functions can be retrieved using [getHashes](././node__crypto.d.ts/~/getHashes).
f
privateDecrypt
Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
the corresponding public key, for example using [publicEncrypt](././node__crypto.d.ts/~/publicEncrypt).
If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to [createPrivateKey](././node__crypto.d.ts/~/createPrivateKey). If it is an
object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`.
f
privateEncrypt
Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
the corresponding public key, for example using [publicDecrypt](././node__crypto.d.ts/~/publicDecrypt).
If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to [createPrivateKey](././node__crypto.d.ts/~/createPrivateKey). If it is an
object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`.
I
f
pseudoRandomBytes
No documentation available
f
publicDecrypt
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
Decrypts `buffer` with `key`.`buffer` was previously encrypted using
the corresponding private key, for example using [privateEncrypt](././node__crypto.d.ts/~/privateEncrypt).
If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to [createPublicKey](././node__crypto.d.ts/~/createPublicKey). If it is an
object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`.
Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.
f
publicEncrypt
Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using
the corresponding private key, for example using [privateDecrypt](././node__crypto.d.ts/~/privateDecrypt).
If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to [createPublicKey](././node__crypto.d.ts/~/createPublicKey). If it is an
object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`.
Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.
I
f
randomBytes
Generates cryptographically strong pseudorandom data. The `size` argument
is a number indicating the number of bytes to generate.
If a `callback` function is provided, the bytes are generated asynchronously
and the `callback` function is invoked with two arguments: `err` and `buf`.
If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes.
```js
// Asynchronous
const {
randomBytes,
} = await import('node:crypto');
randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
```
If the `callback` function is not provided, the random bytes are generated
synchronously and returned as a `Buffer`. An error will be thrown if
there is a problem generating the bytes.
```js
// Synchronous
const {
randomBytes,
} = await import('node:crypto');
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
```
The `crypto.randomBytes()` method will not complete until there is
sufficient entropy available.
This should normally never take longer than a few milliseconds. The only time
when generating the random bytes may conceivably block for a longer period of
time is right after boot, when the whole system is still low on entropy.
This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
The asynchronous version of `crypto.randomBytes()` is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large `randomBytes` requests when doing so as part of fulfilling a client
request.
f
randomFill
This function is similar to [randomBytes](././node__crypto.d.ts/~/randomBytes) but requires the first
argument to be a `Buffer` that will be filled. It also
requires that a callback is passed in.
If the `callback` function is not provided, an error will be thrown.
```js
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
const buf = Buffer.alloc(10);
randomFill(buf, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
randomFill(buf, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
// The above is equivalent to the following:
randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
```
Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`.
While this includes instances of `Float32Array` and `Float64Array`, this
function should not be used to generate random floating-point numbers. The
result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.
```js
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
const a = new Uint32Array(10);
randomFill(a, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const b = new DataView(new ArrayBuffer(10));
randomFill(b, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const c = new ArrayBuffer(10);
randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});
```
This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
The asynchronous version of `crypto.randomFill()` is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large `randomFill` requests when doing so as part of fulfilling a client
request.
f
randomFillSync
Synchronous version of [randomFill](././node__crypto.d.ts/~/randomFill).
```js
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));
randomFillSync(buf, 5);
console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
```
Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`.
```js
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
a.byteOffset, a.byteLength).toString('hex'));
const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
b.byteOffset, b.byteLength).toString('hex'));
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
```
f
randomInt
Return a random integer `n` such that `min <= n < max`. This
implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias).
The range (`max - min`) must be less than 2**48. `min` and `max` must
be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
If the `callback` function is not provided, the random integer is
generated synchronously.
```js
// Asynchronous
const {
randomInt,
} = await import('node:crypto');
randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
```
```js
// Synchronous
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
```
```js
// With `min` argument
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
```
f
randomUUID
Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a
cryptographic pseudorandom number generator.
I
I
I
RSAKeyPairOptions
No documentation available
I
I
RSAPSSKeyPairKeyObjectOptions
No documentation available
I
I
f
scrypt
Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.
The `salt` should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the
callback as a `Buffer`.
An exception is thrown when any of the input arguments specify invalid values
or types.
```js
const {
scrypt,
} = await import('node:crypto');
// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
```
I
f
scryptSync
Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.
The `salt` should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
An exception is thrown when key derivation fails, otherwise the derived key is
returned as a `Buffer`.
An exception is thrown when any of the input arguments specify invalid values
or types.
```js
const {
scryptSync,
} = await import('node:crypto');
// Using the factory defaults.
const key1 = scryptSync('password', 'salt', 64);
console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'
```
I
f
secureHeapUsed
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
f
setEngine
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
Load and set the `engine` for some or all OpenSSL functions (selected by flags).
`engine` could be either an id or a path to the engine's shared library.
The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`):
* `crypto.constants.ENGINE_METHOD_RSA`
* `crypto.constants.ENGINE_METHOD_DSA`
* `crypto.constants.ENGINE_METHOD_DH`
* `crypto.constants.ENGINE_METHOD_RAND`
* `crypto.constants.ENGINE_METHOD_EC`
* `crypto.constants.ENGINE_METHOD_CIPHERS`
* `crypto.constants.ENGINE_METHOD_DIGESTS`
* `crypto.constants.ENGINE_METHOD_PKEY_METHS`
* `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
* `crypto.constants.ENGINE_METHOD_ALL`
* `crypto.constants.ENGINE_METHOD_NONE`
f
setFips
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
Throws an error if FIPS mode is not available.
c
Sign
> [!WARNING] Deno compatibility
> The `sign` and `verify` methods are not supported with non BinaryLike input.
The `Sign` class is a utility for generating signatures. It can be used in one
of two ways:
* As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or
* Using the `sign.update()` and `sign.sign()` methods to produce the
signature.
The [createSign](././node__crypto.d.ts/~/createSign) method is used to create `Sign` instances. The
argument is the string name of the hash function to use. `Sign` objects are not
to be created directly using the `new` keyword.
Example: Using `Sign` and `Verify` objects as streams:
```js
const {
generateKeyPairSync,
createSign,
createVerify,
} = await import('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const sign = createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
```
Example: Using the `sign.update()` and `verify.update()` methods:
```js
const {
generateKeyPairSync,
createSign,
createVerify,
} = await import('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);
const verify = createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
```
f
sign
Calculates and returns the signature for `data` using the given private key and
algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
dependent upon the key type (especially Ed25519 and Ed448).
If `key` is not a `KeyObject`, this function behaves as if `key` had been
passed to [createPrivateKey](././node__crypto.d.ts/~/createPrivateKey). If it is an object, the following
additional properties can be passed:
If the `callback` function is provided this function uses libuv's threadpool.
I
I
SignJsonWebKeyInput
No documentation available
I
I
SignPrivateKeyInput
No documentation available
v
subtle
A convenient alias for `crypto.webcrypto.subtle`.
f
timingSafeEqual
This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time
algorithm.
This function does not leak timing information that
would allow an attacker to guess one of the values. This is suitable for
comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/).
`a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
must have the same byte length. An error is thrown if `a` and `b` have
different byte lengths.
If at least one of `a` and `b` is a `TypedArray` with more than one byte per
entry, such as `Uint16Array`, the result will be computed using the platform
byte order.
**When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754**
**encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point**
**numbers `x` and `y` are equal.**
Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
is timing-safe. Care should be taken to ensure that the surrounding code does
not introduce timing vulnerabilities.
T
UUID
No documentation available
c
Verify
The `Verify` class is a utility for verifying signatures. It can be used in one
of two ways:
* As a writable `stream` where written data is used to validate against the
supplied signature, or
* Using the `verify.update()` and `verify.verify()` methods to verify
the signature.
The [createVerify](././node__crypto.d.ts/~/createVerify) method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword.
See `Sign` for examples.
f
verify
Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
key type (especially Ed25519 and Ed448).
If `key` is not a `KeyObject`, this function behaves as if `key` had been
passed to [createPublicKey](././node__crypto.d.ts/~/createPublicKey). If it is an object, the following
additional properties can be passed:
The `signature` argument is the previously calculated signature for the `data`.
Because public keys can be derived from private keys, a private key or a public
key may be passed for `key`.
If the `callback` function is provided this function uses libuv's threadpool.
I
VerifyJsonWebKeyInput
No documentation available
I
I
VerifyPublicKeyInput
No documentation available
N
v
webcrypto
No documentation available
I
I
I
I
I
I
I
T
webcrypto.AlgorithmIdentifier
No documentation available
T
webcrypto.BigInteger
No documentation available
T
webcrypto.BufferSource
No documentation available
I
webcrypto.Crypto
Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class.
`Crypto` is a singleton that provides access to the remainder of the crypto API.
I
I
I
webcrypto.CryptoKeyPair
The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair.
I
I
I
I
I
I
T
webcrypto.HashAlgorithmIdentifier
No documentation available
I
I
I
I
I
T
webcrypto.KeyFormat
No documentation available
T
webcrypto.KeyType
No documentation available
T
webcrypto.KeyUsage
No documentation available
T
webcrypto.NamedCurve
No documentation available
I
I
I
I
I
I
I
I
I
I
I
X25519KeyPairKeyObjectOptions
No documentation available
I
I
X448KeyPairKeyObjectOptions
No documentation available
I
c
X509Certificate
Encapsulates an X509 certificate and provides read-only access to
its information.
```js
const { X509Certificate } = await import('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
```
I
X509CheckOptions
No documentation available
v
fips
No documentation available
c
Hmac
The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
be used in one of two ways:
* As a `stream` that is both readable and writable, where data is written
to produce a computed HMAC digest on the readable side, or
* Using the `hmac.update()` and `hmac.digest()` methods to produce the
computed HMAC digest.
The [createHmac](././node__crypto.d.ts/~/createHmac) method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
Example: Using `Hmac` objects as streams:
```js
const {
createHmac,
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = hmac.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
}
});
hmac.write('some data to hash');
hmac.end();
```
Example: Using `Hmac` and piped streams:
```js
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const {
createHmac,
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
```
Example: Using the `hmac.update()` and `hmac.digest()` methods:
```js
const {
createHmac,
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
```
node__dgram.d.ts
The `node:dgram` module provides an implementation of UDP datagram sockets. ```js 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 ```I
f
createSocket
Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
messages. When `address` and `port` are not passed to `socket.bind()` the
method will bind the socket to the "all interfaces" address on a random port
(it does the right thing for both `udp4` and `udp6` sockets). The bound address
and port can be retrieved using `socket.address().address` and `socket.address().port`.
If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket:
```js
const controller = new AbortController();
const { signal } = controller;
const server = dgram.createSocket({ type: 'udp4', signal });
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
// Later, when you want to close the server.
controller.abort();
```
I
c
Socket
> [!WARNING] Deno compatibility
> The following methods are non-functional stubs:
> - addMembership
> - addSourceSpecificMembership
> - dropMembership
> - dropSourceSpecificMembership
> - setBroadcast
> - setMulticastInterface
> - setMulticastLoopback
> - setMulticastTtl
> - setTtl
>
Encapsulates the datagram functionality.
New instances of `dgram.Socket` are created using [createSocket](././node__dgram.d.ts/~/createSocket).
The `new` keyword is not to be used to create `dgram.Socket` instances.
- addListener
- addMembership
- addSourceSpecificMembership
- address
- bind
- close
- connect
- disconnect
- dropMembership
- dropSourceSpecificMembership
- emit
- getRecvBufferSize
- getSendBufferSize
- getSendQueueCount
- getSendQueueSize
- on
- once
- prependListener
- prependOnceListener
- ref
- remoteAddress
- send
- setBroadcast
- setMulticastInterface
- setMulticastLoopback
- setMulticastTTL
- setRecvBufferSize
- setSendBufferSize
- setTTL
- unref
I
T
SocketType
No documentation available
node__diagnostics_channel.d.ts
The `node:diagnostics_channel` module provides an API to create named channels to report arbitrary message data for diagnostics purposes. It can be accessed using: ```js import diagnostics_channel from 'node:diagnostics_channel'; ``` It is intended that a module writer wanting to report diagnostics messages will create one or many top-level channels to report messages through. Channels may also be acquired at runtime but it is not encouraged due to the additional overhead of doing so. Channels may be exported for convenience, but as long as the name is known it can be acquired anywhere. If you intend for your module to produce diagnostics data for others to consume it is recommended that you include documentation of what named channels are used along with the shape of the message data. Channel names should generally include the module name to avoid collisions with data from other modules.c
Channel
The class `Channel` represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
are subscribers present. It exists as a separate object to avoid channel
lookups at publish time, enabling very fast publish speeds and allowing
for heavy use while incurring very minimal cost. Channels are created with [channel](././node__diagnostics_channel.d.ts/~/channel), constructing a channel directly
with `new Channel(name)` is not supported.
f
channel
This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.
```js
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
```
T
ChannelListener
No documentation available
f
hasSubscribers
Check if there are active subscribers to the named channel. This is helpful if
the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
```js
import diagnostics_channel from 'node:diagnostics_channel';
if (diagnostics_channel.hasSubscribers('my-channel')) {
// There are subscribers, prepare and publish message
}
```
f
subscribe
Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an `'uncaughtException'`.
```js
import diagnostics_channel from 'node:diagnostics_channel';
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
});
```
c
TracingChannel
The class `TracingChannel` is a collection of `TracingChannel Channels` which
together express a single traceable action. It is used to formalize and
simplify the process of producing events for tracing application flow. [tracingChannel](././node__diagnostics_channel.d.ts/~/tracingChannel) is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a
single `TracingChannel` at the top-level of the file rather than creating them
dynamically.
f
tracingChannel
Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing
channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`.
```js
import diagnostics_channel from 'node:diagnostics_channel';
const channelsByName = diagnostics_channel.tracingChannel('my-channel');
// or...
const channelsByCollection = diagnostics_channel.tracingChannel({
start: diagnostics_channel.channel('tracing:my-channel:start'),
end: diagnostics_channel.channel('tracing:my-channel:end'),
asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
error: diagnostics_channel.channel('tracing:my-channel:error'),
});
```
I
I
f
unsubscribe
Remove a message handler previously registered to this channel with [subscribe](././node__diagnostics_channel.d.ts/~/subscribe).
```js
import diagnostics_channel from 'node:diagnostics_channel';
function onMessage(message, name) {
// Received data
}
diagnostics_channel.subscribe('my-channel', onMessage);
diagnostics_channel.unsubscribe('my-channel', onMessage);
```
node__dns--promises.d.ts
The `dns.promises` API provides an alternative set of asynchronous DNS methods that return `Promise` objects rather than using callbacks. The API is accessible via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.v
ADDRGETNETWORKPARAMS
No documentation available
v
BADFAMILY
No documentation available
v
BADFLAGS
No documentation available
v
BADHINTS
No documentation available
v
BADNAME
No documentation available
v
BADQUERY
No documentation available
v
BADRESP
No documentation available
v
BADSTR
No documentation available
v
CANCELLED
No documentation available
v
CONNREFUSED
No documentation available
v
DESTRUCTION
No documentation available
v
EOF
No documentation available
v
FILE
No documentation available
v
FORMERR
No documentation available
f
getDefaultResultOrder
Get the default value for `verbatim` in [lookup](././node__dns--promises.d.ts/~/lookup) and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
The value could be:
* `ipv4first`: for `verbatim` defaulting to `false`.
* `verbatim`: for `verbatim` defaulting to `true`.
f
getServers
Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.
```js
[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]
```
v
LOADIPHLPAPI
No documentation available
f
lookup
Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
AAAA (IPv6) record. All `option` properties are optional. If `options` is an
integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
and IPv6 addresses are both returned if found.
With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
[`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS
protocol. The implementation uses an operating system facility that can
associate names with addresses and vice versa. This implementation can have
subtle but important consequences on the behavior of any Node.js program. Please
take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before
using `dnsPromises.lookup()`.
Example usage:
```js
import dns from 'node:dns';
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dnsPromises.lookup('example.com', options).then((result) => {
console.log('address: %j family: IPv%s', result.address, result.family);
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
});
// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.com', options).then((result) => {
console.log('addresses: %j', result);
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
});
```
f
lookupService
Resolves the given `address` and `port` into a host name and service using
the operating system's underlying `getnameinfo` implementation.
If `address` is not a valid IP address, a `TypeError` will be thrown.
The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
```js
import dnsPromises from 'node:dns';
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
console.log(result.hostname, result.service);
// Prints: localhost ssh
});
```
v
NODATA
No documentation available
v
NOMEM
No documentation available
v
NONAME
No documentation available
v
NOTFOUND
No documentation available
v
NOTIMP
No documentation available
v
NOTINITIALIZED
No documentation available
v
REFUSED
No documentation available
f
resolve
Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
of the resource records. When successful, the `Promise` is resolved with an
array of resource records. The type and structure of individual results vary
based on `rrtype`:
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
f
resolve4
Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
f
resolve6
Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6
addresses.
f
resolveAny
Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
On success, the `Promise` is resolved with an array containing various types of
records. Each object has a property `type` that indicates the type of the
current record. And depending on the `type`, additional properties will be
present on the object:
Here is an example of the result object:
```js
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
```
f
resolveCaa
Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
the `Promise` is resolved with an array of objects containing available
certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
f
resolveCname
Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
the `Promise` is resolved with an array of canonical name records available for
the `hostname` (e.g. `['bar.example.com']`).
f
resolveMx
Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects
containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
f
resolveNaptr
Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array
of objects with the following properties:
* `flags`
* `service`
* `regexp`
* `replacement`
* `order`
* `preference`
```js
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
```
f
resolveNs
Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server
records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
f
resolvePtr
Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings
containing the reply records.
c
Resolver
An independent resolver for DNS requests.
Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect
other resolvers:
```js
import { promises } from 'node:dns';
const resolver = new promises.Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org').then((addresses) => {
// ...
});
// Alternatively, the same code can be written using async-await style.
(async function() {
const addresses = await resolver.resolve4('example.org');
})();
```
The following methods from the `dnsPromises` API are available:
* `resolver.getServers()`
* `resolver.resolve()`
* `resolver.resolve4()`
* `resolver.resolve6()`
* `resolver.resolveAny()`
* `resolver.resolveCaa()`
* `resolver.resolveCname()`
* `resolver.resolveMx()`
* `resolver.resolveNaptr()`
* `resolver.resolveNs()`
* `resolver.resolvePtr()`
* `resolver.resolveSoa()`
* `resolver.resolveSrv()`
* `resolver.resolveTxt()`
* `resolver.reverse()`
* `resolver.setServers()`
f
resolveSoa
Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
the `hostname`. On success, the `Promise` is resolved with an object with the
following properties:
* `nsname`
* `hostmaster`
* `serial`
* `refresh`
* `retry`
* `expire`
* `minttl`
```js
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
```
f
resolveSrv
Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with
the following properties:
* `priority`
* `weight`
* `port`
* `name`
```js
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
```
f
resolveTxt
Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
f
reverse
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
v
SERVFAIL
No documentation available
f
setDefaultResultOrder
Set the default value of `order` in `dns.lookup()` and `[lookup](././node__dns--promises.d.ts/~/lookup)`. The value could be:
* `ipv4first`: sets default `order` to `ipv4first`.
* `ipv6first`: sets default `order` to `ipv6first`.
* `verbatim`: sets default `order` to `verbatim`.
The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
from the main thread won't affect the default dns orders in workers.
f
setServers
Sets the IP address and port of servers to be used when performing DNS
resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
```js
dnsPromises.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]);
```
An error will be thrown if an invalid address is provided.
The `dnsPromises.setServers()` method must not be called while a DNS query is in
progress.
This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.
v
TIMEOUT
No documentation available
node__dns.d.ts
The `node:dns` module enables name resolution. For example, use it to look up IP addresses of host names. Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the DNS protocol for lookups. [lookup](././node__dns.d.ts/~/lookup) uses the operating system facilities to perform name resolution. It may not need to perform any network communication. To perform name resolution the way other applications on the same system do, use [lookup](././node__dns.d.ts/~/lookup). ```js import dns from 'node:dns'; dns.lookup('example.org', (err, address, family) => { console.log('address: %j family: IPv%s', address, family); }); // address: "93.184.216.34" family: IPv4 ``` All other functions in the `node:dns` module connect to an actual DNS server to perform name resolution. They will always use the network to perform DNS queries. These functions do not use the same set of configuration files used by [lookup](././node__dns.d.ts/~/lookup) (e.g. `/etc/hosts`). Use these functions to always perform DNS queries, bypassing other name-resolution facilities. ```js import dns from 'node:dns'; dns.resolve4('archive.org', (err, addresses) => { if (err) throw err; console.log(`addresses: ${JSON.stringify(addresses)}`); addresses.forEach((a) => { dns.reverse(a, (err, hostnames) => { if (err) { throw err; } console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); }); ``` See the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations) for more information.v
ADDRCONFIG
Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are
only returned if the current system has at least one IPv4 address configured.
v
ADDRGETNETWORKPARAMS
No documentation available
v
ALL
If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
well as IPv4 mapped IPv6 addresses.
I
I
I
I
I
I
I
T
AnyRecord
No documentation available
I
I
I
v
BADFAMILY
No documentation available
v
BADFLAGS
No documentation available
v
BADHINTS
No documentation available
v
BADNAME
No documentation available
v
BADQUERY
No documentation available
v
BADRESP
No documentation available
v
BADSTR
No documentation available
I
v
CANCELLED
No documentation available
v
CONNREFUSED
No documentation available
v
DESTRUCTION
No documentation available
v
EOF
No documentation available
v
FILE
No documentation available
v
FORMERR
No documentation available
f
getDefaultResultOrder
Get the default value for `order` in [lookup](././node__dns.d.ts/~/lookup) and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options).
The value could be:
* `ipv4first`: for `order` defaulting to `ipv4first`.
* `ipv6first`: for `order` defaulting to `ipv6first`.
* `verbatim`: for `order` defaulting to `verbatim`.
f
getServers
Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.
```js
[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]
```
v
LOADIPHLPAPI
No documentation available
f
lookup
Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
AAAA (IPv6) record. All `option` properties are optional. If `options` is an
integer, then it must be `4` or `6` – if `options` is `0` or not provided, then
IPv4 and IPv6 addresses are both returned if found.
With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the
properties `address` and `family`.
On error, `err` is an `Error` object, where `err.code` is the error code.
Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
`dns.lookup()` does not necessarily have anything to do with the DNS protocol.
The implementation uses an operating system facility that can associate names
with addresses and vice versa. This implementation can have subtle but
important consequences on the behavior of any Node.js program. Please take some
time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v22.x/api/dns.html#implementation-considerations)
before using `dns.lookup()`.
Example usage:
```js
import dns from 'node:dns';
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.com', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.com', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
```
If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed
version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties.
I
I
I
f
lookupService
Resolves the given `address` and `port` into a host name and service using
the operating system's underlying `getnameinfo` implementation.
If `address` is not a valid IP address, a `TypeError` will be thrown.
The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object,
where `err.code` is the error code.
```js
import dns from 'node:dns';
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
console.log(hostname, service);
// Prints: localhost ssh
});
```
If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v22.x/api/util.html#utilpromisifyoriginal) ed
version, it returns a `Promise` for an `Object` with `hostname` and `service` properties.
I
v
NODATA
No documentation available
v
NOMEM
No documentation available
v
NONAME
No documentation available
v
NOTFOUND
No documentation available
v
NOTIMP
No documentation available
v
NOTINITIALIZED
No documentation available
N
promises
The `dns.promises` API provides an alternative set of asynchronous DNS methods
that return `Promise` objects rather than using callbacks. The API is accessible
via `import { promises as dnsPromises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.
v
promises.ADDRGETNETWORKPARAMS
No documentation available
v
promises.BADFAMILY
No documentation available
v
promises.BADFLAGS
No documentation available
v
promises.BADHINTS
No documentation available
v
promises.BADNAME
No documentation available
v
promises.BADQUERY
No documentation available
v
promises.BADRESP
No documentation available
v
promises.BADSTR
No documentation available
v
promises.CANCELLED
No documentation available
v
promises.CONNREFUSED
No documentation available
v
promises.DESTRUCTION
No documentation available
v
promises.EOF
No documentation available
v
promises.FILE
No documentation available
v
promises.FORMERR
No documentation available
f
promises.getDefaultResultOrder
Get the default value for `verbatim` in [lookup](././node__dns.d.ts/~/lookup) and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
The value could be:
* `ipv4first`: for `verbatim` defaulting to `false`.
* `verbatim`: for `verbatim` defaulting to `true`.
f
promises.getServers
Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.
```js
[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]
```
v
promises.LOADIPHLPAPI
No documentation available
f
promises.lookup
Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
AAAA (IPv6) record. All `option` properties are optional. If `options` is an
integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
and IPv6 addresses are both returned if found.
With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.
[`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS
protocol. The implementation uses an operating system facility that can
associate names with addresses and vice versa. This implementation can have
subtle but important consequences on the behavior of any Node.js program. Please
take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before
using `dnsPromises.lookup()`.
Example usage:
```js
import dns from 'node:dns';
const dnsPromises = dns.promises;
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dnsPromises.lookup('example.com', options).then((result) => {
console.log('address: %j family: IPv%s', result.address, result.family);
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
});
// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.com', options).then((result) => {
console.log('addresses: %j', result);
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
});
```
f
promises.lookupService
Resolves the given `address` and `port` into a host name and service using
the operating system's underlying `getnameinfo` implementation.
If `address` is not a valid IP address, a `TypeError` will be thrown.
The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
```js
import dnsPromises from 'node:dns';
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
console.log(result.hostname, result.service);
// Prints: localhost ssh
});
```
v
promises.NODATA
No documentation available
v
promises.NOMEM
No documentation available
v
promises.NONAME
No documentation available
v
promises.NOTFOUND
No documentation available
v
promises.NOTIMP
No documentation available
v
promises.NOTINITIALIZED
No documentation available
v
promises.REFUSED
No documentation available
f
promises.resolve
Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
of the resource records. When successful, the `Promise` is resolved with an
array of resource records. The type and structure of individual results vary
based on `rrtype`:
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
f
promises.resolve4
Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
f
promises.resolve6
Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6
addresses.
f
promises.resolveAny
Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
On success, the `Promise` is resolved with an array containing various types of
records. Each object has a property `type` that indicates the type of the
current record. And depending on the `type`, additional properties will be
present on the object:
Here is an example of the result object:
```js
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
```
f
promises.resolveCaa
Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
the `Promise` is resolved with an array of objects containing available
certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
f
promises.resolveCname
Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
the `Promise` is resolved with an array of canonical name records available for
the `hostname` (e.g. `['bar.example.com']`).
f
promises.resolveMx
Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects
containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
f
promises.resolveNaptr
Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array
of objects with the following properties:
* `flags`
* `service`
* `regexp`
* `replacement`
* `order`
* `preference`
```js
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
```
f
promises.resolveNs
Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server
records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
f
promises.resolvePtr
Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings
containing the reply records.
c
promises.Resolver
An independent resolver for DNS requests.
Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect
other resolvers:
```js
import { promises } from 'node:dns';
const resolver = new promises.Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org').then((addresses) => {
// ...
});
// Alternatively, the same code can be written using async-await style.
(async function() {
const addresses = await resolver.resolve4('example.org');
})();
```
The following methods from the `dnsPromises` API are available:
* `resolver.getServers()`
* `resolver.resolve()`
* `resolver.resolve4()`
* `resolver.resolve6()`
* `resolver.resolveAny()`
* `resolver.resolveCaa()`
* `resolver.resolveCname()`
* `resolver.resolveMx()`
* `resolver.resolveNaptr()`
* `resolver.resolveNs()`
* `resolver.resolvePtr()`
* `resolver.resolveSoa()`
* `resolver.resolveSrv()`
* `resolver.resolveTxt()`
* `resolver.reverse()`
* `resolver.setServers()`
f
promises.resolveSoa
Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
the `hostname`. On success, the `Promise` is resolved with an object with the
following properties:
* `nsname`
* `hostmaster`
* `serial`
* `refresh`
* `retry`
* `expire`
* `minttl`
```js
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
```
f
promises.resolveSrv
Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with
the following properties:
* `priority`
* `weight`
* `port`
* `name`
```js
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
```
f
promises.resolveTxt
Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
f
promises.reverse
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.
On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
v
promises.SERVFAIL
No documentation available
f
promises.setDefaultResultOrder
Set the default value of `order` in `dns.lookup()` and `[lookup](././node__dns.d.ts/~/lookup)`. The value could be:
* `ipv4first`: sets default `order` to `ipv4first`.
* `ipv6first`: sets default `order` to `ipv6first`.
* `verbatim`: sets default `order` to `verbatim`.
The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
from the main thread won't affect the default dns orders in workers.
f
promises.setServers
Sets the IP address and port of servers to be used when performing DNS
resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
```js
dnsPromises.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]);
```
An error will be thrown if an invalid address is provided.
The `dnsPromises.setServers()` method must not be called while a DNS query is in
progress.
This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.
v
promises.TIMEOUT
No documentation available
I
v
REFUSED
No documentation available
f
resolve
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource
records. The type and structure of individual results varies based on `rrtype`:
On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object,
where `err.code` is one of the `DNS error codes`.
f
resolve4
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function
will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
f
resolve6
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function
will contain an array of IPv6 addresses.
f
resolveAny
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
The `ret` argument passed to the `callback` function will be an array containing
various types of records. Each object has a property `type` that indicates the
type of the current record. And depending on the `type`, additional properties
will be present on the object:
Here is an example of the `ret` object passed to the callback:
```js
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
{ type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
{ type: 'NS', value: 'ns1.example.com' },
{ type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
{ type: 'SOA',
nsname: 'ns1.example.com',
hostmaster: 'admin.example.com',
serial: 156696742,
refresh: 900,
retry: 900,
expire: 1800,
minttl: 60 } ]
```
DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like [resolve4](././node__dns.d.ts/~/resolve4), [resolveMx](././node__dns.d.ts/~/resolveMx), and so on. For more details, see
[RFC 8482](https://tools.ietf.org/html/rfc8482).
f
resolveCaa
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function
will contain an array of certification authority authorization records
available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
f
resolveCname
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function
will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`).
f
resolveMx
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
f
resolveNaptr
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of
objects with the following properties:
* `flags`
* `service`
* `regexp`
* `replacement`
* `order`
* `preference`
```js
{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
```
f
resolveNs
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`).
I
f
resolvePtr
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
be an array of strings containing the reply records.
c
Resolver
An independent resolver for DNS requests.
Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnssetserversservers) does not affect
other resolvers:
```js
import { Resolver } from 'node:dns';
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);
// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org', (err, addresses) => {
// ...
});
```
The following methods from the `node:dns` module are available:
* `resolver.getServers()`
* `resolver.resolve()`
* `resolver.resolve4()`
* `resolver.resolve6()`
* `resolver.resolveAny()`
* `resolver.resolveCaa()`
* `resolver.resolveCname()`
* `resolver.resolveMx()`
* `resolver.resolveNaptr()`
* `resolver.resolveNs()`
* `resolver.resolvePtr()`
* `resolver.resolveSoa()`
* `resolver.resolveSrv()`
* `resolver.resolveTxt()`
* `resolver.reverse()`
* `resolver.setServers()`
I
f
resolveSoa
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
the `hostname`. The `address` argument passed to the `callback` function will
be an object with the following properties:
* `nsname`
* `hostmaster`
* `serial`
* `refresh`
* `retry`
* `expire`
* `minttl`
```js
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
```
f
resolveSrv
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
be an array of objects with the following properties:
* `priority`
* `weight`
* `port`
* `name`
```js
{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
```
f
resolveTxt
> [!WARNING] Deno compatibility
> The `ttl` option is not supported.
Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a
two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.
I
f
reverse
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.
On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-error) object, where `err.code` is
one of the [DNS error codes](https://nodejs.org/docs/latest-v22.x/api/dns.html#error-codes).
v
SERVFAIL
No documentation available
f
setDefaultResultOrder
Set the default value of `order` in [lookup](././node__dns.d.ts/~/lookup) and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v22.x/api/dns.html#dnspromiseslookuphostname-options).
The value could be:
* `ipv4first`: sets default `order` to `ipv4first`.
* `ipv6first`: sets default `order` to `ipv6first`.
* `verbatim`: sets default `order` to `verbatim`.
The default is `verbatim` and [setDefaultResultOrder](././node__dns.d.ts/~/setDefaultResultOrder) have higher
priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--dns-result-orderorder). When using
[worker threads](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html), [setDefaultResultOrder](././node__dns.d.ts/~/setDefaultResultOrder) from the main
thread won't affect the default dns orders in workers.
f
setServers
Sets the IP address and port of servers to be used when performing DNS
resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.
```js
dns.setServers([
'4.4.4.4',
'[2001:4860:4860::8888]',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053',
]);
```
An error will be thrown if an invalid address is provided.
The `dns.setServers()` method must not be called while a DNS query is in
progress.
The [setServers](././node__dns.d.ts/~/setServers) method affects only [resolve](././node__dns.d.ts/~/resolve), `dns.resolve*()` and [reverse](././node__dns.d.ts/~/reverse) (and specifically _not_ [lookup](././node__dns.d.ts/~/lookup)).
This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.
v
TIMEOUT
No documentation available
v
V4MAPPED
If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported
on some operating systems (e.g. FreeBSD 10.1).
T
AnyRecordWithTtl
No documentation available
node__domain.d.ts
> [!WARNING] Deno compatibility > All exports are non-functional stubs. > This is a deprecated Node module. > **This module is pending deprecation.** Once a replacement API has been finalized, this module will be fully deprecated. Most developers should **not** have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future. Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an `'error'` event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to exit immediately with an error code.f
create
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
c
Domain
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
The `Domain` class encapsulates the functionality of routing errors and
uncaught exceptions to the active `Domain` object.
To handle the errors that it catches, listen to its `'error'` event.
node__events.d.ts
Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause `Function` objects ("listeners") to be called. For instance: a `net.Server` object emits an event each time a peer connects to it; a `fs.ReadStream` emits an event when the file is opened; a `stream` emits an event whenever data is available to be read. All objects that emit events are instances of the `EventEmitter` class. These objects expose an `eventEmitter.on()` function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used. When the `EventEmitter` object emits an event, all of the functions attached to that specific event are called _synchronously_. Any values returned by the called listeners are _ignored_ and discarded. The following example shows a simple `EventEmitter` instance with a single listener. The `eventEmitter.on()` method is used to register listeners, while the `eventEmitter.emit()` method is used to trigger the event. ```js import { EventEmitter } from 'node:events'; class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event'); ```T
AnyRest
No documentation available
T
Args
No documentation available
T
DefaultEventMap
No documentation available
c
I
N
EventEmitter
The `EventEmitter` class is defined and exposed by the `node:events` module:
```js
import { EventEmitter } from 'node:events';
```
All `EventEmitter`s emit the event `'newListener'` when new listeners are
added and `'removeListener'` when existing listeners are removed.
It supports the following option:
I
c
EventEmitter.EventEmitterAsyncResource
Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
require manual async tracking. Specifically, all events emitted by instances
of `events.EventEmitterAsyncResource` will run within its `async context`.
```js
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
import { notStrictEqual, strictEqual } from 'node:assert';
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
// Async tracking tooling will identify this as 'Q'.
const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
// 'foo' listeners will run in the EventEmitters async context.
ee1.on('foo', () => {
strictEqual(executionAsyncId(), ee1.asyncId);
strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
});
const ee2 = new EventEmitter();
// 'foo' listeners on ordinary EventEmitters that do not track async
// context, however, run in the same async context as the emit().
ee2.on('foo', () => {
notStrictEqual(executionAsyncId(), ee2.asyncId);
notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
});
Promise.resolve().then(() => {
ee1.emit('foo');
ee2.emit('foo');
});
```
The `EventEmitterAsyncResource` class has the same methods and takes the
same options as `EventEmitter` and `AsyncResource` themselves.
I
I
I
T
EventMap
No documentation available
T
Key
No documentation available
T
Key2
No documentation available
T
Listener
No documentation available
T
Listener1
No documentation available
T
Listener2
No documentation available
I
I
node__fs--promises.d.ts
The `fs/promises` API provides asynchronous file system methods that return promises. The promise APIs use the underlying Node.js threadpool to perform file system operations off the event loop thread. These operations are not synchronized or threadsafe. Care must be taken when performing multiple concurrent modifications on the same file or data corruption may occur.f
access
Tests a user's permissions for the file or directory specified by `path`.
The `mode` argument is an optional integer that specifies the accessibility
checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK`
(e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
possible values of `mode`.
If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and
written by the current process.
```js
import { access, constants } from 'node:fs/promises';
try {
await access('/etc/passwd', constants.R_OK | constants.W_OK);
console.log('can access');
} catch {
console.error('cannot access');
}
```
Using `fsPromises.access()` to check for the accessibility of a file before
calling `fsPromises.open()` is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.
f
appendFile
Asynchronously append data to a file, creating the file if it does not yet
exist. `data` can be a string or a `Buffer`.
If `options` is a string, then it specifies the `encoding`.
The `mode` option only affects the newly created file. See `fs.open()` for more details.
The `path` may be specified as a `FileHandle` that has been opened
for appending (using `fsPromises.open()`).
f
chmod
Changes the permissions of a file.
f
chown
Changes the ownership of a file.
v
constants
No documentation available
f
copyFile
Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
already exists.
No guarantees are made about the atomicity of the copy operation. If an
error occurs after the destination file has been opened for writing, an attempt
will be made to remove the destination.
```js
import { copyFile, constants } from 'node:fs/promises';
try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
```
f
cp
Asynchronously copies the entire directory structure from `src` to `dest`,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to `cp dir1/ dir2/`.
I
I
CreateWriteStreamOptions
No documentation available
I
I
I
I
I
f
glob
Retrieves the files matching the specified pattern.
f
lchown
Changes the ownership on a symbolic link.
f
link
Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail.
f
lstat
Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail.
f
lutimes
Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.
f
mkdir
Asynchronously creates a directory.
The optional `options` argument can be an integer specifying `mode` (permission
and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory
that exists results in a
rejection only when `recursive` is false.
```js
import { mkdir } from 'node:fs/promises';
try {
const projectFolder = new URL('./test/project/', import.meta.url);
const createDir = await mkdir(projectFolder, { recursive: true });
console.log(`created ${createDir}`);
} catch (err) {
console.error(err.message);
}
```
f
mkdtemp
Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided `prefix`. Due to
platform inconsistencies, avoid trailing `X` characters in `prefix`. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing `X` characters in `prefix` with random characters.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use.
```js
import { mkdtemp } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
try {
await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
```
The `fsPromises.mkdtemp()` method will append the six randomly selected
characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing
platform-specific path separator
(`import { sep } from 'node:path'`).
f
open
Opens a `FileHandle`.
Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail.
Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
f
opendir
Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail.
Creates an `fs.Dir`, which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
directory and subsequent read operations.
Example using async iteration:
```js
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
```
When using the async iterator, the `fs.Dir` object will be automatically
closed after the iterator exits.
I
f
readdir
Reads the contents of a directory.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
will be passed as `Buffer` objects.
If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects.
```js
import { readdir } from 'node:fs/promises';
try {
const files = await readdir(path);
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
```
f
readFile
Asynchronously reads the entire contents of a file.
If no encoding is specified (using `options.encoding`), the data is returned
as a `Buffer` object. Otherwise, the data will be a string.
If `options` is a string, then it specifies the encoding.
When the `path` is a directory, the behavior of `fsPromises.readFile()` is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.
An example of reading a `package.json` file located in the same directory of the
running code:
```js
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
```
It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a
request is aborted the promise returned is rejected with an `AbortError`:
```js
import { readFile } from 'node:fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
```
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.readFile` performs.
Any specified `FileHandle` has to support reading.
f
readlink
Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is
fulfilled with the`linkString` upon success.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`, the link path
returned will be passed as a `Buffer` object.
f
realpath
Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function.
Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path. If the `encoding` is set to `'buffer'`, the path returned will be
passed as a `Buffer` object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
this restriction.
f
rename
Renames `oldPath` to `newPath`.
f
rm
Removes files and directories (modeled on the standard POSIX `rm` utility).
f
rmdir
Removes the directory identified by `path`.
Using `fsPromises.rmdir()` on a file (not a directory) results in the
promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX.
To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.
f
stat
No documentation available
f
statfs
No documentation available
f
symlink
Creates a symbolic link.
The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will
autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not
exist, `'file'` will be used. Windows junction points require the destination
path to be absolute. When using `'junction'`, the `target` argument will
automatically be normalized to absolute path. Junction points on NTFS volumes
can only point to directories.
f
truncate
Truncates (shortens or extends the length) of the content at `path` to `len` bytes.
f
unlink
If `path` refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the `path` refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail.
f
utimes
Change the file system timestamps of the object referenced by `path`.
The `atime` and `mtime` arguments follow these rules:
* Values can be either numbers representing Unix epoch time, `Date`s, or a
numeric string like `'123456789.0'`.
* If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
f
watch
Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.
```js
import { watch } from 'node:fs/promises';
const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);
(async () => {
try {
const watcher = watch(__filename, { signal });
for await (const event of watcher)
console.log(event);
} catch (err) {
if (err.name === 'AbortError')
return;
throw err;
}
})();
```
On most platforms, `'rename'` is emitted whenever a filename appears or
disappears in the directory.
All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`.
f
writeFile
Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an
[AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an
[Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object.
The `encoding` option is ignored if `data` is a buffer.
If `options` is a string, then it specifies the encoding.
The `mode` option only affects the newly created file. See `fs.open()` for more details.
Any specified `FileHandle` has to support writing.
It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
without waiting for the promise to be settled.
Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience
method that performs multiple `write` calls internally to write the buffer
passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`.
It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
```js
import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
try {
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
const promise = writeFile('message.txt', data, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
```
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.writeFile` performs.
f
lchmod
> [!WARNING] Deno compatibility
> The lchmod implementation is a not implemented.
Changes the permissions on a symbolic link.
This method is only implemented on macOS.
node__fs.d.ts
The `node:fs` module enables interacting with the file system in a way modeled on standard POSIX functions. To use the promise-based APIs: ```js import * as fs from 'node:fs/promises'; ``` To use the callback and sync APIs: ```js import * as fs from 'node:fs'; ``` All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).f
access
Tests a user's permissions for the file or directory specified by `path`.
The `mode` argument is an optional integer that specifies the accessibility
checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK`
(e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
possible values of `mode`.
The final argument, `callback`, is a callback function that is invoked with
a possible error argument. If any of the accessibility checks fail, the error
argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable.
```js
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
```
Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file is not accessible.
**write (NOT RECOMMENDED)**
```js
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
```
**write (RECOMMENDED)**
```js
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
```
**read (NOT RECOMMENDED)**
```js
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
```
**read (RECOMMENDED)**
```js
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
```
The "not recommended" examples above check for accessibility and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be
used directly, for example when its accessibility is a signal from another
process.
On Windows, access-control policies (ACLs) on a directory may limit access to
a file or directory. The `fs.access()` function, however, does not check the
ACL and therefore may report that a path is accessible even if the ACL restricts
the user from reading or writing to it.
f
accessSync
Synchronously tests a user's permissions for the file or directory specified
by `path`. The `mode` argument is an optional integer that specifies the
accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and
`fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
possible values of `mode`.
If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
the method will return `undefined`.
```js
import { accessSync, constants } from 'node:fs';
try {
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
```
f
appendFile
Asynchronously append data to a file, creating the file if it does not yet
exist. `data` can be a string or a `Buffer`.
The `mode` option only affects the newly created file. See [open](././node__fs.d.ts/~/open) for more details.
```js
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
```
If `options` is a string, then it specifies the encoding:
```js
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
```
The `path` may be specified as a numeric file descriptor that has been opened
for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
not be closed automatically.
```js
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
```
f
appendFileSync
Synchronously append data to a file, creating the file if it does not yet
exist. `data` can be a string or a `Buffer`.
The `mode` option only affects the newly created file. See [open](././node__fs.d.ts/~/open) for more details.
```js
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
// Handle the error
}
```
If `options` is a string, then it specifies the encoding:
```js
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8');
```
The `path` may be specified as a numeric file descriptor that has been opened
for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
not be closed automatically.
```js
import { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
// Handle the error
} finally {
if (fd !== undefined)
closeSync(fd);
}
```
I
I
I
BigIntStatsFs
No documentation available
T
BigIntStatsListener
No documentation available
T
BufferEncodingOption
No documentation available
f
chmod
Asynchronously changes the permissions of a file. No arguments other than a
possible exception are given to the completion callback.
See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
```js
import { chmod } from 'node:fs';
chmod('my_file.txt', 0o775, (err) => {
if (err) throw err;
console.log('The permissions for file "my_file.txt" have been changed!');
});
```
f
chmodSync
For detailed information, see the documentation of the asynchronous version of
this API: [chmod](././node__fs.d.ts/~/chmod).
See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
f
chown
Asynchronously changes owner and group of a file. No arguments other than a
possible exception are given to the completion callback.
See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
f
chownSync
Synchronously changes owner and group of a file. Returns `undefined`.
This is the synchronous version of [chown](././node__fs.d.ts/~/chown).
See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
f
close
Closes the file descriptor. No arguments other than a possible exception are
given to the completion callback.
Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
through any other `fs` operation may lead to undefined behavior.
See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
f
closeSync
Closes the file descriptor. Returns `undefined`.
Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use
through any other `fs` operation may lead to undefined behavior.
See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
N
constants
No documentation available
v
constants.COPYFILE_EXCL
Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists.
v
constants.COPYFILE_FICLONE
Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink.
If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
v
constants.COPYFILE_FICLONE_FORCE
Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink.
If the underlying platform does not support copy-on-write, then the operation will fail with an error.
v
constants.F_OK
Constant for fs.access(). File is visible to the calling process.
v
constants.O_APPEND
Constant for fs.open(). Flag indicating that data will be appended to the end of the file.
v
constants.O_CREAT
Constant for fs.open(). Flag indicating to create the file if it does not already exist.
v
constants.O_DIRECT
Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O.
v
constants.O_DIRECTORY
Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory.
v
constants.O_DSYNC
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity.
v
constants.O_EXCL
Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists.
v
constants.O_NOATIME
constant for fs.open().
Flag indicating reading accesses to the file system will no longer result in
an update to the atime information associated with the file.
This flag is available on Linux operating systems only.
v
constants.O_NOCTTY
Constant for fs.open(). Flag indicating that if path identifies a terminal device,
opening the path shall not cause that terminal to become the controlling terminal for the process
(if the process does not already have one).
v
constants.O_NOFOLLOW
Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link.
v
constants.O_NONBLOCK
Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible.
v
constants.O_RDONLY
Constant for fs.open(). Flag indicating to open a file for read-only access.
v
constants.O_RDWR
Constant for fs.open(). Flag indicating to open a file for read-write access.
v
constants.O_SYMLINK
Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to.
v
constants.O_SYNC
Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O.
v
constants.O_TRUNC
Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
v
constants.O_WRONLY
Constant for fs.open(). Flag indicating to open a file for write-only access.
v
constants.R_OK
Constant for fs.access(). File can be read by the calling process.
v
constants.S_IFBLK
Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file.
v
constants.S_IFCHR
Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file.
v
constants.S_IFDIR
Constant for fs.Stats mode property for determining a file's type. File type constant for a directory.
v
constants.S_IFIFO
Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe.
v
constants.S_IFLNK
Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link.
v
constants.S_IFMT
Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code.
v
constants.S_IFREG
Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file.
v
constants.S_IFSOCK
Constant for fs.Stats mode property for determining a file's type. File type constant for a socket.
v
constants.S_IRGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group.
v
constants.S_IROTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others.
v
constants.S_IRUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner.
v
constants.S_IRWXG
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group.
v
constants.S_IRWXO
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others.
v
constants.S_IRWXU
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner.
v
constants.S_IWGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group.
v
constants.S_IWOTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others.
v
constants.S_IWUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner.
v
constants.S_IXGRP
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group.
v
constants.S_IXOTH
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others.
v
constants.S_IXUSR
Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner.
v
constants.UV_FS_O_FILEMAP
When set, a memory file mapping is used to access the file. This flag
is available on Windows operating systems only. On other operating systems,
this flag is ignored.
v
constants.W_OK
Constant for fs.access(). File can be written by the calling process.
v
constants.X_OK
Constant for fs.access(). File can be executed by the calling process.
f
copyFile
Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.
`mode` is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
exists.
* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.
* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support
copy-on-write, then the operation will fail.
```js
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
```
f
copyFileSync
Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
already exists. Returns `undefined`. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.
`mode` is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
* `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
exists.
* `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.
* `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support
copy-on-write, then the operation will fail.
```js
import { copyFileSync, constants } from 'node:fs';
// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
```
I
I
CopyOptionsBase
No documentation available
I
f
cp
Asynchronously copies the entire directory structure from `src` to `dest`,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to `cp dir1/ dir2/`.
f
cpSync
Synchronously copies the entire directory structure from `src` to `dest`,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to `cp dir1/ dir2/`.
f
createReadStream
Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream
returned by this method has a default `highWaterMark` of 64 KiB.
`options` can include `start` and `end` values to read a range of bytes from
the file instead of the entire file. Both `start` and `end` are inclusive and
start counting at 0, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is
omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
current file position. The `encoding` can be any one of those accepted by `Buffer`.
If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
the specified file descriptor. This means that no `'open'` event will be
emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`.
If `fd` points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
available. This can prevent the process from exiting and the stream from
closing naturally.
By default, the stream will emit a `'close'` event after it has been
destroyed. Set the `emitClose` option to `false` to change this behavior.
By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option,
an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is
also required.
```js
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
```
If `autoClose` is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If `autoClose` is set to true (default
behavior), on `'error'` or `'end'` the file descriptor will be closed
automatically.
`mode` sets the file mode (permission and sticky bits), but only if the
file was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
```js
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
```
If `options` is a string, then it specifies the encoding.
I
f
createWriteStream
`options` may also include a `start` option to allow writing data at some
position past the beginning of the file, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than
replacing it may require the `flags` option to be set to `r+` rather than the
default `w`. The `encoding` can be any one of those accepted by `Buffer`.
If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.
By default, the stream will emit a `'close'` event after it has been
destroyed. Set the `emitClose` option to `false` to change this behavior.
By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce
performance as some optimizations (`_writev()`)
will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override
for `open` is also required. If `autoClose` is `true`, an override for `close` is also required.
Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be
emitted. `fd` should be blocking; non-blocking `fd`s
should be passed to `net.Socket`.
If `options` is a string, then it specifies the encoding.
I
c
Dir
A class representing a directory stream.
Created by [opendir](././node__fs.d.ts/~/opendir), [opendirSync](././node__fs.d.ts/~/opendirSync), or `fsPromises.opendir()`.
```js
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
```
When using the async iterator, the `fs.Dir` object will be automatically
closed after the iterator exits.
c
Dirent
A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an `fs.Dir`. The
directory entry is a combination of the file name and file type pairs.
Additionally, when [readdir](././node__fs.d.ts/~/readdir) or [readdirSync](././node__fs.d.ts/~/readdirSync) is called with
the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s.
T
EncodingOption
No documentation available
f
existsSync
Returns `true` if the path exists, `false` otherwise.
For detailed information, see the documentation of the asynchronous version of
this API: [exists](././node__fs.d.ts/~/exists).
`fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other
Node.js callbacks. `fs.existsSync()` does not use a callback.
```js
import { existsSync } from 'node:fs';
if (existsSync('/etc/passwd'))
console.log('The path exists.');
```
f
fchmod
Sets the permissions on the file. No arguments other than a possible exception
are given to the completion callback.
See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
f
fchmodSync
Sets the permissions on the file. Returns `undefined`.
See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
f
fchown
Sets the owner of the file. No arguments other than a possible exception are
given to the completion callback.
See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
f
fchownSync
Sets the owner of the file. Returns `undefined`.
See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
f
fdatasync
Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other
than a possible
exception are given to the completion callback.
f
fdatasyncSync
Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`.
I
f
fstat
Invokes the callback with the `fs.Stats` for the file descriptor.
See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
f
fstatSync
Retrieves the `fs.Stats` for the file descriptor.
See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
I
FSWatcher
No documentation available
f
fsync
Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other
than a possible exception are given to the completion callback.
f
fsyncSync
Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`.
f
ftruncate
Truncates the file descriptor. No arguments other than a possible exception are
given to the completion callback.
See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail.
If the file referred to by the file descriptor was larger than `len` bytes, only
the first `len` bytes will be retained in the file.
For example, the following program retains only the first four bytes of the
file:
```js
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
```
If the file previously was shorter than `len` bytes, it is extended, and the
extended part is filled with null bytes (`'\0'`):
If `len` is negative then `0` will be used.
f
ftruncateSync
Truncates the file descriptor. Returns `undefined`.
For detailed information, see the documentation of the asynchronous version of
this API: [ftruncate](././node__fs.d.ts/~/ftruncate).
f
futimes
Change the file system timestamps of the object referenced by the supplied file
descriptor. See [utimes](././node__fs.d.ts/~/utimes).
f
futimesSync
Synchronous version of [futimes](././node__fs.d.ts/~/futimes). Returns `undefined`.
f
glob
Retrieves the files matching the specified pattern.
I
I
I
f
globSync
Retrieves the files matching the specified pattern.
f
lchown
Set the owner of the symbolic link. No arguments other than a possible
exception are given to the completion callback.
See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail.
f
lchownSync
Set the owner for the path. Returns `undefined`.
See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details.
f
link
Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than
a possible
exception are given to the completion callback.
f
linkSync
Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`.
f
lstat
Retrieves the `fs.Stats` for the symbolic link referred to by the path.
The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details.
v
lstatSync
Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
f
lutimes
Changes the access and modification times of a file in the same way as [utimes](././node__fs.d.ts/~/utimes), with the difference that if the path refers to a symbolic
link, then the link is not dereferenced: instead, the timestamps of the
symbolic link itself are changed.
No arguments other than a possible exception are given to the completion
callback.
f
lutimesSync
Change the file system timestamps of the symbolic link referenced by `path`.
Returns `undefined`, or throws an exception when parameters are incorrect or
the operation fails. This is the synchronous version of [lutimes](././node__fs.d.ts/~/lutimes).
I
f
mkdir
Asynchronously creates a directory.
The callback is given a possible exception and, if `recursive` is `true`, the
first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was
created (for instance, if it was previously created).
The optional `options` argument can be an integer specifying `mode` (permission
and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that
exists results in an error only
when `recursive` is false. If `recursive` is false and the directory exists,
an `EEXIST` error occurs.
```js
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
```
On Windows, using `fs.mkdir()` on the root directory even with recursion will
result in an error:
```js
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
```
See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
f
mkdirSync
Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created.
This is the synchronous version of [mkdir](././node__fs.d.ts/~/mkdir).
See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
f
mkdtemp
Creates a unique temporary directory.
Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform
inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
notably the BSDs, can return more than six random characters, and replace
trailing `X` characters in `prefix` with random characters.
The created directory path is passed as a string to the callback's second
parameter.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use.
```js
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
```
The `fs.mkdtemp()` method will append the six randomly selected characters
directly to the `prefix` string. For instance, given a directory `/tmp`, if the
intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator
(`import { sep } from 'node:path'`).
```js
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
```
f
mkdtempSync
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of
this API: [mkdtemp](././node__fs.d.ts/~/mkdtemp).
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use.
T
Mode
No documentation available
T
NoParamCallback
No documentation available
I
f
open
Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details.
`mode` sets the file mode (permission and sticky bits), but only if the file was
created. On Windows, only the write permission can be manipulated; see [chmod](././node__fs.d.ts/~/chmod).
The callback gets two arguments `(err, fd)`.
Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc.
f
openAsBlob
Returns a `Blob` whose data is backed by the given file.
The file must not be modified after the `Blob` is created. Any modifications
will cause reading the `Blob` data to fail with a `DOMException` error.
Synchronous stat operations on the file when the `Blob` is created, and before
each read in order to detect whether the file data has been modified on disk.
```js
import { openAsBlob } from 'node:fs';
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
```
I
f
opendir
Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for
more details.
Creates an `fs.Dir`, which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
directory and subsequent read operations.
I
f
opendirSync
Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html).
Creates an `fs.Dir`, which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
directory and subsequent read operations.
T
OpenMode
No documentation available
f
openSync
Returns an integer representing the file descriptor.
For detailed information, see the documentation of the asynchronous version of
this API: [open](././node__fs.d.ts/~/open).
T
PathLike
Valid types for path values in "fs".
T
PathOrFileDescriptor
No documentation available
N
promises
The `fs/promises` API provides asynchronous file system methods that return
promises.
The promise APIs use the underlying Node.js threadpool to perform file
system operations off the event loop thread. These operations are not
synchronized or threadsafe. Care must be taken when performing multiple
concurrent modifications on the same file or data corruption may occur.
f
promises.access
Tests a user's permissions for the file or directory specified by `path`.
The `mode` argument is an optional integer that specifies the accessibility
checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK`
(e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
possible values of `mode`.
If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and
written by the current process.
```js
import { access, constants } from 'node:fs/promises';
try {
await access('/etc/passwd', constants.R_OK | constants.W_OK);
console.log('can access');
} catch {
console.error('cannot access');
}
```
Using `fsPromises.access()` to check for the accessibility of a file before
calling `fsPromises.open()` is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.
f
promises.appendFile
Asynchronously append data to a file, creating the file if it does not yet
exist. `data` can be a string or a `Buffer`.
If `options` is a string, then it specifies the `encoding`.
The `mode` option only affects the newly created file. See `fs.open()` for more details.
The `path` may be specified as a `FileHandle` that has been opened
for appending (using `fsPromises.open()`).
f
promises.chmod
Changes the permissions of a file.
f
promises.chown
Changes the ownership of a file.
v
promises.constants
No documentation available
f
promises.copyFile
Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
already exists.
No guarantees are made about the atomicity of the copy operation. If an
error occurs after the destination file has been opened for writing, an attempt
will be made to remove the destination.
```js
import { copyFile, constants } from 'node:fs/promises';
try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
console.error('The file could not be copied');
}
```
f
promises.cp
Asynchronously copies the entire directory structure from `src` to `dest`,
including subdirectories and files.
When copying a directory to another directory, globs are not supported and
behavior is similar to `cp dir1/ dir2/`.
I
promises.CreateReadStreamOptions
No documentation available
I
promises.CreateWriteStreamOptions
No documentation available
I
I
I
I
I
f
promises.glob
Retrieves the files matching the specified pattern.
f
promises.lchown
Changes the ownership on a symbolic link.
f
promises.link
Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail.
f
promises.lstat
Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail.
f
promises.lutimes
Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.
f
promises.mkdir
Asynchronously creates a directory.
The optional `options` argument can be an integer specifying `mode` (permission
and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory
that exists results in a
rejection only when `recursive` is false.
```js
import { mkdir } from 'node:fs/promises';
try {
const projectFolder = new URL('./test/project/', import.meta.url);
const createDir = await mkdir(projectFolder, { recursive: true });
console.log(`created ${createDir}`);
} catch (err) {
console.error(err.message);
}
```
f
promises.mkdtemp
Creates a unique temporary directory. A unique directory name is generated by
appending six random characters to the end of the provided `prefix`. Due to
platform inconsistencies, avoid trailing `X` characters in `prefix`. Some
platforms, notably the BSDs, can return more than six random characters, and
replace trailing `X` characters in `prefix` with random characters.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use.
```js
import { mkdtemp } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
try {
await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
```
The `fsPromises.mkdtemp()` method will append the six randomly selected
characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing
platform-specific path separator
(`import { sep } from 'node:path'`).
f
promises.open
Opens a `FileHandle`.
Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail.
Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
f
promises.opendir
Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail.
Creates an `fs.Dir`, which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
directory and subsequent read operations.
Example using async iteration:
```js
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
```
When using the async iterator, the `fs.Dir` object will be automatically
closed after the iterator exits.
I
f
promises.readdir
Reads the contents of a directory.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
will be passed as `Buffer` objects.
If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects.
```js
import { readdir } from 'node:fs/promises';
try {
const files = await readdir(path);
for (const file of files)
console.log(file);
} catch (err) {
console.error(err);
}
```
f
promises.readFile
Asynchronously reads the entire contents of a file.
If no encoding is specified (using `options.encoding`), the data is returned
as a `Buffer` object. Otherwise, the data will be a string.
If `options` is a string, then it specifies the encoding.
When the `path` is a directory, the behavior of `fsPromises.readFile()` is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.
An example of reading a `package.json` file located in the same directory of the
running code:
```js
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
```
It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a
request is aborted the promise returned is rejected with an `AbortError`:
```js
import { readFile } from 'node:fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
```
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.readFile` performs.
Any specified `FileHandle` has to support reading.
f
promises.readlink
Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is
fulfilled with the`linkString` upon success.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`, the link path
returned will be passed as a `Buffer` object.
f
promises.realpath
Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function.
Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path. If the `encoding` is set to `'buffer'`, the path returned will be
passed as a `Buffer` object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
this restriction.
f
promises.rename
Renames `oldPath` to `newPath`.
f
promises.rm
Removes files and directories (modeled on the standard POSIX `rm` utility).
f
promises.rmdir
Removes the directory identified by `path`.
Using `fsPromises.rmdir()` on a file (not a directory) results in the
promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX.
To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`.
f
promises.stat
No documentation available
f
promises.statfs
No documentation available
f
promises.symlink
Creates a symbolic link.
The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will
autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not
exist, `'file'` will be used. Windows junction points require the destination
path to be absolute. When using `'junction'`, the `target` argument will
automatically be normalized to absolute path. Junction points on NTFS volumes
can only point to directories.
f
promises.truncate
Truncates (shortens or extends the length) of the content at `path` to `len` bytes.
f
promises.unlink
If `path` refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the `path` refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail.
f
promises.utimes
Change the file system timestamps of the object referenced by `path`.
The `atime` and `mtime` arguments follow these rules:
* Values can be either numbers representing Unix epoch time, `Date`s, or a
numeric string like `'123456789.0'`.
* If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
f
promises.watch
Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.
```js
import { watch } from 'node:fs/promises';
const ac = new AbortController();
const { signal } = ac;
setTimeout(() => ac.abort(), 10000);
(async () => {
try {
const watcher = watch(__filename, { signal });
for await (const event of watcher)
console.log(event);
} catch (err) {
if (err.name === 'AbortError')
return;
throw err;
}
})();
```
On most platforms, `'rename'` is emitted whenever a filename appears or
disappears in the directory.
All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`.
f
promises.writeFile
Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an
[AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an
[Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object.
The `encoding` option is ignored if `data` is a buffer.
If `options` is a string, then it specifies the encoding.
The `mode` option only affects the newly created file. See `fs.open()` for more details.
Any specified `FileHandle` has to support writing.
It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
without waiting for the promise to be settled.
Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience
method that performs multiple `write` calls internally to write the buffer
passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`.
It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
```js
import { writeFile } from 'node:fs/promises';
import { Buffer } from 'node:buffer';
try {
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
const promise = writeFile('message.txt', data, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
```
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.writeFile` performs.
f
read
Read data from the file specified by `fd`.
The callback is given the three arguments, `(err, bytesRead, buffer)`.
If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.
If this method is invoked as its `util.promisify()` ed version, it returns
a promise for an `Object` with `bytesRead` and `buffer` properties.
I
f
readdir
Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`.
See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
the filenames returned will be passed as `Buffer` objects.
If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects.
f
readdirSync
Reads the contents of the directory.
See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames returned. If the `encoding` is set to `'buffer'`,
the filenames returned will be passed as `Buffer` objects.
If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects.
f
readFile
Asynchronously reads the entire contents of a file.
```js
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
```
The callback is passed two arguments `(err, data)`, where `data` is the
contents of the file.
If no encoding is specified, then the raw buffer is returned.
If `options` is a string, then it specifies the encoding:
```js
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
```
When the path is a directory, the behavior of `fs.readFile()` and [readFileSync](././node__fs.d.ts/~/readFileSync) is platform-specific. On macOS, Linux, and Windows, an
error will be returned. On FreeBSD, a representation of the directory's contents
will be returned.
```js
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read ]
});
// FreeBSD
readFile('', (err, data) => {
// => null,
});
```
It is possible to abort an ongoing request using an `AbortSignal`. If a
request is aborted the callback is called with an `AbortError`:
```js
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
```
The `fs.readFile()` function buffers the entire file. To minimize memory costs,
when possible prefer streaming via `fs.createReadStream()`.
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.readFile` performs.
f
readFileSync
Returns the contents of the `path`.
For detailed information, see the documentation of the asynchronous version of
this API: [readFile](././node__fs.d.ts/~/readFile).
If the `encoding` option is specified then this function returns a
string. Otherwise it returns a buffer.
Similar to [readFile](././node__fs.d.ts/~/readFile), when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific.
```js
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('');
// => [Error: EISDIR: illegal operation on a directory, read ]
// FreeBSD
readFileSync(''); // =>
```
f
readlink
Reads the contents of the symbolic link referred to by `path`. The callback gets
two arguments `(err, linkString)`.
See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path passed to the callback. If the `encoding` is set to `'buffer'`,
the link path returned will be passed as a `Buffer` object.
f
readlinkSync
Returns the symbolic link's string value.
See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`,
the link path returned will be passed as a `Buffer` object.
T
ReadPosition
No documentation available
c
ReadStream
Instances of `fs.ReadStream` are created and returned using the [createReadStream](././node__fs.d.ts/~/createReadStream) function.
I
f
readSync
Returns the number of `bytesRead`.
For detailed information, see the documentation of the asynchronous version of
this API: [read](././node__fs.d.ts/~/read).
I
f
readv
Read from a file specified by `fd` and write to an array of `ArrayBufferView`s
using `readv()`.
`position` is the offset from the beginning of the file from where data
should be read. If `typeof position !== 'number'`, the data will be read
from the current position.
The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file.
If this method is invoked as its `util.promisify()` ed version, it returns
a promise for an `Object` with `bytesRead` and `buffers` properties.
I
f
readvSync
For detailed information, see the documentation of the asynchronous version of
this API: [readv](././node__fs.d.ts/~/readv).
f
N
realpath
Asynchronously computes the canonical pathname by resolving `.`, `..`, and
symbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can
expose a file system entity through many pathnames.
This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions:
1. No case conversion is performed on case-insensitive file systems.
2. The maximum number of symbolic links is platform-independent and generally
(much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports.
The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
the path returned will be passed as a `Buffer` object.
If `path` resolves to a socket or a pipe, the function will return a system
dependent name for that object.
f
realpath.native
Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html).
The `callback` gets two arguments `(err, resolvedPath)`.
Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
the path returned will be passed as a `Buffer` object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
this restriction.
f
N
realpathSync
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of
this API: [realpath](././node__fs.d.ts/~/realpath).
f
realpathSync.native
No documentation available
f
rename
Asynchronously rename file at `oldPath` to the pathname provided
as `newPath`. In the case that `newPath` already exists, it will
be overwritten. If there is a directory at `newPath`, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.
See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html).
```js
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
```
f
renameSync
Renames the file from `oldPath` to `newPath`. Returns `undefined`.
See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details.
f
rm
Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the
completion callback.
f
rmdir
Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given
to the completion callback.
Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on
Windows and an `ENOTDIR` error on POSIX.
To get a behavior similar to the `rm -rf` Unix command, use [rm](././node__fs.d.ts/~/rm) with options `{ recursive: true, force: true }`.
I
f
rmdirSync
Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`.
Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
on Windows and an `ENOTDIR` error on POSIX.
To get a behavior similar to the `rm -rf` Unix command, use [rmSync](././node__fs.d.ts/~/rmSync) with options `{ recursive: true, force: true }`.
I
f
rmSync
Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`.
f
stat
Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object.
In case of an error, the `err.code` will be one of `Common System Errors`.
[stat](././node__fs.d.ts/~/stat) follows symbolic links. Use [lstat](././node__fs.d.ts/~/lstat) to look at the
links themselves.
Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended.
Instead, user code should open/read/write the file directly and handle the
error raised if the file is not available.
To check if a file exists without manipulating it afterwards, [access](././node__fs.d.ts/~/access) is recommended.
For example, given the following directory structure:
```text
- txtDir
-- file.txt
- app.js
```
The next program will check for the stats of the given paths:
```js
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i < pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
```
The resulting output will resemble:
```console
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
```
f
statfs
Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which
contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object.
In case of an error, the `err.code` will be one of `Common System Errors`.
I
f
statfsSync
Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which
contains `path`.
In case of an error, the `err.code` will be one of `Common System Errors`.
I
c
I
Stats
A `fs.Stats` object provides information about a file.
Objects returned from [stat](././node__fs.d.ts/~/stat), [lstat](././node__fs.d.ts/~/lstat), [fstat](././node__fs.d.ts/~/fstat), and
their synchronous counterparts are of this type.
If `bigint` in the `options` passed to those methods is true, the numeric values
will be `bigint` instead of `number`, and the object will contain additional
nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword.
```console
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
```
`bigint` version:
```console
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
```
I
c
I
StatsFs
Provides information about a mounted file system.
Objects returned from [statfs](././node__fs.d.ts/~/statfs) and its synchronous counterpart are of
this type. If `bigint` in the `options` passed to those methods is `true`, the
numeric values will be `bigint` instead of `number`.
```console
StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}
```
`bigint` version:
```console
StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}
```
T
StatsListener
No documentation available
v
statSync
Synchronous stat(2) - Get file status.
I
StatSyncFn
No documentation available
I
I
I
StreamOptions
No documentation available
f
N
symlink
Creates the link called `path` pointing to `target`. No arguments other than a
possible exception are given to the completion callback.
See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details.
The `type` argument is only available on Windows and ignored on other platforms.
It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is
not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`.
If the `target` does not exist, `'file'` will be used. Windows junction points
require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction
points on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
```js
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
```
The above example creates a symbolic link `mewtwo` which points to `mew` in the
same directory:
```bash
$ tree .
.
├── mew
└── mewtwo -> ./mew
```
T
symlink.Type
No documentation available
f
symlinkSync
Returns `undefined`.
For detailed information, see the documentation of the asynchronous version of
this API: [symlink](././node__fs.d.ts/~/symlink).
T
TimeLike
No documentation available
f
truncate
Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, `fs.ftruncate()` is called.
```js
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
```
Passing a file descriptor is deprecated and may result in an error being thrown
in the future.
See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details.
f
truncateSync
Truncates the file. Returns `undefined`. A file descriptor can also be
passed as the first argument. In this case, `fs.ftruncateSync()` is called.
Passing a file descriptor is deprecated and may result in an error being thrown
in the future.
f
unlink
Asynchronously removes a file or symbolic link. No arguments other than a
possible exception are given to the completion callback.
```js
import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was deleted');
});
```
`fs.unlink()` will not work on a directory, empty or otherwise. To remove a
directory, use [rmdir](././node__fs.d.ts/~/rmdir).
See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details.
f
unlinkSync
Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`.
f
unwatchFile
Stop watching for changes on `filename`. If `listener` is specified, only that
particular listener is removed. Otherwise, _all_ listeners are removed,
effectively stopping watching of `filename`.
Calling `fs.unwatchFile()` with a filename that is not being watched is a
no-op, not an error.
Using [watch](././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible.
f
utimes
Change the file system timestamps of the object referenced by `path`.
The `atime` and `mtime` arguments follow these rules:
* Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`.
* If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
f
utimesSync
Returns `undefined`.
For detailed information, see the documentation of the asynchronous version of
this API: [utimes](././node__fs.d.ts/~/utimes).
f
watch
Watch for changes on `filename`, where `filename` is either a file or a
directory.
The second argument is optional. If `options` is provided as a string, it
specifies the `encoding`. Otherwise `options` should be passed as an object.
The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file
which triggered the event.
On most platforms, `'rename'` is emitted whenever a filename appears or
disappears in the directory.
The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`.
If a `signal` is passed, aborting the corresponding AbortController will close
the returned `fs.FSWatcher`.
T
WatchEventType
No documentation available
f
watchFile
Watch for changes on `filename`. The callback `listener` will be called each
time the file is accessed.
The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates
whether the process should continue to run as long as files are being watched.
The `options` object may specify an `interval` property indicating how often the
target should be polled in milliseconds.
The `listener` gets two arguments the current stat object and the previous
stat object:
```js
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
```
These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
the numeric values in these objects are specified as `BigInt`s.
To be notified when the file was modified, not just accessed, it is necessary
to compare `curr.mtimeMs` and `prev.mtimeMs`.
When an `fs.watchFile` operation results in an `ENOENT` error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). If the file is created later on, the listener will be called
again, with the latest stat objects. This is a change in functionality since
v0.10.
Using [watch](././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible.
When a file being watched by `fs.watchFile()` disappears and reappears,
then the contents of `previous` in the second callback event (the file's
reappearance) will be the same as the contents of `previous` in the first
callback event (its disappearance).
This happens when:
* the file is deleted, followed by a restore
* the file is renamed and then renamed a second time back to its original name
I
WatchFileOptions
Watch for changes on `filename`. The callback `listener` will be called each
time the file is accessed.
The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates
whether the process should continue to run as long as files are being watched.
The `options` object may specify an `interval` property indicating how often the
target should be polled in milliseconds.
The `listener` gets two arguments the current stat object and the previous
stat object:
```js
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
```
These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
the numeric values in these objects are specified as `BigInt`s.
To be notified when the file was modified, not just accessed, it is necessary
to compare `curr.mtimeMs` and `prev.mtimeMs`.
When an `fs.watchFile` operation results in an `ENOENT` error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). If the file is created later on, the listener will be called
again, with the latest stat objects. This is a change in functionality since
v0.10.
Using [watch](././node__fs.d.ts/~/watch) is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible.
When a file being watched by `fs.watchFile()` disappears and reappears,
then the contents of `previous` in the second callback event (the file's
reappearance) will be the same as the contents of `previous` in the first
callback event (its disappearance).
This happens when:
* the file is deleted, followed by a restore
* the file is renamed and then renamed a second time back to its original name
T
WatchListener
No documentation available
I
f
write
Write `buffer` to the file specified by `fd`.
`offset` determines the part of the buffer to be written, and `length` is
an integer specifying the number of bytes to write.
`position` refers to the offset from the beginning of the file where this data
should be written. If `typeof position !== 'number'`, the data will be written
at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html).
The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`.
If this method is invoked as its `util.promisify()` ed version, it returns
a promise for an `Object` with `bytesWritten` and `buffer` properties.
It is unsafe to use `fs.write()` multiple times on the same file without waiting
for the callback. For this scenario, [createWriteStream](././node__fs.d.ts/~/createWriteStream) is
recommended.
On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.
f
writeFile
> [!WARNING] Deno compatibility
> Missing `utf16le`, `latin1` and `ucs2` encoding.
When `file` is a filename, asynchronously writes data to the file, replacing the
file if it already exists. `data` can be a string or a buffer.
When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using
a file descriptor.
The `encoding` option is ignored if `data` is a buffer.
The `mode` option only affects the newly created file. See [open](././node__fs.d.ts/~/open) for more details.
```js
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
```
If `options` is a string, then it specifies the encoding:
```js
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
```
It is unsafe to use `fs.writeFile()` multiple times on the same file without
waiting for the callback. For this scenario, [createWriteStream](././node__fs.d.ts/~/createWriteStream) is
recommended.
Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that
performs multiple `write` calls internally to write the buffer passed to it.
For performance sensitive code consider using [createWriteStream](././node__fs.d.ts/~/createWriteStream).
It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
```js
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
```
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.writeFile` performs.
T
WriteFileOptions
No documentation available
f
writeFileSync
> [!WARNING] Deno compatibility
> Missing `utf16le`, `latin1` and `ucs2` encoding.
Returns `undefined`.
The `mode` option only affects the newly created file. See [open](././node__fs.d.ts/~/open) for more details.
For detailed information, see the documentation of the asynchronous version of
this API: [writeFile](././node__fs.d.ts/~/writeFile).
c
WriteStream
* Extends `stream.Writable`
Instances of `fs.WriteStream` are created and returned using the [createWriteStream](././node__fs.d.ts/~/createWriteStream) function.
I
f
writeSync
For detailed information, see the documentation of the asynchronous version of
this API: [write](././node__fs.d.ts/~/write).
f
writev
Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`.
`position` is the offset from the beginning of the file where this data
should be written. If `typeof position !== 'number'`, the data will be written
at the current position.
The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`.
If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties.
It is unsafe to use `fs.writev()` multiple times on the same file without
waiting for the callback. For this scenario, use [createWriteStream](././node__fs.d.ts/~/createWriteStream).
On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.
I
f
writevSync
For detailed information, see the documentation of the asynchronous version of
this API: [writev](././node__fs.d.ts/~/writev).
f
exists
Test whether or not the given path exists by checking with the file system.
Then call the `callback` argument with either true or false:
```js
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
```
**The parameters for this callback are not consistent with other Node.js**
**callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback
has only one boolean parameter. This is one reason `fs.access()` is recommended
instead of `fs.exists()`.
Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file does not exist.
**write (NOT RECOMMENDED)**
```js
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
```
**write (RECOMMENDED)**
```js
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
```
**read (NOT RECOMMENDED)**
```js
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
```
**read (RECOMMENDED)**
```js
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
```
The "not recommended" examples above check for existence and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.
In general, check for the existence of a file only if the file won't be
used directly, for example when its existence is a signal from another
process.
f
lchmod
Changes the permissions on a symbolic link. No arguments other than a possible
exception are given to the completion callback.
This method is only implemented on macOS.
See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
f
lchmodSync
Changes the permissions on a symbolic link. Returns `undefined`.
This method is only implemented on macOS.
See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
f
promises.lchmod
> [!WARNING] Deno compatibility
> The lchmod implementation is a not implemented.
Changes the permissions on a symbolic link.
This method is only implemented on macOS.
node__http.d.ts
To use the HTTP server and client one must import the `node:http` module. The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data. HTTP message headers are represented by an object like this: ```json { "content-length": "123", "content-type": "text/plain", "connection": "keep-alive", "host": "example.com", "accept": "*" } ``` Keys are lowercased. Values are not modified. In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body. See `message.headers` for details on how duplicate headers are handled. The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For example, the previous message header object might have a `rawHeaders` list like the following: ```js [ 'ConTent-Length', '123456', 'content-LENGTH', '123', 'content-type', 'text/plain', 'CONNECTION', 'keep-alive', 'Host', 'example.com', 'accepT', '*' ] ```c
Agent
An `Agent` is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The `Agent` will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see `socket.unref()`).
It is good practice, to `destroy()` an `Agent` instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a `'close'` event or an `'agentRemove'` event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
```js
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
```
An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options
will be used
for the client connection.
`agent:false`:
```js
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
```
`options` in [`socket.connect()`](https://nodejs.org/docs/latest-v22.x/api/net.html#socketconnectoptions-connectlistener) are also supported.
To configure any of them, a custom [Agent](././node__http.d.ts/~/Agent) instance must be created.
```js
import http from 'node:http';
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback)
```
I
AgentOptions
No documentation available
c
ClientRequest
> [!WARNING] Deno compatibility
> Constructor option `createConnection` is not supported.
This object is created internally and returned from [request](././node__http.d.ts/~/request). It
represents an _in-progress_ request whose header has already been queued. The
header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will
be sent along with the first data chunk or when calling `request.end()`.
To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response
headers have been received. The `'response'` event is executed with one
argument which is an instance of [IncomingMessage](././node__http.d.ts/~/IncomingMessage).
During the `'response'` event, one can add listeners to the
response object; particularly to listen for the `'data'` event.
If no `'response'` handler is added, then the response will be
entirely discarded. However, if a `'response'` event handler is added,
then the data from the response object **must** be consumed, either by
calling `response.read()` whenever there is a `'readable'` event, or
by adding a `'data'` handler, or by calling the `.resume()` method.
Until the data is consumed, the `'end'` event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered.
Set `Content-Length` header to limit the response body size.
If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown,
identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`.
`Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes.
I
ClientRequestArgs
> [!WARNING] Deno compatibility
> Option `createConnection` is not supported.
v
CloseEvent
No documentation available
f
createServer
Returns a new instance of [Server](././node__http.d.ts/~/Server).
The `requestListener` is a function which is automatically
added to the `'request'` event.
```js
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
```
```js
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
```
f
get
> [!WARNING] Deno compatibility
> Constructor option `createConnection` is not supported.
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and [request](././node__http.d.ts/~/request) is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to
consume the response
data for reasons stated in [ClientRequest](././node__http.d.ts/~/ClientRequest) section.
The `callback` is invoked with a single argument that is an instance of [IncomingMessage](././node__http.d.ts/~/IncomingMessage).
JSON fetching example:
```js
http.get('http://localhost:8000/', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
```
v
globalAgent
Global instance of `Agent` which is used as the default for all HTTP client
requests. Diverges from a default `Agent` configuration by having `keepAlive`
enabled and a `timeout` of 5 seconds.
I
IncomingHttpHeaders
No documentation available
- accept
- accept-language
- accept-patch
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- alt-svc
- authorization
- cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-type
- cookie
- date
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-unmodified-since
- last-modified
- location
- origin
- pragma
- proxy-authenticate
- proxy-authorization
- public-key-pins
- range
- referer
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- set-cookie
- strict-transport-security
- tk
- trailer
- transfer-encoding
- upgrade
- user-agent
- vary
- via
- warning
- www-authenticate
c
IncomingMessage
An `IncomingMessage` object is created by [Server](././node__http.d.ts/~/Server) or [ClientRequest](././node__http.d.ts/~/ClientRequest) and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to
access response
status, headers, and data.
Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
I
InformationEvent
No documentation available
v
maxHeaderSize
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option.
v
MessageEvent
No documentation available
v
METHODS
No documentation available
T
OutgoingHttpHeader
No documentation available
I
OutgoingHttpHeaders
No documentation available
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- authorization
- cache-control
- cdn-cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-security-policy
- content-security-policy-report-only
- cookie
- date
- dav
- dnt
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-range
- if-unmodified-since
- last-modified
- link
- location
- max-forwards
- origin
- prgama
- proxy-authenticate
- proxy-authorization
- public-key-pins
- public-key-pins-report-only
- range
- referer
- referrer-policy
- refresh
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- server
- set-cookie
- strict-transport-security
- te
- trailer
- transfer-encoding
- upgrade
- upgrade-insecure-requests
- user-agent
- vary
- via
- warning
- www-authenticate
- x-content-type-options
- x-dns-prefetch-control
- x-frame-options
- x-xss-protection
c
OutgoingMessage
This class serves as the parent class of [ClientRequest](././node__http.d.ts/~/ClientRequest) and [ServerResponse](././node__http.d.ts/~/ServerResponse). It is an abstract outgoing message from
the perspective of the participants of an HTTP transaction.
f
request
> [!WARNING] Deno compatibility
> Constructor option `createConnection` is not supported.
`options` in `socket.connect()` are also supported.
Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.
`url` can be a string or a `URL` object. If `url` is a
string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence.
The optional `callback` parameter will be added as a one-time listener for
the `'response'` event.
`http.request()` returns an instance of the [ClientRequest](././node__http.d.ts/~/ClientRequest) class. The `ClientRequest` instance is a writable stream. If one needs to
upload a file with a POST request, then write to the `ClientRequest` object.
```js
import http from 'node:http';
import { Buffer } from 'node:buffer';
const postData = JSON.stringify({
'msg': 'Hello World!',
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
```
In the example `req.end()` was called. With `http.request()` one
must always call `req.end()` to signify the end of the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted
on the returned request object. As with all `'error'` events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
* Sending a 'Connection: keep-alive' will notify Node.js that the connection to
the server should be persisted until the next request.
* Sending a 'Content-Length' header will disable the default chunked encoding.
* Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', both a timeout and a listener
for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more
information.
* Sending an Authorization header will override using the `auth` option
to compute basic authentication.
Example using a `URL` as `options`:
```js
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
```
In a successful request, the following events will be emitted in the following
order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
(`'data'` will not be emitted at all if the response body is empty, for
instance, in most redirects)
* `'end'` on the `res` object
* `'close'`
In the case of a connection error, the following events will be emitted:
* `'socket'`
* `'error'`
* `'close'`
In the case of a premature connection close before the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`
* `'close'`
In the case of a premature connection close after the response is received,
the following events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (connection closed here)
* `'aborted'` on the `res` object
* `'close'`
* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`
* `'close'` on the `res` object
If `req.destroy()` is called before a socket is assigned, the following
events will be emitted in the following order:
* (`req.destroy()` called here)
* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called
* `'close'`
If `req.destroy()` is called before the connection succeeds, the following
events will be emitted in the following order:
* `'socket'`
* (`req.destroy()` called here)
* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called
* `'close'`
If `req.destroy()` is called after the response is received, the following
events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (`req.destroy()` called here)
* `'aborted'` on the `res` object
* `'close'`
* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called
* `'close'` on the `res` object
If `req.abort()` is called before a socket is assigned, the following
events will be emitted in the following order:
* (`req.abort()` called here)
* `'abort'`
* `'close'`
If `req.abort()` is called before the connection succeeds, the following
events will be emitted in the following order:
* `'socket'`
* (`req.abort()` called here)
* `'abort'`
* `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`
* `'close'`
If `req.abort()` is called after the response is received, the following
events will be emitted in the following order:
* `'socket'`
* `'response'`
* `'data'` any number of times, on the `res` object
* (`req.abort()` called here)
* `'abort'`
* `'aborted'` on the `res` object
* `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`.
* `'close'`
* `'close'` on the `res` object
Setting the `timeout` option or using the `setTimeout()` function will
not abort the request or do anything besides add a `'timeout'` event.
Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the
request. Specifically, the `'error'` event will be emitted with an error with
the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided.
T
RequestListener
No documentation available
I
RequestOptions
> [!WARNING] Deno compatibility
> Option `createConnection` is not supported.
c
I
c
ServerResponse
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the `'request'` event.
f
setMaxIdleHTTPParsers
Set the maximum number of idle HTTP parsers.
v
STATUS_CODES
No documentation available
f
validateHeaderName
Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called.
Passing illegal value as `name` will result in a `TypeError` being thrown,
identified by `code: 'ERR_INVALID_HTTP_TOKEN'`.
It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.
Example:
```js
import { validateHeaderName } from 'node:http';
try {
validateHeaderName('');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}
```
f
validateHeaderValue
Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called.
Passing illegal value as `value` will result in a `TypeError` being thrown.
* Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`.
* Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`.
It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.
Examples:
```js
import { validateHeaderValue } from 'node:http';
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}
```
v
WebSocket
A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket).
node__http2.d.ts
The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It can be accessed using: ```js import http2 from 'node:http2'; ```I
I
ClientHttp2Session
No documentation available
I
ClientHttp2Stream
> [!WARNING] Deno compatibility
> All methods are non-functional stubs.
I
I
ClientSessionRequestOptions
No documentation available
f
connect
Returns a `ClientHttp2Session` instance.
```js
import http2 from 'node:http2';
const client = http2.connect('https://localhost:1234');
// Use the client
client.close();
```
N
constants
No documentation available
v
constants.DEFAULT_SETTINGS_ENABLE_PUSH
No documentation available
v
constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE
No documentation available
v
constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE
No documentation available
v
constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE
No documentation available
v
constants.HTTP2_HEADER_ACCEPT
No documentation available
v
constants.HTTP2_HEADER_ACCEPT_CHARSET
No documentation available
v
constants.HTTP2_HEADER_ACCEPT_ENCODING
No documentation available
v
constants.HTTP2_HEADER_ACCEPT_LANGUAGE
No documentation available
v
constants.HTTP2_HEADER_ACCEPT_RANGES
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS
No documentation available
v
constants.HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD
No documentation available
v
constants.HTTP2_HEADER_AGE
No documentation available
v
constants.HTTP2_HEADER_ALLOW
No documentation available
v
constants.HTTP2_HEADER_CACHE_CONTROL
No documentation available
v
constants.HTTP2_HEADER_CONNECTION
No documentation available
v
constants.HTTP2_HEADER_CONTENT_DISPOSITION
No documentation available
v
constants.HTTP2_HEADER_CONTENT_ENCODING
No documentation available
v
constants.HTTP2_HEADER_CONTENT_LANGUAGE
No documentation available
v
constants.HTTP2_HEADER_CONTENT_LENGTH
No documentation available
v
constants.HTTP2_HEADER_CONTENT_LOCATION
No documentation available
v
constants.HTTP2_HEADER_CONTENT_MD5
No documentation available
v
constants.HTTP2_HEADER_CONTENT_RANGE
No documentation available
v
constants.HTTP2_HEADER_CONTENT_TYPE
No documentation available
v
constants.HTTP2_HEADER_DATE
No documentation available
v
constants.HTTP2_HEADER_ETAG
No documentation available
v
constants.HTTP2_HEADER_EXPECT
No documentation available
v
constants.HTTP2_HEADER_EXPIRES
No documentation available
v
constants.HTTP2_HEADER_FROM
No documentation available
v
constants.HTTP2_HEADER_HOST
No documentation available
v
constants.HTTP2_HEADER_HTTP2_SETTINGS
No documentation available
v
constants.HTTP2_HEADER_IF_MATCH
No documentation available
v
constants.HTTP2_HEADER_IF_MODIFIED_SINCE
No documentation available
v
constants.HTTP2_HEADER_IF_NONE_MATCH
No documentation available
v
constants.HTTP2_HEADER_IF_RANGE
No documentation available
v
constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE
No documentation available
v
constants.HTTP2_HEADER_KEEP_ALIVE
No documentation available
v
constants.HTTP2_HEADER_LAST_MODIFIED
No documentation available
v
constants.HTTP2_HEADER_LINK
No documentation available
v
constants.HTTP2_HEADER_LOCATION
No documentation available
v
constants.HTTP2_HEADER_MAX_FORWARDS
No documentation available
v
constants.HTTP2_HEADER_METHOD
No documentation available
v
constants.HTTP2_HEADER_PATH
No documentation available
v
constants.HTTP2_HEADER_PREFER
No documentation available
v
constants.HTTP2_HEADER_PROXY_AUTHENTICATE
No documentation available
v
constants.HTTP2_HEADER_PROXY_CONNECTION
No documentation available
v
constants.HTTP2_HEADER_RANGE
No documentation available
v
constants.HTTP2_HEADER_REFERER
No documentation available
v
constants.HTTP2_HEADER_REFRESH
No documentation available
v
constants.HTTP2_HEADER_RETRY_AFTER
No documentation available
v
constants.HTTP2_HEADER_SCHEME
No documentation available
v
constants.HTTP2_HEADER_SERVER
No documentation available
v
constants.HTTP2_HEADER_STATUS
No documentation available
v
constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY
No documentation available
v
constants.HTTP2_HEADER_TE
No documentation available
v
constants.HTTP2_HEADER_TRANSFER_ENCODING
No documentation available
v
constants.HTTP2_HEADER_UPGRADE
No documentation available
v
constants.HTTP2_HEADER_USER_AGENT
No documentation available
v
constants.HTTP2_HEADER_VARY
No documentation available
v
constants.HTTP2_HEADER_VIA
No documentation available
v
constants.HTTP2_HEADER_WWW_AUTHENTICATE
No documentation available
v
constants.HTTP2_METHOD_ACL
No documentation available
v
constants.HTTP2_METHOD_BASELINE_CONTROL
No documentation available
v
constants.HTTP2_METHOD_BIND
No documentation available
v
constants.HTTP2_METHOD_CHECKIN
No documentation available
v
constants.HTTP2_METHOD_CHECKOUT
No documentation available
v
constants.HTTP2_METHOD_CONNECT
No documentation available
v
constants.HTTP2_METHOD_COPY
No documentation available
v
constants.HTTP2_METHOD_DELETE
No documentation available
v
constants.HTTP2_METHOD_GET
No documentation available
v
constants.HTTP2_METHOD_HEAD
No documentation available
v
constants.HTTP2_METHOD_LABEL
No documentation available
v
constants.HTTP2_METHOD_LINK
No documentation available
v
constants.HTTP2_METHOD_LOCK
No documentation available
v
constants.HTTP2_METHOD_MERGE
No documentation available
v
constants.HTTP2_METHOD_MKACTIVITY
No documentation available
v
constants.HTTP2_METHOD_MKCALENDAR
No documentation available
v
constants.HTTP2_METHOD_MKCOL
No documentation available
v
constants.HTTP2_METHOD_MKREDIRECTREF
No documentation available
v
constants.HTTP2_METHOD_MKWORKSPACE
No documentation available
v
constants.HTTP2_METHOD_MOVE
No documentation available
v
constants.HTTP2_METHOD_OPTIONS
No documentation available
v
constants.HTTP2_METHOD_ORDERPATCH
No documentation available
v
constants.HTTP2_METHOD_PATCH
No documentation available
v
constants.HTTP2_METHOD_POST
No documentation available
v
constants.HTTP2_METHOD_PRI
No documentation available
v
constants.HTTP2_METHOD_PROPFIND
No documentation available
v
constants.HTTP2_METHOD_PROPPATCH
No documentation available
v
constants.HTTP2_METHOD_PUT
No documentation available
v
constants.HTTP2_METHOD_REBIND
No documentation available
v
constants.HTTP2_METHOD_REPORT
No documentation available
v
constants.HTTP2_METHOD_SEARCH
No documentation available
v
constants.HTTP2_METHOD_TRACE
No documentation available
v
constants.HTTP2_METHOD_UNBIND
No documentation available
v
constants.HTTP2_METHOD_UNCHECKOUT
No documentation available
v
constants.HTTP2_METHOD_UNLINK
No documentation available
v
constants.HTTP2_METHOD_UNLOCK
No documentation available
v
constants.HTTP2_METHOD_UPDATE
No documentation available
v
constants.HTTP2_METHOD_UPDATEREDIRECTREF
No documentation available
v
constants.HTTP2_METHOD_VERSION_CONTROL
No documentation available
v
constants.HTTP_STATUS_ACCEPTED
No documentation available
v
constants.HTTP_STATUS_ALREADY_REPORTED
No documentation available
v
constants.HTTP_STATUS_BAD_GATEWAY
No documentation available
v
constants.HTTP_STATUS_BAD_REQUEST
No documentation available
v
constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED
No documentation available
v
constants.HTTP_STATUS_CONFLICT
No documentation available
v
constants.HTTP_STATUS_CONTINUE
No documentation available
v
constants.HTTP_STATUS_CREATED
No documentation available
v
constants.HTTP_STATUS_EXPECTATION_FAILED
No documentation available
v
constants.HTTP_STATUS_FAILED_DEPENDENCY
No documentation available
v
constants.HTTP_STATUS_FORBIDDEN
No documentation available
v
constants.HTTP_STATUS_FOUND
No documentation available
v
constants.HTTP_STATUS_GATEWAY_TIMEOUT
No documentation available
v
constants.HTTP_STATUS_GONE
No documentation available
v
constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED
No documentation available
v
constants.HTTP_STATUS_IM_USED
No documentation available
v
constants.HTTP_STATUS_INSUFFICIENT_STORAGE
No documentation available
v
constants.HTTP_STATUS_INTERNAL_SERVER_ERROR
No documentation available
v
constants.HTTP_STATUS_LENGTH_REQUIRED
No documentation available
v
constants.HTTP_STATUS_LOCKED
No documentation available
v
constants.HTTP_STATUS_LOOP_DETECTED
No documentation available
v
constants.HTTP_STATUS_METHOD_NOT_ALLOWED
No documentation available
v
constants.HTTP_STATUS_MISDIRECTED_REQUEST
No documentation available
v
constants.HTTP_STATUS_MOVED_PERMANENTLY
No documentation available
v
constants.HTTP_STATUS_MULTI_STATUS
No documentation available
v
constants.HTTP_STATUS_MULTIPLE_CHOICES
No documentation available
v
constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED
No documentation available
v
constants.HTTP_STATUS_NO_CONTENT
No documentation available
v
constants.HTTP_STATUS_NOT_ACCEPTABLE
No documentation available
v
constants.HTTP_STATUS_NOT_EXTENDED
No documentation available
v
constants.HTTP_STATUS_NOT_FOUND
No documentation available
v
constants.HTTP_STATUS_NOT_IMPLEMENTED
No documentation available
v
constants.HTTP_STATUS_NOT_MODIFIED
No documentation available
v
constants.HTTP_STATUS_OK
No documentation available
v
constants.HTTP_STATUS_PARTIAL_CONTENT
No documentation available
v
constants.HTTP_STATUS_PAYLOAD_TOO_LARGE
No documentation available
v
constants.HTTP_STATUS_PAYMENT_REQUIRED
No documentation available
v
constants.HTTP_STATUS_PERMANENT_REDIRECT
No documentation available
v
constants.HTTP_STATUS_PRECONDITION_FAILED
No documentation available
v
constants.HTTP_STATUS_PRECONDITION_REQUIRED
No documentation available
v
constants.HTTP_STATUS_PROCESSING
No documentation available
v
constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED
No documentation available
v
constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE
No documentation available
v
constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE
No documentation available
v
constants.HTTP_STATUS_REQUEST_TIMEOUT
No documentation available
v
constants.HTTP_STATUS_RESET_CONTENT
No documentation available
v
constants.HTTP_STATUS_SEE_OTHER
No documentation available
v
constants.HTTP_STATUS_SWITCHING_PROTOCOLS
No documentation available
v
constants.HTTP_STATUS_TEAPOT
No documentation available
v
constants.HTTP_STATUS_TEMPORARY_REDIRECT
No documentation available
v
constants.HTTP_STATUS_TOO_MANY_REQUESTS
No documentation available
v
constants.HTTP_STATUS_UNORDERED_COLLECTION
No documentation available
v
constants.HTTP_STATUS_UNPROCESSABLE_ENTITY
No documentation available
v
constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE
No documentation available
v
constants.HTTP_STATUS_UPGRADE_REQUIRED
No documentation available
v
constants.HTTP_STATUS_URI_TOO_LONG
No documentation available
v
constants.HTTP_STATUS_USE_PROXY
No documentation available
v
constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES
No documentation available
v
constants.MAX_INITIAL_WINDOW_SIZE
No documentation available
v
constants.MAX_MAX_FRAME_SIZE
No documentation available
v
constants.MIN_MAX_FRAME_SIZE
No documentation available
v
constants.NGHTTP2_CANCEL
No documentation available
v
constants.NGHTTP2_COMPRESSION_ERROR
No documentation available
v
constants.NGHTTP2_CONNECT_ERROR
No documentation available
v
constants.NGHTTP2_DEFAULT_WEIGHT
No documentation available
v
constants.NGHTTP2_ENHANCE_YOUR_CALM
No documentation available
v
constants.NGHTTP2_ERR_FRAME_SIZE_ERROR
No documentation available
v
constants.NGHTTP2_FLAG_ACK
No documentation available
v
constants.NGHTTP2_FLAG_END_HEADERS
No documentation available
v
constants.NGHTTP2_FLAG_END_STREAM
No documentation available
v
constants.NGHTTP2_FLAG_NONE
No documentation available
v
constants.NGHTTP2_FLAG_PADDED
No documentation available
v
constants.NGHTTP2_FLAG_PRIORITY
No documentation available
v
constants.NGHTTP2_FLOW_CONTROL_ERROR
No documentation available
v
constants.NGHTTP2_FRAME_SIZE_ERROR
No documentation available
v
constants.NGHTTP2_HTTP_1_1_REQUIRED
No documentation available
v
constants.NGHTTP2_INADEQUATE_SECURITY
No documentation available
v
constants.NGHTTP2_INTERNAL_ERROR
No documentation available
v
constants.NGHTTP2_NO_ERROR
No documentation available
v
constants.NGHTTP2_PROTOCOL_ERROR
No documentation available
v
constants.NGHTTP2_REFUSED_STREAM
No documentation available
v
constants.NGHTTP2_SESSION_CLIENT
No documentation available
v
constants.NGHTTP2_SESSION_SERVER
No documentation available
v
constants.NGHTTP2_SETTINGS_ENABLE_PUSH
No documentation available
v
constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE
No documentation available
v
constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE
No documentation available
v
constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS
No documentation available
v
constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE
No documentation available
v
constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE
No documentation available
v
constants.NGHTTP2_SETTINGS_TIMEOUT
No documentation available
v
constants.NGHTTP2_STREAM_CLOSED
No documentation available
v
constants.NGHTTP2_STREAM_STATE_CLOSED
No documentation available
v
constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL
No documentation available
v
constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE
No documentation available
v
constants.NGHTTP2_STREAM_STATE_IDLE
No documentation available
v
constants.NGHTTP2_STREAM_STATE_OPEN
No documentation available
v
constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL
No documentation available
v
constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE
No documentation available
v
constants.PADDING_STRATEGY_CALLBACK
No documentation available
v
constants.PADDING_STRATEGY_MAX
No documentation available
v
constants.PADDING_STRATEGY_NONE
No documentation available
f
createSecureServer
Returns a `tls.Server` instance that creates and manages `Http2Session` instances.
```js
import http2 from 'node:http2';
import fs from 'node:fs';
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
};
// Create a secure HTTP/2 server
const server = http2.createSecureServer(options);
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('
Hello World
'); }); server.listen(8443); ```f
createServer
Returns a `net.Server` instance that creates and manages `Http2Session` instances.
Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of [createSecureServer](././node__http2.d.ts/~/createSecureServer) is necessary when
communicating
with browser clients.
```js
import http2 from 'node:http2';
// Create an unencrypted HTTP/2 server.
// Since there are no browsers known that support
// unencrypted HTTP/2, the use of `http2.createSecureServer()`
// is necessary when communicating with browser clients.
const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
});
stream.end('
Hello World
'); }); server.listen(8000); ```f
getDefaultSettings
> [!WARNING] Deno compatibility
> This function is a non-functional stub.
Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called
so instances returned may be safely modified for use.
f
getPackedSettings
> [!WARNING] Deno compatibility
> This function is a non-functional stub.
Returns a `Buffer` instance containing serialized representation of the given
HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended
for use with the `HTTP2-Settings` header field.
```js
import http2 from 'node:http2';
const packed = http2.getPackedSettings({ enablePush: false });
console.log(packed.toString('base64'));
// Prints: AAIAAAAA
```
f
getUnpackedSettings
> [!WARNING] Deno compatibility
> This function is a non-functional stub.
Returns a `HTTP/2 Settings Object` containing the deserialized settings from
the given `Buffer` as generated by `http2.getPackedSettings()`.
I
I
I
c
Http2ServerRequest
A `Http2ServerRequest` object is created by Server or SecureServer and passed as the first argument to the `'request'` event. It may be used to access a request status,
headers, and
data.
c
Http2ServerResponse
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the `'request'` event.
I
Http2Session
> [!WARNING] Deno compatibility
> The following methods are non-functional stubs:
> - setLocalWindowSize
> - ping
> - localSettings
> - remoteSettings
> - settings
> - ref
> - unref
>
I
Http2Stream
> [!WARNING] Deno compatibility
> The following methods are non-functional stubs:
> - aborted
> - bufferSize
> - endAfterHeaders
> - id
> - pending
> - priority
> - rstCode
> - sentHeaders
> - sentInfoHeaders
> - sentTrailers
> - state
>
I
I
I
OutgoingHttpHeaders
No documentation available
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- authorization
- cache-control
- cdn-cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-security-policy
- content-security-policy-report-only
- cookie
- date
- dav
- dnt
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-range
- if-unmodified-since
- last-modified
- link
- location
- max-forwards
- origin
- prgama
- proxy-authenticate
- proxy-authorization
- public-key-pins
- public-key-pins-report-only
- range
- referer
- referrer-policy
- refresh
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- server
- set-cookie
- strict-transport-security
- te
- trailer
- transfer-encoding
- upgrade
- upgrade-insecure-requests
- user-agent
- vary
- via
- warning
- www-authenticate
- x-content-type-options
- x-dns-prefetch-control
- x-frame-options
- x-xss-protection
f
performServerHandshake
Create an HTTP/2 server session from an existing socket.
I
SecureClientSessionOptions
No documentation available
I
I
SecureServerSessionOptions
No documentation available
v
sensitiveHeaders
This symbol can be set as a property on the HTTP/2 headers object with
an array value in order to provide a list of headers considered sensitive.
I
ServerHttp2Session
> [!WARNING] Deno compatibility
> All methods are non-functional stubs.
I
ServerHttp2Stream
No documentation available
I
ServerOptions
No documentation available
I
ServerSessionOptions
No documentation available
I
I
I
I
I
I
I
I
I
StreamState
No documentation available
node__https.d.ts
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module.c
I
f
createServer
```js
// curl -k https://localhost:8000/
import https from 'node:https';
import fs from 'node:fs';
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
Or
```js
import https from 'node:https';
import fs from 'node:fs';
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample',
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
```
f
get
Like `http.get()` but for HTTPS.
`options` can be an object, a string, or a `URL` object. If `options` is a
string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
```js
import https from 'node:https';
https.get('https://encrypted.google.com/', (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});
```
v
globalAgent
No documentation available
f
request
Makes a request to a secure web server.
The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`,
`pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`.
`options` can be an object, a string, or a `URL` object. If `options` is a
string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
`https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to
upload a file with a POST request, then write to the `ClientRequest` object.
```js
import https from '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();
```
Example using options from `tls.connect()`:
```js
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
// ...
});
```
Alternatively, opt out of connection pooling by not using an `Agent`.
```js
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
agent: false,
};
const req = https.request(options, (res) => {
// ...
});
```
Example using a `URL` as `options`:
```js
const options = new URL('https://abc:xyz@example.com');
const req = https.request(options, (res) => {
// ...
});
```
Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
```js
import tls from 'node:tls';
import https from 'node:https';
import crypto from 'node:crypto';
function sha256(s) {
return crypto.createHash('sha256').update(s).digest('base64');
}
const options = {
hostname: 'github.com',
port: 443,
path: '/',
method: 'GET',
checkServerIdentity: function(host, cert) {
// Make sure the certificate is issued to the host we are connected to
const err = tls.checkServerIdentity(host, cert);
if (err) {
return err;
}
// Pin the public key, similar to HPKP pin-sha256 pinning
const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
if (sha256(cert.pubkey) !== pubkey256) {
const msg = 'Certificate verification error: ' +
`The public key of '${cert.subject.CN}' ` +
'does not match our pinned fingerprint';
return new Error(msg);
}
// Pin the exact certificate, rather than the pub key
const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
if (cert.fingerprint256 !== cert256) {
const msg = 'Certificate verification error: ' +
`The certificate of '${cert.subject.CN}' ` +
'does not match our pinned fingerprint';
return new Error(msg);
}
// This loop is informational only.
// Print the certificate and public key fingerprints of all certs in the
// chain. Its common to pin the public key of the issuer on the public
// internet, while pinning the public key of the service in sensitive
// environments.
do {
console.log('Subject Common Name:', cert.subject.CN);
console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
hash = crypto.createHash('sha256');
console.log(' Public key ping-sha256:', sha256(cert.pubkey));
lastprint256 = cert.fingerprint256;
cert = cert.issuerCertificate;
} while (cert.fingerprint256 !== lastprint256);
},
};
options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
console.log('All OK. Server matched our pinned cert or public key');
console.log('statusCode:', res.statusCode);
// Print the HPKP values
console.log('headers:', res.headers['public-key-pins']);
res.on('data', (d) => {});
});
req.on('error', (e) => {
console.error(e.message);
});
req.end();
```
Outputs for example:
```text
Subject Common Name: github.com
Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
Subject Common Name: DigiCert SHA2 Extended Validation Server CA
Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
Subject Common Name: DigiCert High Assurance EV Root CA
Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
All OK. Server matched our pinned cert or public key
statusCode: 200
headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=";
pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=";
pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
```
T
RequestOptions
No documentation available
c
I
Server
> [!WARNING] Deno compatibility
> The `cert` and `key` options do not support an array input.
See `http.Server` for more information.
T
ServerOptions
No documentation available
node__inspector--promises.d.ts
The `node:inspector/promises` module provides an API for interacting with the V8 inspector.f
close
Deactivate the inspector. Blocks until there are no active connections.
N
Console
No documentation available
v
console
An object to send messages to the remote inspector console.
I
N
Debugger
No documentation available
I
T
Debugger.BreakpointId
Breakpoint identifier.
I
I
Debugger.CallFrame
JavaScript call frame. Array of call frames form the call stack.
T
Debugger.CallFrameId
Call frame identifier.
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
Debugger.RestartFrameReturnType
No documentation available
I
I
I
I
I
I
I
I
I
I
I
Debugger.SetBreakpointByUrlParameterType
No documentation available
I
I
I
I
I
I
I
I
Debugger.SetScriptSourceReturnType
No documentation available
I
I
Debugger.SetVariableValueParameterType
No documentation available
I
N
HeapProfiler
No documentation available
I
I
I
I
I
I
I
T
HeapProfiler.HeapSnapshotObjectId
Heap snapshot object id.
I
I
I
I
I
HeapProfiler.SamplingHeapProfileNode
Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
I
I
I
I
I
I
N
Network
No documentation available
I
Network.Headers
Request / response headers as keys / values of JSON object.
f
Network.loadingFailed
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
HTTP request has failed to load.
I
f
Network.loadingFinished
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
HTTP request has finished loading.
I
T
Network.MonotonicTime
Monotonically increasing time in seconds since an arbitrary point in the past.
I
T
Network.RequestId
Unique request identifier.
f
Network.requestWillBeSent
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
the application is about to send an HTTP request.
I
T
Network.ResourceType
Resource type as it was perceived by the rendering engine.
I
f
Network.responseReceived
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
HTTP response is available.
I
T
Network.TimeSinceEpoch
UTC time in seconds, counted from January 1, 1970.
N
NodeRuntime
No documentation available
I
N
NodeTracing
No documentation available
I
I
I
I
N
NodeWorker
No documentation available
I
NodeWorker.AttachedToWorkerEventDataType
No documentation available
I
I
I
I
I
T
NodeWorker.SessionID
Unique identifier of attached debugging session.
T
NodeWorker.WorkerID
No documentation available
I
f
open
Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has
started.
If wait is `true`, will block until a client has connected to the inspect port
and flow control has been passed to the debugger client.
See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
regarding the `host` parameter usage.
N
Profiler
No documentation available
I
I
I
I
I
I
Profiler.PositionTickInfo
Specifies a number of samples attributed to a certain source position.
I
Profiler.ProfileNode
Profile node. Holds callsite information, execution statistics and child nodes.
I
I
I
I
I
N
Runtime
No documentation available
I
Runtime.AwaitPromiseParameterType
No documentation available
I
I
Runtime.CallArgument
Represents function call argument. Either remote object id
objectId
, primitive value
, unserializable primitive value or neither of (for undefined) them should be specified.I
Runtime.CallFrame
Stack entry for runtime errors and assertions.
I
I
I
Runtime.CompileScriptParameterType
No documentation available
I
I
Runtime.ConsoleAPICalledEventDataType
No documentation available
I
Runtime.CustomPreview
No documentation available
I
I
I
I
Runtime.ExceptionDetails
Detailed information about exception (or error) that was thrown during script compilation or execution.
I
I
I
I
I
T
Runtime.ExecutionContextId
Id of an execution context.
I
Runtime.GetPropertiesParameterType
No documentation available
I
I
I
I
I
Runtime.InternalPropertyDescriptor
Object internal property descriptor. This property isn't normally visible in JavaScript code.
I
Runtime.ObjectPreview
Object containing abbreviated remote object value.
I
Runtime.PropertyDescriptor
Object property descriptor.
I
I
I
I
I
I
Runtime.RemoteObject
Mirror object referencing original JavaScript object.
T
Runtime.RemoteObjectId
Unique object identifier.
I
I
T
Runtime.ScriptId
Unique script identifier.
I
I
I
Runtime.StackTraceId
If
debuggerId
is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace
and Debugger.paused
for usages.T
Runtime.Timestamp
Number of milliseconds since epoch.
T
Runtime.UniqueDebuggerId
Unique identifier of current debugger.
T
Runtime.UnserializableValue
Primitive value which cannot be JSON-stringified.
N
Schema
No documentation available
I
I
c
Session
The `inspector.Session` is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.
f
url
Return the URL of the active inspector, or `undefined` if there is none.
```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/en/docs/inspector
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/en/docs/inspector
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
$ node -p 'inspector.url()'
undefined
```
f
waitForDebugger
Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command.
An exception will be thrown if there is no active inspector.
node__inspector.d.ts
> [!WARNING] Deno compatibility > `console` is supported. Other APIs are non-functional stubs. The `node:inspector` module provides an API for interacting with the V8 inspector.f
close
Deactivate the inspector. Blocks until there are no active connections.
N
Console
No documentation available
v
console
An object to send messages to the remote inspector console.
I
N
Debugger
No documentation available
I
T
Debugger.BreakpointId
Breakpoint identifier.
I
I
Debugger.CallFrame
JavaScript call frame. Array of call frames form the call stack.
T
Debugger.CallFrameId
Call frame identifier.
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
Debugger.RestartFrameReturnType
No documentation available
I
I
I
I
I
I
I
I
I
I
I
Debugger.SetBreakpointByUrlParameterType
No documentation available
I
I
I
I
I
I
I
I
Debugger.SetScriptSourceReturnType
No documentation available
I
I
Debugger.SetVariableValueParameterType
No documentation available
I
N
HeapProfiler
No documentation available
I
I
I
I
I
I
I
T
HeapProfiler.HeapSnapshotObjectId
Heap snapshot object id.
I
I
I
I
I
HeapProfiler.SamplingHeapProfileNode
Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.
I
I
I
I
I
I
I
N
Network
No documentation available
I
Network.Headers
Request / response headers as keys / values of JSON object.
f
Network.loadingFailed
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.loadingFailed` event to connected frontends. This event indicates that
HTTP request has failed to load.
I
f
Network.loadingFinished
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.loadingFinished` event to connected frontends. This event indicates that
HTTP request has finished loading.
I
T
Network.MonotonicTime
Monotonically increasing time in seconds since an arbitrary point in the past.
I
T
Network.RequestId
Unique request identifier.
f
Network.requestWillBeSent
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.requestWillBeSent` event to connected frontends. This event indicates that
the application is about to send an HTTP request.
I
T
Network.ResourceType
Resource type as it was perceived by the rendering engine.
I
f
Network.responseReceived
This feature is only available with the `--experimental-network-inspection` flag enabled.
Broadcasts the `Network.responseReceived` event to connected frontends. This event indicates that
HTTP response is available.
I
T
Network.TimeSinceEpoch
UTC time in seconds, counted from January 1, 1970.
N
NodeRuntime
No documentation available
I
N
NodeTracing
No documentation available
I
I
I
I
N
NodeWorker
No documentation available
I
NodeWorker.AttachedToWorkerEventDataType
No documentation available
I
I
I
I
I
T
NodeWorker.SessionID
Unique identifier of attached debugging session.
T
NodeWorker.WorkerID
No documentation available
I
f
open
Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has
started.
If wait is `true`, will block until a client has connected to the inspect port
and flow control has been passed to the debugger client.
See the [security warning](https://nodejs.org/docs/latest-v22.x/api/cli.html#warning-binding-inspector-to-a-public-ipport-combination-is-insecure)
regarding the `host` parameter usage.
N
Profiler
No documentation available
I
I
I
I
I
I
Profiler.PositionTickInfo
Specifies a number of samples attributed to a certain source position.
I
Profiler.ProfileNode
Profile node. Holds callsite information, execution statistics and child nodes.
I
I
I
I
I
N
Runtime
No documentation available
I
Runtime.AwaitPromiseParameterType
No documentation available
I
I
Runtime.CallArgument
Represents function call argument. Either remote object id
objectId
, primitive value
, unserializable primitive value or neither of (for undefined) them should be specified.I
Runtime.CallFrame
Stack entry for runtime errors and assertions.
I
I
I
Runtime.CompileScriptParameterType
No documentation available
I
I
Runtime.ConsoleAPICalledEventDataType
No documentation available
I
Runtime.CustomPreview
No documentation available
I
I
I
I
Runtime.ExceptionDetails
Detailed information about exception (or error) that was thrown during script compilation or execution.
I
I
I
I
I
T
Runtime.ExecutionContextId
Id of an execution context.
I
Runtime.GetPropertiesParameterType
No documentation available
I
I
I
I
I
Runtime.InternalPropertyDescriptor
Object internal property descriptor. This property isn't normally visible in JavaScript code.
I
Runtime.ObjectPreview
Object containing abbreviated remote object value.
I
Runtime.PropertyDescriptor
Object property descriptor.
I
I
I
I
I
I
Runtime.RemoteObject
Mirror object referencing original JavaScript object.
T
Runtime.RemoteObjectId
Unique object identifier.
I
I
T
Runtime.ScriptId
Unique script identifier.
I
I
I
Runtime.StackTraceId
If
debuggerId
is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace
and Debugger.paused
for usages.T
Runtime.Timestamp
Number of milliseconds since epoch.
T
Runtime.UniqueDebuggerId
Unique identifier of current debugger.
T
Runtime.UnserializableValue
Primitive value which cannot be JSON-stringified.
N
Schema
No documentation available
I
I
c
Session
The `inspector.Session` is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.
f
url
Return the URL of the active inspector, or `undefined` if there is none.
```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/en/docs/inspector
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/en/docs/inspector
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
$ node -p 'inspector.url()'
undefined
```
f
waitForDebugger
Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command.
An exception will be thrown if there is no active inspector.
I
c
I
N
Module
> [!WARNING] Deno compatibility
> The `register` method is a non-functional stub.
f
Module.findSourceMap
`path` is the resolved path for the file for which a corresponding source map
should be fetched.
I
I
T
Module.InitializeHook
The `initialize` hook provides a way to define a custom function that runs in the hooks thread
when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`.
This hook can receive data from a `register` invocation, including ports and other transferrable objects.
The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes.
I
T
Module.LoadHook
The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed.
It is also in charge of validating the import assertion.
I
T
Module.ModuleFormat
No documentation available
T
Module.ModuleSource
No documentation available
I
T
Module.ResolveHook
The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook.
If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`);
if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook.
I
c
I
Module.SourceMapPayload
No documentation available
I
Module.SourceMapping
No documentation available
I
f
Module.syncBuiltinESMExports
The `module.syncBuiltinESMExports()` method updates all the live bindings for
builtin `ES Modules` to match the properties of the `CommonJS` exports. It
does not add or remove exported names from the `ES Modules`.
```js
import fs from 'node:fs';
import assert from 'node:assert';
import { syncBuiltinESMExports } from 'node:module';
fs.readFile = newAPI;
delete fs.readFileSync;
function newAPI() {
// ...
}
fs.newAPI = newAPI;
syncBuiltinESMExports();
import('node:fs').then((esmFS) => {
// It syncs the existing readFile property with the new value
assert.strictEqual(esmFS.readFile, newAPI);
// readFileSync has been deleted from the required fs
assert.strictEqual('readFileSync' in fs, false);
// syncBuiltinESMExports() does not remove readFileSync from esmFS
assert.strictEqual('readFileSync' in esmFS, true);
// syncBuiltinESMExports() does not add names
assert.strictEqual(esmFS.newAPI, undefined);
});
```
I
T
Module.GlobalPreloadHook
No documentation available
node__net.d.ts
> Stability: 2 - Stable The `node:net` module provides an asynchronous network API for creating stream-based TCP or `IPC` servers ([createServer](././node__net.d.ts/~/createServer)) and clients ([createConnection](././node__net.d.ts/~/createConnection)). It can be accessed using: ```js import net from 'node:net'; ```I
c
f
connect
Aliases to [createConnection](././node__net.d.ts/~/createConnection).
Possible signatures:
* [connect](././node__net.d.ts/~/connect)
* [connect](././node__net.d.ts/~/connect) for `IPC` connections.
* [connect](././node__net.d.ts/~/connect) for TCP connections.
f
createConnection
A factory function, which creates a new [Socket](././node__net.d.ts/~/Socket),
immediately initiates connection with `socket.connect()`,
then returns the `net.Socket` that starts the connection.
When the connection is established, a `'connect'` event will be emitted
on the returned socket. The last parameter `connectListener`, if supplied,
will be added as a listener for the `'connect'` event **once**.
Possible signatures:
* [createConnection](././node__net.d.ts/~/createConnection)
* [createConnection](././node__net.d.ts/~/createConnection) for `IPC` connections.
* [createConnection](././node__net.d.ts/~/createConnection) for TCP connections.
The [connect](././node__net.d.ts/~/connect) function is an alias to this function.
f
createServer
Creates a new TCP or `IPC` server.
If `allowHalfOpen` is set to `true`, when the other end of the socket
signals the end of transmission, the server will only send back the end of
transmission when `socket.end()` is explicitly called. For example, in the
context of TCP, when a FIN packed is received, a FIN packed is sent
back only when `socket.end()` is explicitly called. Until then the
connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information.
If `pauseOnConnect` is set to `true`, then the socket associated with each
incoming connection will be paused, and no data will be read from its handle.
This allows connections to be passed between processes without any data being
read by the original process. To begin reading data from a paused socket, call `socket.resume()`.
The server can be a TCP server or an `IPC` server, depending on what it `listen()` to.
Here is an example of a TCP echo server which listens for connections
on port 8124:
```js
import net from 'node:net';
const server = net.createServer((c) => {
// 'connection' listener.
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
```
Test this by using `telnet`:
```bash
telnet localhost 8124
```
To listen on the socket `/tmp/echo.sock`:
```js
server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
```
Use `nc` to connect to a Unix domain socket server:
```bash
nc -U /tmp/echo.sock
```
I
DropArgument
No documentation available
f
getDefaultAutoSelectFamily
Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`.
The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided.
f
getDefaultAutoSelectFamilyAttemptTimeout
Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`.
I
I
T
IPVersion
No documentation available
f
isIP
Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4
address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`.
```js
net.isIP('::1'); // returns 6
net.isIP('127.0.0.1'); // returns 4
net.isIP('127.000.000.001'); // returns 0
net.isIP('127.0.0.1/24'); // returns 0
net.isIP('fhqwhgads'); // returns 0
```
f
isIPv4
Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no
leading zeroes. Otherwise, returns `false`.
```js
net.isIPv4('127.0.0.1'); // returns true
net.isIPv4('127.000.000.001'); // returns false
net.isIPv4('127.0.0.1/24'); // returns false
net.isIPv4('fhqwhgads'); // returns false
```
f
isIPv6
Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`.
```js
net.isIPv6('::1'); // returns true
net.isIPv6('fhqwhgads'); // returns false
```
I
T
LookupFunction
No documentation available
T
NetConnectOpts
No documentation available
I
c
Server
This class is used to create a TCP or `IPC` server.
I
ServerOpts
No documentation available
f
setDefaultAutoSelectFamily
Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`.
f
setDefaultAutoSelectFamilyAttemptTimeout
Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
c
Socket
> [!WARNING] Deno compatibility
> The `fd` option is not supported.
This class is an abstraction of a TCP socket or a streaming `IPC` endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
an `EventEmitter`.
A `net.Socket` can be created by the user and used directly to interact with
a server. For example, it is returned by [createConnection](././node__net.d.ts/~/createConnection),
so the user can use it to talk to the server.
It can also be created by Node.js and passed to the user when a connection
is received. For example, it is passed to the listeners of a `'connection'` event emitted on a [Server](././node__net.d.ts/~/Server), so the user can use
it to interact with the client.
- addListener
- address
- autoSelectFamilyAttemptedAddresses
- bufferSize
- bytesRead
- bytesWritten
- connect
- connecting
- destroySoon
- destroyed
- emit
- end
- localAddress
- localFamily
- localPort
- on
- once
- pause
- pending
- prependListener
- prependOnceListener
- readyState
- ref
- remoteAddress
- remoteFamily
- remotePort
- resetAndDestroy
- resume
- setEncoding
- setKeepAlive
- setNoDelay
- setTimeout
- timeout
- unref
- write
c
I
T
SocketConnectOpts
No documentation available
I
T
SocketReadyState
No documentation available
I
I
I
ConnectOpts
No documentation available
node__os.d.ts
The `node:os` module provides operating system-related utility methods and properties. It can be accessed using: ```js import os from 'node:os'; ```f
arch
Returns the operating system CPU architecture for which the Node.js binary was
compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`,
and `'x64'`.
The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v22.x/api/process.html#processarch).
f
availableParallelism
Returns an estimate of the default amount of parallelism a program should use.
Always returns a value greater than zero.
This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism).
N
constants
No documentation available
N
constants.dlopen
No documentation available
v
constants.dlopen.RTLD_DEEPBIND
No documentation available
v
constants.dlopen.RTLD_GLOBAL
No documentation available
v
constants.dlopen.RTLD_LAZY
No documentation available
v
constants.dlopen.RTLD_LOCAL
No documentation available
v
constants.dlopen.RTLD_NOW
No documentation available
N
constants.errno
No documentation available
v
constants.errno.E2BIG
No documentation available
v
constants.errno.EACCES
No documentation available
v
constants.errno.EADDRINUSE
No documentation available
v
constants.errno.EADDRNOTAVAIL
No documentation available
v
constants.errno.EAFNOSUPPORT
No documentation available
v
constants.errno.EAGAIN
No documentation available
v
constants.errno.EALREADY
No documentation available
v
constants.errno.EBADF
No documentation available
v
constants.errno.EBADMSG
No documentation available
v
constants.errno.EBUSY
No documentation available
v
constants.errno.ECANCELED
No documentation available
v
constants.errno.ECHILD
No documentation available
v
constants.errno.ECONNABORTED
No documentation available
v
constants.errno.ECONNREFUSED
No documentation available
v
constants.errno.ECONNRESET
No documentation available
v
constants.errno.EDEADLK
No documentation available
v
constants.errno.EDESTADDRREQ
No documentation available
v
constants.errno.EDOM
No documentation available
v
constants.errno.EDQUOT
No documentation available
v
constants.errno.EEXIST
No documentation available
v
constants.errno.EFAULT
No documentation available
v
constants.errno.EFBIG
No documentation available
v
constants.errno.EHOSTUNREACH
No documentation available
v
constants.errno.EIDRM
No documentation available
v
constants.errno.EILSEQ
No documentation available
v
constants.errno.EINPROGRESS
No documentation available
v
constants.errno.EINTR
No documentation available
v
constants.errno.EINVAL
No documentation available
v
constants.errno.EIO
No documentation available
v
constants.errno.EISCONN
No documentation available
v
constants.errno.EISDIR
No documentation available
v
constants.errno.ELOOP
No documentation available
v
constants.errno.EMFILE
No documentation available
v
constants.errno.EMLINK
No documentation available
v
constants.errno.EMSGSIZE
No documentation available
v
constants.errno.EMULTIHOP
No documentation available
v
constants.errno.ENAMETOOLONG
No documentation available
v
constants.errno.ENETDOWN
No documentation available
v
constants.errno.ENETRESET
No documentation available
v
constants.errno.ENETUNREACH
No documentation available
v
constants.errno.ENFILE
No documentation available
v
constants.errno.ENOBUFS
No documentation available
v
constants.errno.ENODATA
No documentation available
v
constants.errno.ENODEV
No documentation available
v
constants.errno.ENOENT
No documentation available
v
constants.errno.ENOEXEC
No documentation available
v
constants.errno.ENOLCK
No documentation available
v
constants.errno.ENOLINK
No documentation available
v
constants.errno.ENOMEM
No documentation available
v
constants.errno.ENOMSG
No documentation available
v
constants.errno.ENOPROTOOPT
No documentation available
v
constants.errno.ENOSPC
No documentation available
v
constants.errno.ENOSR
No documentation available
v
constants.errno.ENOSTR
No documentation available
v
constants.errno.ENOSYS
No documentation available
v
constants.errno.ENOTCONN
No documentation available
v
constants.errno.ENOTDIR
No documentation available
v
constants.errno.ENOTEMPTY
No documentation available
v
constants.errno.ENOTSOCK
No documentation available
v
constants.errno.ENOTSUP
No documentation available
v
constants.errno.ENOTTY
No documentation available
v
constants.errno.ENXIO
No documentation available
v
constants.errno.EOPNOTSUPP
No documentation available
v
constants.errno.EOVERFLOW
No documentation available
v
constants.errno.EPERM
No documentation available
v
constants.errno.EPIPE
No documentation available
v
constants.errno.EPROTO
No documentation available
v
constants.errno.EPROTONOSUPPORT
No documentation available
v
constants.errno.EPROTOTYPE
No documentation available
v
constants.errno.ERANGE
No documentation available
v
constants.errno.EROFS
No documentation available
v
constants.errno.ESPIPE
No documentation available
v
constants.errno.ESRCH
No documentation available
v
constants.errno.ESTALE
No documentation available
v
constants.errno.ETIME
No documentation available
v
constants.errno.ETIMEDOUT
No documentation available
v
constants.errno.ETXTBSY
No documentation available
v
constants.errno.EWOULDBLOCK
No documentation available
v
constants.errno.EXDEV
No documentation available
v
constants.errno.WSA_E_CANCELLED
No documentation available
v
constants.errno.WSA_E_NO_MORE
No documentation available
v
constants.errno.WSAEACCES
No documentation available
v
constants.errno.WSAEADDRINUSE
No documentation available
v
constants.errno.WSAEADDRNOTAVAIL
No documentation available
v
constants.errno.WSAEAFNOSUPPORT
No documentation available
v
constants.errno.WSAEALREADY
No documentation available
v
constants.errno.WSAEBADF
No documentation available
v
constants.errno.WSAECANCELLED
No documentation available
v
constants.errno.WSAECONNABORTED
No documentation available
v
constants.errno.WSAECONNREFUSED
No documentation available
v
constants.errno.WSAECONNRESET
No documentation available
v
constants.errno.WSAEDESTADDRREQ
No documentation available
v
constants.errno.WSAEDISCON
No documentation available
v
constants.errno.WSAEDQUOT
No documentation available
v
constants.errno.WSAEFAULT
No documentation available
v
constants.errno.WSAEHOSTDOWN
No documentation available
v
constants.errno.WSAEHOSTUNREACH
No documentation available
v
constants.errno.WSAEINPROGRESS
No documentation available
v
constants.errno.WSAEINTR
No documentation available
v
constants.errno.WSAEINVAL
No documentation available
v
constants.errno.WSAEINVALIDPROCTABLE
No documentation available
v
constants.errno.WSAEINVALIDPROVIDER
No documentation available
v
constants.errno.WSAEISCONN
No documentation available
v
constants.errno.WSAELOOP
No documentation available
v
constants.errno.WSAEMFILE
No documentation available
v
constants.errno.WSAEMSGSIZE
No documentation available
v
constants.errno.WSAENAMETOOLONG
No documentation available
v
constants.errno.WSAENETDOWN
No documentation available
v
constants.errno.WSAENETRESET
No documentation available
v
constants.errno.WSAENETUNREACH
No documentation available
v
constants.errno.WSAENOBUFS
No documentation available
v
constants.errno.WSAENOMORE
No documentation available
v
constants.errno.WSAENOPROTOOPT
No documentation available
v
constants.errno.WSAENOTCONN
No documentation available
v
constants.errno.WSAENOTEMPTY
No documentation available
v
constants.errno.WSAENOTSOCK
No documentation available
v
constants.errno.WSAEOPNOTSUPP
No documentation available
v
constants.errno.WSAEPFNOSUPPORT
No documentation available
v
constants.errno.WSAEPROCLIM
No documentation available
v
constants.errno.WSAEPROTONOSUPPORT
No documentation available
v
constants.errno.WSAEPROTOTYPE
No documentation available
v
constants.errno.WSAEPROVIDERFAILEDINIT
No documentation available
v
constants.errno.WSAEREFUSED
No documentation available
v
constants.errno.WSAEREMOTE
No documentation available
v
constants.errno.WSAESHUTDOWN
No documentation available
v
constants.errno.WSAESOCKTNOSUPPORT
No documentation available
v
constants.errno.WSAESTALE
No documentation available
v
constants.errno.WSAETIMEDOUT
No documentation available
v
constants.errno.WSAETOOMANYREFS
No documentation available
v
constants.errno.WSAEUSERS
No documentation available
v
constants.errno.WSAEWOULDBLOCK
No documentation available
v
constants.errno.WSANOTINITIALISED
No documentation available
v
constants.errno.WSASERVICE_NOT_FOUND
No documentation available
v
constants.errno.WSASYSCALLFAILURE
No documentation available
v
constants.errno.WSASYSNOTREADY
No documentation available
v
constants.errno.WSATYPE_NOT_FOUND
No documentation available
v
constants.errno.WSAVERNOTSUPPORTED
No documentation available
N
constants.priority
No documentation available
v
constants.priority.PRIORITY_ABOVE_NORMAL
No documentation available
v
constants.priority.PRIORITY_BELOW_NORMAL
No documentation available
v
constants.priority.PRIORITY_HIGH
No documentation available
v
constants.priority.PRIORITY_HIGHEST
No documentation available
v
constants.priority.PRIORITY_LOW
No documentation available
v
constants.priority.PRIORITY_NORMAL
No documentation available
N
v
constants.signals
No documentation available
v
constants.UV_UDP_REUSEADDR
No documentation available
I
f
cpus
Returns an array of objects containing information about each logical CPU core.
The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable.
The properties included on each object include:
```js
[
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 252020,
nice: 0,
sys: 30340,
idle: 1070356870,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 306960,
nice: 0,
sys: 26980,
idle: 1071569080,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 248450,
nice: 0,
sys: 21750,
idle: 1070919370,
irq: 0,
},
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times: {
user: 256880,
nice: 0,
sys: 19430,
idle: 1070905480,
irq: 20,
},
},
]
```
`nice` values are POSIX-only. On Windows, the `nice` values of all processors
are always 0.
`os.cpus().length` should not be used to calculate the amount of parallelism
available to an application. Use [availableParallelism](././node__os.d.ts/~/availableParallelism) for this purpose.
v
devNull
No documentation available
f
endianness
Returns a string identifying the endianness of the CPU for which the Node.js
binary was compiled.
Possible values are `'BE'` for big endian and `'LE'` for little endian.
v
EOL
The operating system-specific end-of-line marker.
* `\n` on POSIX
* `\r\n` on Windows
f
freemem
Returns the amount of free system memory in bytes as an integer.
f
getPriority
Returns the scheduling priority for the process specified by `pid`. If `pid` is
not provided or is `0`, the priority of the current process is returned.
f
homedir
Returns the string path of the current user's home directory.
On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it
uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory.
On Windows, it uses the `USERPROFILE` environment variable if defined.
Otherwise it uses the path to the profile directory of the current user.
f
hostname
Returns the host name of the operating system as a string.
f
loadavg
Returns an array containing the 1, 5, and 15 minute load averages.
The load average is a measure of system activity calculated by the operating
system and expressed as a fractional number.
The load average is a Unix-specific concept. On Windows, the return value is
always `[0, 0, 0]`.
f
machine
Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
T
NetworkInterfaceInfo
No documentation available
I
I
f
networkInterfaces
Returns an object containing network interfaces that have been assigned a
network address.
Each key on the returned object identifies a network interface. The associated
value is an array of objects that each describe an assigned network address.
The properties available on the assigned network address object include:
```js
{
lo: [
{
address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true,
cidr: '127.0.0.1/8'
},
{
address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
scopeid: 0,
internal: true,
cidr: '::1/128'
}
],
eth0: [
{
address: '192.168.1.108',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '01:02:03:0a:0b:0c',
internal: false,
cidr: '192.168.1.108/24'
},
{
address: 'fe80::a00:27ff:fe4e:66a1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '01:02:03:0a:0b:0c',
scopeid: 1,
internal: false,
cidr: 'fe80::a00:27ff:fe4e:66a1/64'
}
]
}
```
f
platform
Returns a string identifying the operating system platform for which
the Node.js binary was compiled. The value is set at compile time.
Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`.
The return value is equivalent to `process.platform`.
The value `'android'` may also be returned if Node.js is built on the Android
operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os).
f
release
Returns the operating system as a string.
On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See
[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
f
setPriority
Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used.
The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows
priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range
mapping may cause the return value to be slightly different on Windows. To avoid
confusion, set `priority` to one of the priority constants.
On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user
privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`.
T
SignalConstants
No documentation available
f
tmpdir
Returns the operating system's default directory for temporary files as a
string.
f
totalmem
Returns the total amount of system memory in bytes as an integer.
f
type
Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it
returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information
about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems.
f
uptime
Returns the system uptime in number of seconds.
f
userInfo
Returns information about the currently effective user. On POSIX platforms,
this is typically a subset of the password file. The returned object includes
the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`.
The value of `homedir` returned by `os.userInfo()` is provided by the operating
system. This differs from the result of `os.homedir()`, which queries
environment variables for the home directory before falling back to the
operating system response.
Throws a [`SystemError`](https://nodejs.org/docs/latest-v22.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`.
f
version
Returns a string identifying the kernel version.
On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
node__path.d.ts
The `node:path` module provides utilities for working with file and directory paths. It can be accessed using: ```js import path from 'node:path'; ```N
v
default
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
```js
import path from 'node:path';
```
I
I
N
v
path
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
```js
import path from 'node:path';
```
I
node__perf_hooks.d.ts
This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for Node.js-specific performance measurements. Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): * [High Resolution Time](https://www.w3.org/TR/hr-time-2) * [Performance Timeline](https://w3c.github.io/performance-timeline/) * [User Timing](https://www.w3.org/TR/user-timing/) * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) ```js import { PerformanceObserver, performance } from 'node:perf_hooks'; const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); performance.clearMarks(); }); obs.observe({ type: 'measure' }); performance.measure('Start to Now'); performance.mark('A'); doSomeLongRunningProcess(() => { performance.measure('A to Now', 'A'); performance.mark('B'); performance.measure('A to B', 'A', 'B'); }); ```N
constants
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_NO
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
No documentation available
v
constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
No documentation available
v
constants.NODE_PERFORMANCE_GC_INCREMENTAL
No documentation available
v
constants.NODE_PERFORMANCE_GC_MAJOR
No documentation available
v
constants.NODE_PERFORMANCE_GC_MINOR
No documentation available
v
constants.NODE_PERFORMANCE_GC_WEAKCB
No documentation available
f
createHistogram
Returns a `RecordableHistogram`.
I
T
EntryType
No documentation available
I
T
EventLoopUtilityFunction
No documentation available
I
I
I
I
I
f
monitorEventLoopDelay
> [!WARNING] Deno compatibility
> This symbol is not implemented.
_This property is an extension by Node.js. It is not available in Web browsers._
Creates an `IntervalHistogram` object that samples and reports the event loop
delay over time. The delays will be reported in nanoseconds.
Using a timer to detect approximate event loop delay works because the
execution of timers is tied specifically to the lifecycle of the libuv
event loop. That is, a delay in the loop will cause a delay in the execution
of the timer, and those delays are specifically what this API is intended to
detect.
```js
import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));
```
I
I
v
performance
No documentation available
c
v
c
v
c
v
PerformanceMeasure
Exposes measures created via the `Performance.measure()` method.
The constructor of this class is not exposed to users directly.
c
PerformanceNodeTiming
_This property is an extension by Node.js. It is not available in Web browsers._
Provides timing details for Node.js itself. The constructor of this class
is not exposed to users.
c
v
T
PerformanceObserverCallback
No documentation available
c
v
c
v
PerformanceResourceTiming
Provides detailed network timing data regarding the loading of an application's resources.
The constructor of this class is not exposed to users directly.
I
I
T
Architecture
No documentation available
T
BeforeExitListener
No documentation available
T
DisconnectListener
No documentation available
I
T
ExitListener
No documentation available
I
I
T
MessageListener
No documentation available
T
MultipleResolveListener
No documentation available
T
MultipleResolveType
No documentation available
T
Platform
No documentation available
I
Process
No documentation available
- abort
- addListener
- allowedNodeEnvironmentFlags
- arch
- argv
- argv0
- availableMemory
- channel
- chdir
- config
- connected
- constrainedMemory
- cpuUsage
- cwd
- debugPort
- disconnect
- dlopen
- emit
- emitWarning
- env
- execArgv
- execPath
- exit
- exitCode
- features
- finalization
- getActiveResourcesInfo
- getBuiltinModule
- getegid
- geteuid
- getgid
- getgroups
- getuid
- hasUncaughtExceptionCaptureCallback
- hrtime
- kill
- listeners
- loadEnvFile
- mainModule
- memoryUsage
- nextTick
- on
- once
- permission
- pid
- platform
- ppid
- prependListener
- prependOnceListener
- release
- report
- resourceUsage
- send
- setSourceMapsEnabled
- setUncaughtExceptionCaptureCallback
- setegid
- seteuid
- setgid
- setgroups
- setuid
- sourceMapsEnabled
- stderr
- stdin
- stdout
- throwDeprecation
- title
- traceDeprecation
- umask
- uptime
- version
- versions
v
process
No documentation available
I
I
I
I
I
I
I
ReadStream
No documentation available
T
RejectionHandledListener
No documentation available
I
T
Signals
No documentation available
T
SignalsListener
No documentation available
T
UncaughtExceptionListener
No documentation available
T
UncaughtExceptionOrigin
No documentation available
T
UnhandledRejectionListener
Most of the time the unhandledRejection will be an Error, but this should not be relied upon
as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error.
T
WarningListener
No documentation available
T
WorkerListener
No documentation available
I
WriteStream
No documentation available
node__punycode.d.ts
**The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users currently depending on the `punycode` module should switch to using the userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It can be accessed using: ```js import punycode from 'node:punycode'; ``` [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is primarily intended for use in Internationalized Domain Names. Because host names in URLs are limited to ASCII characters only, Domain Names that contain non-ASCII characters must be converted into ASCII using the Punycode scheme. For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. The `punycode` module provides a simple implementation of the Punycode standard. The `punycode` module is a third-party dependency used by Node.js and made available to developers as a convenience. Fixes or other modifications to the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project.f
decode
The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only
characters to the equivalent string of Unicode codepoints.
```js
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
```
f
encode
The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters.
```js
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
```
f
toASCII
The `punycode.toASCII()` method converts a Unicode string representing an
Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the
domain name will be converted. Calling `punycode.toASCII()` on a string that
already only contains ASCII characters will have no effect.
```js
// encode domain names
punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
punycode.toASCII('example.com'); // 'example.com'
```
f
toUnicode
The `punycode.toUnicode()` method converts a string representing a domain name
containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be
converted.
```js
// decode domain names
punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
punycode.toUnicode('example.com'); // 'example.com'
```
v
version
No documentation available
node__querystring.d.ts
The `node:querystring` module provides utilities for parsing and formatting URL query strings. It can be accessed using: ```js import querystring from 'node:querystring'; ``` `querystring` is more performant than `URLSearchParams` but is not a standardized API. Use `URLSearchParams` when performance is not critical or when compatibility with browser code is desirable.v
decode
The querystring.decode() function is an alias for querystring.parse().
v
encode
The querystring.encode() function is an alias for querystring.stringify().
f
escape
The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL
query strings.
The `querystring.escape()` method is used by `querystring.stringify()` and is
generally not expected to be used directly. It is exported primarily to allow
application code to provide a replacement percent-encoding implementation if
necessary by assigning `querystring.escape` to an alternative function.
f
parse
The `querystring.parse()` method parses a URL query string (`str`) into a
collection of key and value pairs.
For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into:
```json
{
"foo": "bar",
"abc": ["xyz", "123"]
}
```
The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`,
`obj.hasOwnProperty()`, and others
are not defined and _will not work_.
By default, percent-encoded characters within the query string will be assumed
to use UTF-8 encoding. If an alternative character encoding is used, then an
alternative `decodeURIComponent` option will need to be specified:
```js
// Assuming gbkDecodeURIComponent function already exists...
querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
{ decodeURIComponent: gbkDecodeURIComponent });
```
I
ParsedUrlQuery
No documentation available
I
ParsedUrlQueryInput
No documentation available
I
f
stringify
The `querystring.stringify()` method produces a URL query string from a
given `obj` by iterating through the object's "own properties".
It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
[bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) |
[string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) |
[number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) |
[bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) |
[boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to
empty strings.
```js
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&baz=qux&baz=quux&corge='
querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// Returns 'foo:bar;baz:qux'
```
By default, characters requiring percent-encoding within the query string will
be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified:
```js
// Assuming gbkEncodeURIComponent function already exists,
querystring.stringify({ w: 'ä¸æ–‡', foo: 'bar' }, null, null,
{ encodeURIComponent: gbkEncodeURIComponent });
```
I
StringifyOptions
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
```js
import querystring from 'node:querystring';
```
`querystring` is more performant than `URLSearchParams` but is not a
standardized API. Use `URLSearchParams` when performance is not critical or
when compatibility with browser code is desirable.
f
unescape
The `querystring.unescape()` method performs decoding of URL percent-encoded
characters on the given `str`.
The `querystring.unescape()` method is used by `querystring.parse()` and is
generally not expected to be used directly. It is exported primarily to allow
application code to provide a replacement decoding implementation if
necessary by assigning `querystring.unescape` to an alternative function.
By default, the `querystring.unescape()` method will attempt to use the
JavaScript built-in `decodeURIComponent()` method to decode. If that fails,
a safer equivalent that does not throw on malformed URLs will be used.
f
createInterface
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance.
```js
import readlinePromises from 'node:readline/promises';
const rl = readlinePromises.createInterface({
input: process.stdin,
output: process.stdout,
});
```
Once the `readlinePromises.Interface` instance is created, the most common case
is to listen for the `'line'` event:
```js
rl.on('line', (line) => {
console.log(`Received: ${line}`);
});
```
If `terminal` is `true` for this instance then the `output` stream will get
the best compatibility if it defines an `output.columns` property and emits
a `'resize'` event on the `output` if or when the columns ever change
(`process.stdout` does this automatically when it is a TTY).
c
Interface
Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a
single `input` `Readable` stream and a single `output` `Writable` stream.
The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
c
node__readline.d.ts
The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream (such as [`process.stdin`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdin)) one line at a time. To use the promise-based APIs: ```js import * as readline from 'node:readline/promises'; ``` To use the callback and sync APIs: ```js import * as readline from 'node:readline'; ``` The following simple example illustrates the basic use of the `node:readline` module. ```js import * as readline from 'node:readline/promises'; import { stdin as input, stdout as output } from 'node:process'; const rl = readline.createInterface({ input, output }); const answer = await rl.question('What do you think of Node.js? '); console.log(`Thank you for your valuable feedback: ${answer}`); rl.close(); ``` Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be received on the `input` stream.T
AsyncCompleter
No documentation available
f
clearLine
The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream
in a specified direction identified by `dir`.
f
clearScreenDown
The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) stream from
the current position of the cursor down.
T
Completer
No documentation available
T
CompleterResult
No documentation available
f
createInterface
The `readline.createInterface()` method creates a new `readline.Interface` instance.
```js
import readline from 'node:readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
```
Once the `readline.Interface` instance is created, the most common case is to
listen for the `'line'` event:
```js
rl.on('line', (line) => {
console.log(`Received: ${line}`);
});
```
If `terminal` is `true` for this instance then the `output` stream will get
the best compatibility if it defines an `output.columns` property and emits
a `'resize'` event on the `output` if or when the columns ever change
(`process.stdout` does this automatically when it is a TTY).
When creating a `readline.Interface` using `stdin` as input, the program
will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without
waiting for user input, call `process.stdin.unref()`.
f
cursorTo
The `readline.cursorTo()` method moves cursor to the specified position in a
given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`.
T
Direction
No documentation available
f
emitKeypressEvents
The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input.
Optionally, `interface` specifies a `readline.Interface` instance for which
autocompletion is disabled when copy-pasted input is detected.
If the `stream` is a `TTY`, then it must be in raw mode.
This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop
the `input` from emitting `'keypress'` events.
```js
readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
```
## Example: Tiny CLI
The following example illustrates the use of `readline.Interface` class to
implement a small command-line interface:
```js
import readline from 'node:readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'OHAI> ',
});
rl.prompt();
rl.on('line', (line) => {
switch (line.trim()) {
case 'hello':
console.log('world!');
break;
default:
console.log(`Say what? I might have heard '${line.trim()}'`);
break;
}
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
```
## Example: Read file stream line-by-Line
A common use case for `readline` is to consume an input file one line at a
time. The easiest way to do so is leveraging the `fs.ReadStream` API as
well as a `for await...of` loop:
```js
import fs from 'node:fs';
import readline from 'node:readline';
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
```
Alternatively, one could use the `'line'` event:
```js
import fs from 'node:fs';
import readline from 'node:readline';
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
crlfDelay: Infinity,
});
rl.on('line', (line) => {
console.log(`Line from file: ${line}`);
});
```
Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied:
```js
import { once } from 'node:events';
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
(async function processLineByLine() {
try {
const rl = createInterface({
input: createReadStream('big-file.txt'),
crlfDelay: Infinity,
});
rl.on('line', (line) => {
// Process the line.
});
await once(rl, 'close');
console.log('File processed.');
} catch (err) {
console.error(err);
}
})();
```
c
Interface
Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a
single `input` [Readable](https://nodejs.org/docs/latest-v22.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v22.x/api/stream.html#writable-streams) stream.
The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
f
moveCursor
The `readline.moveCursor()` method moves the cursor _relative_ to its current
position in a given [TTY](https://nodejs.org/docs/latest-v22.x/api/tty.html) `stream`.
N
promises
No documentation available
f
promises.createInterface
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance.
```js
import readlinePromises from 'node:readline/promises';
const rl = readlinePromises.createInterface({
input: process.stdin,
output: process.stdout,
});
```
Once the `readlinePromises.Interface` instance is created, the most common case
is to listen for the `'line'` event:
```js
rl.on('line', (line) => {
console.log(`Received: ${line}`);
});
```
If `terminal` is `true` for this instance then the `output` stream will get
the best compatibility if it defines an `output.columns` property and emits
a `'resize'` event on the `output` if or when the columns ever change
(`process.stdout` does this automatically when it is a TTY).
c
promises.Interface
Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a
single `input` `Readable` stream and a single `output` `Writable` stream.
The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
c
promises.Readline
No documentation available
T
ReadLine
No documentation available
node__repl.d.ts
> [!WARNING] Deno compatibility > All symbols are not supported. The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using: ```js import repl from 'node:repl'; ```c
Recoverable
> [!WARNING] Deno compatibility
> This symbol is not supported.
Indicates a recoverable error that a `REPLServer` can use to support multi-line input.
v
REPL_MODE_SLOPPY
A flag passed in the REPL options. Evaluates expressions in sloppy mode.
v
REPL_MODE_STRICT
A flag passed in the REPL options. Evaluates expressions in strict mode.
This is equivalent to prefacing every repl statement with `'use strict'`.
I
T
REPLCommandAction
> [!WARNING] Deno compatibility
> This symbol is not supported.
T
REPLEval
> [!WARNING] Deno compatibility
> This symbol is not supported.
I
ReplOptions
> [!WARNING] Deno compatibility
> This symbol is not supported.
c
REPLServer
> [!WARNING] Deno compatibility
> This symbol is not supported.
Instances of `repl.REPLServer` are created using the [start](././node__repl.d.ts/~/start) method
or directly using the JavaScript `new` keyword.
```js
import repl from 'node:repl';
const options = { useColors: true };
const firstInstance = repl.start(options);
const secondInstance = new repl.REPLServer(options);
```
T
REPLWriter
> [!WARNING] Deno compatibility
> This symbol is not supported.
f
start
> [!WARNING] Deno compatibility
> This symbol is not supported.
The `repl.start()` method creates and starts a [REPLServer](././node__repl.d.ts/~/REPLServer) instance.
If `options` is a string, then it specifies the input prompt:
```js
import repl from 'node:repl';
// a Unix style prompt
repl.start('$ ');
```
v
writer
This is the default "writer" value, if none is passed in the REPL options,
and it can be overridden by custom print functions.
node__sea.d.ts
> [!WARNING] Deno compatibility > All symbols are not supported. This feature allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed. Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing the injection of a blob prepared by Node.js, which can contain a bundled script, into the `node` binary. During start up, the program checks if anything has been injected. If the blob is found, it executes the script in the blob. Otherwise Node.js operates as it normally does. The single executable application feature currently only supports running a single embedded script using the `CommonJS` module system. Users can create a single executable application from their bundled script with the `node` binary itself and any tool which can inject resources into the binary. Here are the steps for creating a single executable application using one such tool, [postject](https://github.com/nodejs/postject): 1. Create a JavaScript file: ```bash echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js ``` 2. Create a configuration file building a blob that can be injected into the single executable application (see `Generating single executable preparation blobs` for details): ```bash echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json ``` 3. Generate the blob to be injected: ```bash node --experimental-sea-config sea-config.json ``` 4. Create a copy of the `node` executable and name it according to your needs: * On systems other than Windows: ```bash cp $(command -v node) hello ``` * On Windows: ```text node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" ``` The `.exe` extension is necessary. 5. Remove the signature of the binary (macOS and Windows only): * On macOS: ```bash codesign --remove-signature hello ``` * On Windows (optional): [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). If this step is skipped, ignore any signature-related warning from postject. ```powershell signtool remove /s hello.exe ``` 6. Inject the blob into the copied binary by running `postject` with the following options: * `hello` / `hello.exe` \- The name of the copy of the `node` executable created in step 4. * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary where the contents of the blob will be stored. * `sea-prep.blob` \- The name of the blob created in step 1. * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been injected. * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the segment in the binary where the contents of the blob will be stored. To summarize, here is the required command for each platform: * On Linux: ```bash npx postject hello NODE_SEA_BLOB sea-prep.blob \ --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 ``` * On Windows - PowerShell: ```powershell npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 ``` * On Windows - Command Prompt: ```text npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 ``` * On macOS: ```bash npx postject hello NODE_SEA_BLOB sea-prep.blob \ --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ --macho-segment-name NODE_SEA ``` 7. Sign the binary (macOS and Windows only): * On macOS: ```bash codesign --sign - hello ``` * On Windows (optional): A certificate needs to be present for this to work. However, the unsigned binary would still be runnable. ```powershell signtool sign /fd SHA256 hello.exe ``` 8. Run the binary: * On systems other than Windows ```console $ ./hello world Hello, world! ``` * On Windows ```console $ .\hello.exe world Hello, world! ```T
AssetKey
> [!WARNING] Deno compatibility
> This symbol is not supported.
f
getAsset
> [!WARNING] Deno compatibility
> This symbol is not supported.
This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.
f
getAssetAsBlob
> [!WARNING] Deno compatibility
> This symbol is not supported.
Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
An error is thrown when no matching asset can be found.
f
getRawAsset
> [!WARNING] Deno compatibility
> This symbol is not supported.
This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.
Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not
return a copy. Instead, it returns the raw asset bundled inside the executable.
For now, users should avoid writing to the returned array buffer. If the
injected section is not marked as writable or not aligned properly,
writes to the returned array buffer is likely to result in a crash.
f
isSea
> [!WARNING] Deno compatibility
> This symbol is not supported.
node__sqlite.d.ts
> [!WARNING] Deno compatibility > This module is not implemented. The `node:sqlite` module facilitates working with SQLite databases. To access it: ```js import sqlite from 'node:sqlite'; ``` This module is only available under the `node:` scheme. The following will not work: ```js import sqlite from 'node:sqlite'; ``` The following example shows the basic usage of the `node:sqlite` module to open an in-memory database, write data to the database, and then read the data back. ```js import { DatabaseSync } from 'node:sqlite'; const database = new DatabaseSync(':memory:'); // Execute SQL statements from strings. database.exec(` CREATE TABLE data( key INTEGER PRIMARY KEY, value TEXT ) STRICT `); // Create a prepared statement to insert data into the database. const insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)'); // Execute the prepared statement with bound values. insert.run(1, 'hello'); insert.run(2, 'world'); // Create a prepared statement to read data from the database. const query = database.prepare('SELECT * FROM data ORDER BY key'); // Execute the prepared statement and log the result set. console.log(query.all()); // Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ] ```c
DatabaseSync
> [!WARNING] Deno compatibility
> This module is not implemented.
This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs
exposed by this class execute synchronously.
I
I
StatementResultingChanges
> [!WARNING] Deno compatibility
> This module is not implemented.
c
StatementSync
> [!WARNING] Deno compatibility
> This module is not implemented.
This class represents a single [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This class cannot be
instantiated via its constructor. Instead, instances are created via the`database.prepare()` method. All APIs exposed by this class execute
synchronously.
A prepared statement is an efficient binary representation of the SQL used to
create it. Prepared statements are parameterizable, and can be invoked multiple
times with different bound values. Parameters also offer protection against [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) attacks. For these reasons, prepared statements are
preferred
over hand-crafted SQL strings when handling user input.
T
SupportedValueType
> [!WARNING] Deno compatibility
> This module is not implemented.
f
arrayBuffer
No documentation available
f
blob
No documentation available
f
buffer
No documentation available
f
json
No documentation available
f
text
No documentation available
T
BufferSource
No documentation available
I
v
ByteLengthQueuingStrategy
This Streams API interface provides a built-in byte length queuing
strategy that can be used when constructing streams.
I
v
I
v
CountQueuingStrategy
This Streams API interface provides a built-in byte length queuing
strategy that can be used when constructing streams.
I
v
I
I
I
QueuingStrategySize
No documentation available
I
v
ReadableByteStreamController
No documentation available
I
ReadableByteStreamControllerCallback
No documentation available
I
v
ReadableStream
This Streams API interface represents a readable stream of byte data.
I
v
ReadableStreamBYOBReader
[MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)
I
v
ReadableStreamBYOBRequest
[MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)
T
ReadableStreamController
No documentation available
I
v
I
v
I
ReadableStreamErrorCallback
No documentation available
I
I
I
T
ReadableStreamReader
No documentation available
T
ReadableStreamReaderMode
No documentation available
T
ReadableStreamReadResult
No documentation available
I
I
I
I
I
v
I
I
TransformerFlushCallback
No documentation available
I
TransformerStartCallback
No documentation available
I
TransformerTransformCallback
No documentation available
I
v
I
v
TransformStreamDefaultController
No documentation available
I
I
UnderlyingSinkAbortCallback
No documentation available
I
UnderlyingSinkCloseCallback
No documentation available
I
UnderlyingSinkStartCallback
No documentation available
I
UnderlyingSinkWriteCallback
No documentation available
I
I
UnderlyingSourceCancelCallback
No documentation available
I
UnderlyingSourcePullCallback
No documentation available
I
UnderlyingSourceStartCallback
No documentation available
I
v
I
v
WritableStreamDefaultController
This Streams API interface represents a controller allowing control of a
WritableStream's state. When constructing a WritableStream, the
underlying sink is given a corresponding WritableStreamDefaultController
instance to manipulate.
I
v
WritableStreamDefaultWriter
This Streams API interface is the object returned by
WritableStream.getWriter() and once created locks the < writer to the
WritableStream ensuring that no other streams can write to the underlying
sink.
node__stream.d.ts
A stream is an abstract interface for working with streaming data in Node.js. The `node:stream` module provides an API for implementing the stream interface. There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v22.x/api/http.html#class-httpincomingmessage) and [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) are both stream instances. Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v22.x/api/events.html#class-eventemitter). To access the `node:stream` module: ```js import stream from 'node:stream'; ``` The `node:stream` module is useful for creating new types of stream instances. It is usually not necessary to use the `node:stream` module to consume streams.I
T
ComposeFnParam
No documentation available
f
default.addAbortSignal
A stream to attach a signal to.
Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an `AbortController`.
Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the
stream, and `controller.error(new AbortError())` for webstreams.
```js
import fs from 'node:fs';
const controller = new AbortController();
const read = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json')),
);
// Later, abort the operation closing the stream
controller.abort();
```
Or using an `AbortSignal` with a readable stream as an async iterable:
```js
const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // set a timeout
const stream = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json')),
);
(async () => {
try {
for await (const chunk of stream) {
await process(chunk);
}
} catch (e) {
if (e.name === 'AbortError') {
// The operation was cancelled
} else {
throw e;
}
}
})();
```
Or using an `AbortSignal` with a ReadableStream:
```js
const controller = new AbortController();
const rs = new ReadableStream({
start(controller) {
controller.enqueue('hello');
controller.enqueue('world');
controller.close();
},
});
addAbortSignal(controller.signal, rs);
finished(rs, (err) => {
if (err) {
if (err.name === 'AbortError') {
// The operation was cancelled
}
}
});
const reader = rs.getReader();
reader.read().then(({ value, done }) => {
console.log(value); // hello
console.log(done); // false
controller.abort();
});
```
v
default.consumers
No documentation available
c
default.Duplex
Duplex streams are streams that implement both the `Readable` and `Writable` interfaces.
Examples of `Duplex` streams include:
* `TCP sockets`
* `zlib streams`
* `crypto streams`
I
f
default.duplexPair
The utility function `duplexPair` returns an Array with two items,
each being a `Duplex` stream connected to the other side:
```js
const [ sideA, sideB ] = duplexPair();
```
Whatever is written to one stream is made readable on the other. It provides
behavior analogous to a network connection, where the data written by the client
becomes readable by the server, and vice-versa.
The Duplex streams are symmetrical; one or the other may be used without any
difference in behavior.
f
N
default.finished
A readable and/or writable stream/webstream.
A function to get notified when a stream is no longer readable, writable
or has experienced an error or a premature close event.
```js
import { finished } from 'node:stream';
import fs from 'node:fs';
const rs = fs.createReadStream('archive.tar');
finished(rs, (err) => {
if (err) {
console.error('Stream failed.', err);
} else {
console.log('Stream is done reading.');
}
});
rs.resume(); // Drain the stream.
```
Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`.
The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options).
`stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been
invoked. The reason for this is so that unexpected `'error'` events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:
```js
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});
```
f
default.finished.__promisify__
No documentation available
I
f
default.getDefaultHighWaterMark
Returns the default highWaterMark used by streams.
Defaults to `65536` (64 KiB), or `16` for `objectMode`.
f
default.isErrored
Returns whether the stream has encountered an error.
f
default.isReadable
Returns whether the stream is readable.
c
default.PassThrough
The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams.
I
f
N
default.pipeline
A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.
```js
import { pipeline } from 'node:stream';
import fs from 'node:fs';
import zlib from 'node:zlib';
// Use the pipeline API to easily pipe a series of streams
// together and get notified when the pipeline is fully done.
// A pipeline to gzip a potentially huge tar file efficiently:
pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
(err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
},
);
```
The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options).
`stream.pipeline()` will call `stream.destroy(err)` on all streams except:
* `Readable` streams which have emitted `'end'` or `'close'`.
* `Writable` streams which have emitted `'finish'` or `'close'`.
`stream.pipeline()` leaves dangling event listeners on the streams
after the `callback` has been invoked. In the case of reuse of streams after
failure, this can cause event listener leaks and swallowed errors. If the last
stream is readable, dangling event listeners will be removed so that the last
stream can be consumed later.
`stream.pipeline()` closes all the streams when an error is raised.
The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior
once it would destroy the socket without sending the expected response.
See the example below:
```js
import fs from 'node:fs';
import http from 'node:http';
import { pipeline } from 'node:stream';
const server = http.createServer((req, res) => {
const fileStream = fs.createReadStream('./fileNotExist.txt');
pipeline(fileStream, res, (err) => {
if (err) {
console.log(err); // No such file
// this message can't be sent once `pipeline` already destroyed the socket
return res.end('error!!!');
}
});
});
```
f
default.pipeline.__promisify__
No documentation available
T
default.PipelineCallback
No documentation available
T
default.PipelineDestination
No documentation available
T
default.PipelineDestinationIterableFunction
No documentation available
T
default.PipelineDestinationPromiseFunction
No documentation available
I
T
default.PipelinePromise
No documentation available
T
default.PipelineSource
No documentation available
T
default.PipelineSourceFunction
No documentation available
T
default.PipelineTransform
No documentation available
T
default.PipelineTransformSource
No documentation available
v
default.promises
No documentation available
c
I
f
default.setDefaultHighWaterMark
Sets the default highWaterMark used by streams.
c
default.Stream
No documentation available
I
default.StreamOptions
No documentation available
c
default.Transform
Transform streams are `Duplex` streams where the output is in some way
related to the input. Like all `Duplex` streams, `Transform` streams
implement both the `Readable` and `Writable` interfaces.
Examples of `Transform` streams include:
* `zlib streams`
* `crypto streams`
T
default.TransformCallback
No documentation available
I
c
I
f
internal.addAbortSignal
A stream to attach a signal to.
Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an `AbortController`.
Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the
stream, and `controller.error(new AbortError())` for webstreams.
```js
import fs from 'node:fs';
const controller = new AbortController();
const read = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json')),
);
// Later, abort the operation closing the stream
controller.abort();
```
Or using an `AbortSignal` with a readable stream as an async iterable:
```js
const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // set a timeout
const stream = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json')),
);
(async () => {
try {
for await (const chunk of stream) {
await process(chunk);
}
} catch (e) {
if (e.name === 'AbortError') {
// The operation was cancelled
} else {
throw e;
}
}
})();
```
Or using an `AbortSignal` with a ReadableStream:
```js
const controller = new AbortController();
const rs = new ReadableStream({
start(controller) {
controller.enqueue('hello');
controller.enqueue('world');
controller.close();
},
});
addAbortSignal(controller.signal, rs);
finished(rs, (err) => {
if (err) {
if (err.name === 'AbortError') {
// The operation was cancelled
}
}
});
const reader = rs.getReader();
reader.read().then(({ value, done }) => {
console.log(value); // hello
console.log(done); // false
controller.abort();
});
```
v
internal.consumers
No documentation available
c
internal.Duplex
Duplex streams are streams that implement both the `Readable` and `Writable` interfaces.
Examples of `Duplex` streams include:
* `TCP sockets`
* `zlib streams`
* `crypto streams`
I
f
internal.duplexPair
The utility function `duplexPair` returns an Array with two items,
each being a `Duplex` stream connected to the other side:
```js
const [ sideA, sideB ] = duplexPair();
```
Whatever is written to one stream is made readable on the other. It provides
behavior analogous to a network connection, where the data written by the client
becomes readable by the server, and vice-versa.
The Duplex streams are symmetrical; one or the other may be used without any
difference in behavior.
f
N
internal.finished
A readable and/or writable stream/webstream.
A function to get notified when a stream is no longer readable, writable
or has experienced an error or a premature close event.
```js
import { finished } from 'node:stream';
import fs from 'node:fs';
const rs = fs.createReadStream('archive.tar');
finished(rs, (err) => {
if (err) {
console.error('Stream failed.', err);
} else {
console.log('Stream is done reading.');
}
});
rs.resume(); // Drain the stream.
```
Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`.
The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streamfinishedstream-options).
`stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been
invoked. The reason for this is so that unexpected `'error'` events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:
```js
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});
```
f
internal.finished.__promisify__
No documentation available
I
f
internal.getDefaultHighWaterMark
Returns the default highWaterMark used by streams.
Defaults to `65536` (64 KiB), or `16` for `objectMode`.
f
internal.isErrored
Returns whether the stream has encountered an error.
f
internal.isReadable
Returns whether the stream is readable.
c
internal.PassThrough
The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams.
I
f
N
internal.pipeline
A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.
```js
import { pipeline } from 'node:stream';
import fs from 'node:fs';
import zlib from 'node:zlib';
// Use the pipeline API to easily pipe a series of streams
// together and get notified when the pipeline is fully done.
// A pipeline to gzip a potentially huge tar file efficiently:
pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
(err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
},
);
```
The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v22.x/api/stream.html#streampipelinesource-transforms-destination-options).
`stream.pipeline()` will call `stream.destroy(err)` on all streams except:
* `Readable` streams which have emitted `'end'` or `'close'`.
* `Writable` streams which have emitted `'finish'` or `'close'`.
`stream.pipeline()` leaves dangling event listeners on the streams
after the `callback` has been invoked. In the case of reuse of streams after
failure, this can cause event listener leaks and swallowed errors. If the last
stream is readable, dangling event listeners will be removed so that the last
stream can be consumed later.
`stream.pipeline()` closes all the streams when an error is raised.
The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior
once it would destroy the socket without sending the expected response.
See the example below:
```js
import fs from 'node:fs';
import http from 'node:http';
import { pipeline } from 'node:stream';
const server = http.createServer((req, res) => {
const fileStream = fs.createReadStream('./fileNotExist.txt');
pipeline(fileStream, res, (err) => {
if (err) {
console.log(err); // No such file
// this message can't be sent once `pipeline` already destroyed the socket
return res.end('error!!!');
}
});
});
```
f
internal.pipeline.__promisify__
No documentation available
T
internal.PipelineCallback
No documentation available
T
internal.PipelineDestination
No documentation available
T
internal.PipelineDestinationIterableFunction
No documentation available
T
internal.PipelineDestinationPromiseFunction
No documentation available
I
T
internal.PipelinePromise
No documentation available
T
internal.PipelineSource
No documentation available
T
internal.PipelineSourceFunction
No documentation available
T
internal.PipelineTransform
No documentation available
T
internal.PipelineTransformSource
No documentation available
v
internal.promises
No documentation available
c
I
f
internal.setDefaultHighWaterMark
Sets the default highWaterMark used by streams.
c
internal.Stream
No documentation available
I
internal.StreamOptions
No documentation available
c
internal.Transform
Transform streams are `Duplex` streams where the output is in some way
related to the input. Like all `Duplex` streams, `Transform` streams
implement both the `Readable` and `Writable` interfaces.
Examples of `Transform` streams include:
* `zlib streams`
* `crypto streams`
T
internal.TransformCallback
No documentation available
I
c
I
c
ReadableBase
No documentation available
- _construct
- _destroy
- _read
- addListener
- asIndexedPairs
- closed
- destroy
- destroyed
- drop
- emit
- errored
- every
- filter
- find
- flatMap
- forEach
- from
- isDisturbed
- isPaused
- iterator
- map
- on
- once
- pause
- prependListener
- prependOnceListener
- push
- read
- readable
- readableAborted
- readableDidRead
- readableEncoding
- readableEnded
- readableFlowing
- readableHighWaterMark
- readableLength
- readableObjectMode
- reduce
- removeListener
- resume
- setEncoding
- some
- take
- toArray
- unpipe
- unshift
- wrap
c
WritableBase
No documentation available
node__string_decoder.d.ts
The `node:string_decoder` module provides an API for decoding `Buffer` objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 characters. It can be accessed using: ```js import { StringDecoder } from 'node:string_decoder'; ``` The following example shows the basic use of the `StringDecoder` class. ```js import { StringDecoder } from 'node:string_decoder'; const decoder = new StringDecoder('utf8'); const cent = Buffer.from([0xC2, 0xA2]); console.log(decoder.write(cent)); // Prints: ¢ const euro = Buffer.from([0xE2, 0x82, 0xAC]); console.log(decoder.write(euro)); // Prints: € ``` When a `Buffer` instance is written to the `StringDecoder` instance, an internal buffer is used to ensure that the decoded string does not contain any incomplete multibyte characters. These are held in the buffer until the next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. In the following example, the three UTF-8 encoded bytes of the European Euro symbol (`€`) are written over three separate operations: ```js import { StringDecoder } from 'node:string_decoder'; const decoder = new StringDecoder('utf8'); decoder.write(Buffer.from([0xE2])); decoder.write(Buffer.from([0x82])); console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € ```c
StringDecoder
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
characters. It can be accessed using:
```js
import { StringDecoder } from 'node:string_decoder';
```
The following example shows the basic use of the `StringDecoder` class.
```js
import { StringDecoder } from 'node:string_decoder';
const decoder = new StringDecoder('utf8');
const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent)); // Prints: ¢
const euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro)); // Prints: €
```
When a `Buffer` instance is written to the `StringDecoder` instance, an
internal buffer is used to ensure that the decoded string does not contain
any incomplete multibyte characters. These are held in the buffer until the
next call to `stringDecoder.write()` or until `stringDecoder.end()` is called.
In the following example, the three UTF-8 encoded bytes of the European Euro
symbol (`€`) are written over three separate operations:
```js
import { StringDecoder } from 'node:string_decoder';
const decoder = new StringDecoder('utf8');
decoder.write(Buffer.from([0xE2]));
decoder.write(Buffer.from([0x82]));
console.log(decoder.end(Buffer.from([0xAC]))); // Prints: €
```
node__test--reporters.d.ts
The `node:test/reporters` module exposes the builtin-reporters for `node:test`. To access it: ```js import test from 'node:test/reporters'; ``` This module is only available under the `node:` scheme. The following will not work: ```js import test from 'node:test/reporters'; ```f
dot
The `dot` reporter outputs the test results in a compact format,
where each passing test is represented by a `.`,
and each failing test is represented by a `X`.
f
junit
The `junit` reporter outputs test results in a jUnit XML format.
v
lcov
The `lcov` reporter outputs test coverage when used with the
[`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag.
c
LcovReporter
No documentation available
I
ReporterConstructorWrapper
No documentation available
v
spec
The `spec` reporter outputs the test results in a human-readable format.
c
SpecReporter
No documentation available
f
tap
The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format.
T
TestEvent
No documentation available
T
TestEventGenerator
No documentation available
node__timers--promises.d.ts
The `timers/promises` API provides an alternative set of timer functions that return `Promise` objects. The API is accessible via `import timersPromises from 'node:timers/promises'`. ```js import { setTimeout, setImmediate, setInterval, } from 'node:timers/promises'; ```v
scheduler
No documentation available
f
setImmediate
```js
import {
setImmediate,
} from 'node:timers/promises';
const res = await setImmediate('result');
console.log(res); // Prints 'result'
```
f
setInterval
Returns an async iterator that generates values in an interval of `delay` ms.
If `ref` is `true`, you need to call `next()` of async iterator explicitly
or implicitly to keep the event loop alive.
```js
import {
setInterval,
} from 'node:timers/promises';
const interval = 100;
for await (const startTime of setInterval(interval, Date.now())) {
const now = Date.now();
console.log(now);
if ((now - startTime) > 1000)
break;
}
console.log(Date.now());
```
f
setTimeout
```js
import {
setTimeout,
} from 'node:timers/promises';
const res = await setTimeout(100, 'result');
console.log(res); // Prints 'result'
```
node__timers.d.ts
The `timer` module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to import `node:timers` to use the API. The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout).f
v
clearImmediate
Cancels an `Immediate` object created by `setImmediate()`.
f
v
clearInterval
Cancels a `Timeout` object created by `setInterval()`.
f
v
clearTimeout
Cancels a `Timeout` object created by `setTimeout()`.
c
Immediate
This object is created internally and is returned from `setImmediate()`. It
can be passed to `clearImmediate()` in order to cancel the scheduled
actions.
By default, when an immediate is scheduled, the Node.js event loop will continue
running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to
control this default behavior.
f
queueMicrotask
No documentation available
f
N
v
setImmediate
Schedules the "immediate" execution of the `callback` after I/O events'
callbacks.
When multiple calls to `setImmediate()` are made, the `callback` functions are
queued for execution in the order in which they are created. The entire callback
queue is processed every event loop iteration. If an immediate timer is queued
from inside an executing callback, that timer will not be triggered until the
next event loop iteration.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setImmediate()`.
v
setImmediate.__promisify__
No documentation available
f
N
v
setInterval
Schedules repeated execution of `callback` every `delay` milliseconds.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be
set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setInterval()`.
v
setInterval.__promisify__
No documentation available
f
N
v
setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
v
setTimeout.__promisify__
No documentation available
c
Timeout
This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the
scheduled actions.
By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the
timer is active. Each of the `Timeout` objects returned by these functions
export both `timeout.ref()` and `timeout.unref()` functions that can be used to
control this default behavior.
I
node__tls.d.ts
The `node:tls` module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using: ```js import tls from 'node:tls'; ```f
checkServerIdentity
Verifies the certificate `cert` is issued to `hostname`.
Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on
failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).
This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to [connect](././node__tls.d.ts/~/connect) and as
such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.
This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The
overwriting function can call `tls.checkServerIdentity()` of course, to augment
the checks done with additional verification.
This function is only called if the certificate passed all other checks, such as
being issued by trusted CA (`options.ca`).
Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name
was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use
a custom `options.checkServerIdentity` function that implements the desired behavior.
I
v
CLIENT_RENEG_LIMIT
No documentation available
v
CLIENT_RENEG_WINDOW
No documentation available
I
CommonConnectionOptions
No documentation available
f
connect
The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.
`tls.connect()` returns a [TLSSocket](././node__tls.d.ts/~/TLSSocket) object.
Unlike the `https` API, `tls.connect()` does not enable the
SNI (Server Name Indication) extension by default, which may cause some
servers to return an incorrect certificate or reject the connection
altogether. To enable SNI, set the `servername` option in addition
to `host`.
The following illustrates a client for the echo server example from [createServer](././node__tls.d.ts/~/createServer):
```js
// Assumes an echo server that is listening on port 8000.
import tls from 'node:tls';
import fs from 'node:fs';
const options = {
// Necessary only if the server requires client certificate authentication.
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
// Necessary only if the server uses a self-signed certificate.
ca: [ fs.readFileSync('server-cert.pem') ],
// Necessary only if the server's cert isn't for "localhost".
checkServerIdentity: () => { return null; },
};
const socket = tls.connect(8000, options, () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
console.log(data);
});
socket.on('end', () => {
console.log('server ends connection');
});
```
I
ConnectionOptions
No documentation available
f
createSecureContext
`[createServer](././node__tls.d.ts/~/createServer)` sets the default value of the `honorCipherOrder` option
to `true`, other APIs that create secure contexts leave it unset.
`[createServer](././node__tls.d.ts/~/createServer)` uses a 128 bit truncated SHA1 hash value generated
from `process.argv` as the default value of the `sessionIdContext` option, other
APIs that create secure contexts have no default value.
The `tls.createSecureContext()` method creates a `SecureContext` object. It is
usable as an argument to several `tls` APIs, such as `server.addContext()`,
but has no public methods. The [Server](././node__tls.d.ts/~/Server) constructor and the [createServer](././node__tls.d.ts/~/createServer) method do not support the `secureContext` option.
A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it.
If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of
CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).
Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength
will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
be used to create custom parameters. The key length must be greater than or
equal to 1024 bits or else an error will be thrown. Although 1024 bits is
permissible, use 2048 bits or larger for stronger security.
f
createServer
Creates a new [Server](././node__tls.d.ts/~/Server). The `secureConnectionListener`, if provided, is
automatically set as a listener for the `'secureConnection'` event.
The `ticketKeys` options is automatically shared between `node:cluster` module
workers.
The following illustrates a simple echo server:
```js
import tls from 'node:tls';
import fs from 'node:fs';
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// This is necessary only if using client certificate authentication.
requestCert: true,
// This is necessary only if the client uses a self-signed certificate.
ca: [ fs.readFileSync('client-cert.pem') ],
};
const server = tls.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');
});
```
The server can be tested by connecting to it using the example client from [connect](././node__tls.d.ts/~/connect).
v
DEFAULT_CIPHERS
The default value of the `ciphers` option of `createSecureContext()`.
It can be assigned any of the supported OpenSSL ciphers.
Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless
changed using CLI options using `--tls-default-ciphers`.
v
DEFAULT_ECDH_CURVE
The default curve name to use for ECDH key agreement in a tls server.
The default value is `'auto'`. See `createSecureContext()` for further
information.
v
DEFAULT_MAX_VERSION
The default value of the `maxVersion` option of `createSecureContext()`.
It can be assigned any of the supported TLS protocol versions,
`'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless
changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using
`--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options
are provided, the highest maximum is used.
v
DEFAULT_MIN_VERSION
The default value of the `minVersion` option of `createSecureContext()`.
It can be assigned any of the supported TLS protocol versions,
`'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless
changed using CLI options. Using `--tls-min-v1.0` sets the default to
`'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using
`--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options
are provided, the lowest minimum is used.
I
I
f
getCiphers
Returns an array with the names of the supported TLS ciphers. The names are
lower-case for historical reasons, but must be uppercased to be used in
the `ciphers` option of `[createSecureContext](././node__tls.d.ts/~/createSecureContext)`.
Not all supported ciphers are enabled by default. See
[Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v22.x/api/tls.html#modifying-the-default-tls-cipher-suite).
Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
TLSv1.2 and below.
```js
console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
```
I
I
I
I
v
rootCertificates
An immutable array of strings representing the root certificates (in PEM format)
from the bundled Mozilla CA store as supplied by the current Node.js version.
The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store
that is fixed at release time. It is identical on all supported platforms.
I
I
T
SecureVersion
No documentation available
c
Server
Accepts encrypted connections using TLS or SSL.
I
TlsOptions
No documentation available
c
TLSSocket
Performs transparent encryption of written data and all required TLS
negotiation.
Instances of `tls.TLSSocket` implement the duplex `Stream` interface.
Methods that return TLS connection metadata (e.g.TLSSocket.getPeerCertificate) will only return data while the
connection is open.
- addListener
- alpnProtocol
- authorizationError
- authorized
- disableRenegotiation
- emit
- enableTrace
- encrypted
- exportKeyingMaterial
- getCertificate
- getCipher
- getEphemeralKeyInfo
- getFinished
- getPeerCertificate
- getPeerFinished
- getPeerX509Certificate
- getProtocol
- getSession
- getSharedSigalgs
- getTLSTicket
- getX509Certificate
- isSessionReused
- on
- once
- prependListener
- prependOnceListener
- renegotiate
- setMaxSendFragment
I
f
createSecurePair
> [!WARNING] Deno compatibility
> This symbol is currently not supported.
Creates a new secure pair object with two streams, one of which reads and writes
the encrypted data and the other of which reads and writes the cleartext data.
Generally, the encrypted stream is piped to/from an incoming encrypted data
stream and the cleartext one is used as a replacement for the initial encrypted
stream.
`tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties.
Using `cleartext` has the same API as [TLSSocket](././node__tls.d.ts/~/TLSSocket).
The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code:
```js
pair = tls.createSecurePair(// ... );
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
```
can be replaced by:
```js
secureSocket = tls.TLSSocket(socket, options);
```
where `secureSocket` has the same API as `pair.cleartext`.
I
node__trace_events.d.ts
> [!WARNING] Deno compatibility > All exports are non-functional stubs. The `node:trace_events` module provides a mechanism to centralize tracing information generated by V8, Node.js core, and userspace code. Tracing can be enabled with the `--trace-event-categories` command-line flag or by using the `trace_events` module. The `--trace-event-categories` flag accepts a list of comma-separated category names. The available categories are: * `node`: An empty placeholder. * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) trace data. The [`async_hooks`](https://nodejs.org/docs/latest-v22.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. * `node.console`: Enables capture of `console.time()` and `console.count()` output. * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. * `node.dns.native`: Enables capture of trace data for DNS queries. * `node.net.native`: Enables capture of trace data for network. * `node.environment`: Enables capture of Node.js Environment milestones. * `node.fs.sync`: Enables capture of trace data for file system sync methods. * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. * `node.fs.async`: Enables capture of trace data for file system async methods. * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v22.x/api/perf_hooks.html) measurements. * `node.perf.usertiming`: Enables capture of only Performance API User Timing measures and marks. * `node.perf.timerify`: Enables capture of only Performance API timerify measurements. * `node.promises.rejections`: Enables capture of trace data tracking the number of unhandled Promise rejections and handled-after-rejections. * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. * `v8`: The [V8](https://nodejs.org/docs/latest-v22.x/api/v8.html) events are GC, compiling, and execution related. * `node.http`: Enables capture of trace data for http request / response. By default the `node`, `node.async_hooks`, and `v8` categories are enabled. ```bash node --trace-event-categories v8,node,node.async_hooks server.js ``` Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. ```bash node --trace-events-enabled node --trace-event-categories v8,node,node.async_hooks ``` Alternatively, trace events may be enabled using the `node:trace_events` module: ```js import trace_events from 'node:trace_events'; const tracing = trace_events.createTracing({ categories: ['node.perf'] }); tracing.enable(); // Enable trace event capture for the 'node.perf' category // do work tracing.disable(); // Disable trace event capture for the 'node.perf' category ``` Running Node.js with tracing enabled will produce log files that can be opened in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can be specified with `--trace-event-file-pattern` that accepts a template string that supports `${rotation}` and `${pid}`: ```bash node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js ``` To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers in your code, such as: ```js process.on('SIGINT', function onSigint() { console.info('Received SIGINT.'); process.exit(130); // Or applicable exit code depending on OS and signal }); ``` The tracing system uses the same time source as the one used by `process.hrtime()`. However the trace-event timestamps are expressed in microseconds, unlike `process.hrtime()` which returns nanoseconds. The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html#class-worker) threads.f
createTracing
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
Creates and returns a `Tracing` object for the given set of `categories`.
```js
import trace_events from 'node:trace_events';
const categories = ['node.perf', 'node.async_hooks'];
const tracing = trace_events.createTracing({ categories });
tracing.enable();
// do stuff
tracing.disable();
```
I
CreateTracingOptions
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
f
getEnabledCategories
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
Returns a comma-separated list of all currently-enabled trace event
categories. The current set of enabled trace event categories is determined
by the _union_ of all currently-enabled `Tracing` objects and any categories
enabled using the `--trace-event-categories` flag.
Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console.
```js
import trace_events from 'node:trace_events';
const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
const t2 = trace_events.createTracing({ categories: ['node.perf'] });
const t3 = trace_events.createTracing({ categories: ['v8'] });
t1.enable();
t2.enable();
console.log(trace_events.getEnabledCategories());
```
I
Tracing
> [!WARNING] Deno compatibility
> This symbol is a non-functional stub.
The `Tracing` object is used to enable or disable tracing for sets of
categories. Instances are created using the
`trace_events.createTracing()` method.
When created, the `Tracing` object is disabled. Calling the
`tracing.enable()` method adds the categories to the set of enabled trace
event categories. Calling `tracing.disable()` will remove the categories
from the set of enabled trace event categories.
node__tty.d.ts
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module directly. However, it can be accessed using: ```js import tty from 'node:tty'; ``` When Node.js detects that it is being run with a text terminal ("TTY") attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by default, be instances of `tty.WriteStream`. The preferred method of determining whether Node.js is being run within a TTY context is to check that the value of the `process.stdout.isTTY` property is `true`: ```console $ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat false ``` In most cases, there should be little to no reason for an application to manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes.T
Direction
-1 - to the left from cursor
0 - the entire line
1 - to the right from cursor
f
isatty
The `tty.isatty()` method returns `true` if the given `fd` is associated with
a TTY and `false` if it is not, including whenever `fd` is not a non-negative
integer.
c
ReadStream
Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js
process and there should be no reason to create additional instances.
c
WriteStream
Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there
should be no reason to create additional instances.
node__url.d.ts
The `node:url` module provides utilities for URL resolution and parsing. It can be accessed using: ```js import url from 'node:url'; ```f
domainToASCII
Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an
invalid domain, the empty string is returned.
It performs the inverse operation to [domainToUnicode](././node__url.d.ts/~/domainToUnicode).
```js
import url from 'node:url';
console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('ä¸æ–‡.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string
```
f
domainToUnicode
Returns the Unicode serialization of the `domain`. If `domain` is an invalid
domain, the empty string is returned.
It performs the inverse operation to [domainToASCII](././node__url.d.ts/~/domainToASCII).
```js
import url from 'node:url';
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints ä¸æ–‡.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
```
f
fileURLToPath
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
```js
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
new URL('file:///ä½ å¥½.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///ä½ å¥½.txt'); // Correct: /ä½ å¥½.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
```
I
f
format
The `url.format()` method returns a formatted URL string derived from `urlObject`.
```js
import url from 'node:url';
url.format({
protocol: 'https',
hostname: 'example.com',
pathname: '/some/path',
query: {
page: 1,
format: 'json',
},
});
// => 'https://example.com/some/path?page=1&format=json'
```
If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`.
The formatting process operates as follows:
* A new empty string `result` is created.
* If `urlObject.protocol` is a string, it is appended as-is to `result`.
* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown.
* For all string values of `urlObject.protocol` that _do not end_ with an ASCII
colon (`:`) character, the literal string `:` will be appended to `result`.
* If either of the following conditions is true, then the literal string `//` will be appended to `result`:
* `urlObject.slashes` property is true;
* `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`;
* If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string
and appended to `result` followed by the literal string `@`.
* If the `urlObject.host` property is `undefined` then:
* If the `urlObject.hostname` is a string, it is appended to `result`.
* Otherwise, if `urlObject.hostname` is not `undefined` and is not a string,
an `Error` is thrown.
* If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`:
* The literal string `:` is appended to `result`, and
* The value of `urlObject.port` is coerced to a string and appended to `result`.
* Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`.
* If the `urlObject.pathname` property is a string that is not an empty string:
* If the `urlObject.pathname` _does not start_ with an ASCII forward slash
(`/`), then the literal string `'/'` is appended to `result`.
* The value of `urlObject.pathname` is appended to `result`.
* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown.
* If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the
`querystring` module's `stringify()` method passing the value of `urlObject.query`.
* Otherwise, if `urlObject.search` is a string:
* If the value of `urlObject.search` _does not start_ with the ASCII question
mark (`?`) character, the literal string `?` is appended to `result`.
* The value of `urlObject.search` is appended to `result`.
* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown.
* If the `urlObject.hash` property is a string:
* If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`)
character, the literal string `#` is appended to `result`.
* The value of `urlObject.hash` is appended to `result`.
* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a
string, an `Error` is thrown.
* `result` is returned.
I
f
parse
No documentation available
f
pathToFileURL
This function ensures that `path` is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.
```js
import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)
```
I
f
resolve
The `url.resolve()` method resolves a target URL relative to a base URL in a
manner similar to that of a web browser resolving an anchor tag.
```js
import url from 'node:url';
url.resolve('/one/two/three', 'four'); // '/one/two/four'
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
```
To achieve the same result using the WHATWG URL API:
```js
function resolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` is a relative URL.
const { pathname, search, hash } = resolvedUrl;
return pathname + search + hash;
}
return resolvedUrl.toString();
}
resolve('/one/two/three', 'four'); // '/one/two/four'
resolve('http://example.com/', '/one'); // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two'
```
c
I
v
URL
Browser-compatible `URL` class, implemented by following the WHATWG URL
Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself.
The `URL` class is also available on the global object.
In accordance with browser conventions, all properties of `URL` objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself. Thus, unlike `legacy urlObject`s,
using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still
return `true`.
I
I
c
I
v
URLSearchParams
The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the
four following constructors.
The `URLSearchParams` class is also available on the global object.
The WHATWG `URLSearchParams` interface and the `querystring` module have
similar purpose, but the purpose of the `querystring` module is more
general, as it allows the customization of delimiter characters (`&` and `=`).
On the other hand, this API is designed purely for URL query strings.
```js
const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123
myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Prints https://example.org/?abc=123&abc=xyz
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// Prints https://example.org/?a=b
const newSearchParams = new URLSearchParams(myURL.searchParams);
// The above is equivalent to
// const newSearchParams = new URLSearchParams(myURL.search);
newSearchParams.append('a', 'c');
console.log(myURL.href);
// Prints https://example.org/?a=b
console.log(newSearchParams.toString());
// Prints a=b&a=c
// newSearchParams.toString() is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
```
f
urlToHttpOptions
This utility function converts a URL object into an ordinary options object as
expected by the `http.request()` and `https.request()` APIs.
```js
import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
console.log(urlToHttpOptions(myURL));
/*
{
protocol: 'https:',
hostname: 'xn--g6w251d',
hash: '#foo',
search: '?abc',
pathname: '/',
path: '/?abc',
href: 'https://a:b@xn--g6w251d/?abc#foo',
auth: 'a:b'
}
```
I
I
f
isAnyArrayBuffer
Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or
[`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance.
See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`.
```js
util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
```
f
isArgumentsObject
Returns `true` if the value is an `arguments` object.
```js
function foo() {
util.types.isArgumentsObject(arguments); // Returns true
}
```
f
isArrayBuffer
Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance.
This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is
desirable to test for both; See `util.types.isAnyArrayBuffer()` for that.
```js
util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
```
f
isArrayBufferView
Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed
array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to
[`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
```js
util.types.isArrayBufferView(new Int8Array()); // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true
util.types.isArrayBufferView(new ArrayBuffer()); // false
```
f
isAsyncFunction
Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
util.types.isAsyncFunction(function foo() {}); // Returns false
util.types.isAsyncFunction(async function foo() {}); // Returns true
```
f
isBigInt64Array
Returns `true` if the value is a `BigInt64Array` instance.
```js
util.types.isBigInt64Array(new BigInt64Array()); // Returns true
util.types.isBigInt64Array(new BigUint64Array()); // Returns false
```
f
isBigUint64Array
Returns `true` if the value is a `BigUint64Array` instance.
```js
util.types.isBigUint64Array(new BigInt64Array()); // Returns false
util.types.isBigUint64Array(new BigUint64Array()); // Returns true
```
f
isBooleanObject
Returns `true` if the value is a boolean object, e.g. created
by `new Boolean()`.
```js
util.types.isBooleanObject(false); // Returns false
util.types.isBooleanObject(true); // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true)); // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true)); // Returns false
```
f
isBoxedPrimitive
Returns `true` if the value is any boxed primitive object, e.g. created
by `new Boolean()`, `new String()` or `Object(Symbol())`.
For example:
```js
util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
```
f
isCryptoKey
Returns `true` if `value` is a `CryptoKey`, `false` otherwise.
f
isDataView
Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance.
```js
const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab)); // Returns true
util.types.isDataView(new Float64Array()); // Returns false
```
See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
f
isDate
Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance.
```js
util.types.isDate(new Date()); // Returns true
```
f
isExternal
Returns `true` if the value is a native `External` value.
A native `External` value is a special type of object that contains a
raw C++ pointer (`void*`) for access from native code, and has no other
properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype.
```c
#include
#include
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
int* raw = (int*) malloc(1024);
napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
if (status != napi_ok) {
napi_throw_error(env, NULL, "napi_create_external failed");
return NULL;
}
return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
```
```js
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false
```
For further information on `napi_create_external`, refer to `napi_create_external()`.
f
isFloat32Array
Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance.
```js
util.types.isFloat32Array(new ArrayBuffer()); // Returns false
util.types.isFloat32Array(new Float32Array()); // Returns true
util.types.isFloat32Array(new Float64Array()); // Returns false
```
f
isFloat64Array
Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance.
```js
util.types.isFloat64Array(new ArrayBuffer()); // Returns false
util.types.isFloat64Array(new Uint8Array()); // Returns false
util.types.isFloat64Array(new Float64Array()); // Returns true
```
f
isGeneratorFunction
Returns `true` if the value is a generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
util.types.isGeneratorFunction(function foo() {}); // Returns false
util.types.isGeneratorFunction(function* foo() {}); // Returns true
```
f
isGeneratorObject
Returns `true` if the value is a generator object as returned from a
built-in generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator); // Returns true
```
f
isInt16Array
Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance.
```js
util.types.isInt16Array(new ArrayBuffer()); // Returns false
util.types.isInt16Array(new Int16Array()); // Returns true
util.types.isInt16Array(new Float64Array()); // Returns false
```
f
isInt32Array
Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance.
```js
util.types.isInt32Array(new ArrayBuffer()); // Returns false
util.types.isInt32Array(new Int32Array()); // Returns true
util.types.isInt32Array(new Float64Array()); // Returns false
```
f
isInt8Array
Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance.
```js
util.types.isInt8Array(new ArrayBuffer()); // Returns false
util.types.isInt8Array(new Int8Array()); // Returns true
util.types.isInt8Array(new Float64Array()); // Returns false
```
f
isKeyObject
Returns `true` if `value` is a `KeyObject`, `false` otherwise.
f
isMap
Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
```js
util.types.isMap(new Map()); // Returns true
```
f
isMapIterator
Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
```js
const map = new Map();
util.types.isMapIterator(map.keys()); // Returns true
util.types.isMapIterator(map.values()); // Returns true
util.types.isMapIterator(map.entries()); // Returns true
util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
```
f
isModuleNamespaceObject
Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects).
```js
import * as ns from './a.js';
util.types.isModuleNamespaceObject(ns); // Returns true
```
f
isNativeError
Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects).
```js
console.log(util.types.isNativeError(new Error())); // true
console.log(util.types.isNativeError(new TypeError())); // true
console.log(util.types.isNativeError(new RangeError())); // true
```
Subclasses of the native error types are also native errors:
```js
class MyError extends Error {}
console.log(util.types.isNativeError(new MyError())); // true
```
A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors
which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors:
```js
import vm from 'node:vm';
const context = vm.createContext({});
const myError = vm.runInContext('new Error()', context);
console.log(util.types.isNativeError(myError)); // true
console.log(myError instanceof Error); // false
```
Conversely, `isNativeError()` returns `false` for all objects which were not
returned by the constructor of a native error. That includes values
which are `instanceof` native errors:
```js
const myError = { __proto__: Error.prototype };
console.log(util.types.isNativeError(myError)); // false
console.log(myError instanceof Error); // true
```
f
isNumberObject
Returns `true` if the value is a number object, e.g. created
by `new Number()`.
```js
util.types.isNumberObject(0); // Returns false
util.types.isNumberObject(new Number(0)); // Returns true
```
f
isPromise
Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
```js
util.types.isPromise(Promise.resolve(42)); // Returns true
```
f
isProxy
Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance.
```js
const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target); // Returns false
util.types.isProxy(proxy); // Returns true
```
f
isRegExp
Returns `true` if the value is a regular expression object.
```js
util.types.isRegExp(/abc/); // Returns true
util.types.isRegExp(new RegExp('abc')); // Returns true
```
f
isSet
Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
```js
util.types.isSet(new Set()); // Returns true
```
f
isSetIterator
Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
```js
const set = new Set();
util.types.isSetIterator(set.keys()); // Returns true
util.types.isSetIterator(set.values()); // Returns true
util.types.isSetIterator(set.entries()); // Returns true
util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
```
f
isStringObject
Returns `true` if the value is a string object, e.g. created
by `new String()`.
```js
util.types.isStringObject('foo'); // Returns false
util.types.isStringObject(new String('foo')); // Returns true
```
f
isSymbolObject
Returns `true` if the value is a symbol object, created
by calling `Object()` on a `Symbol` primitive.
```js
const symbol = Symbol('foo');
util.types.isSymbolObject(symbol); // Returns false
util.types.isSymbolObject(Object(symbol)); // Returns true
```
f
isTypedArray
Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance.
```js
util.types.isTypedArray(new ArrayBuffer()); // Returns false
util.types.isTypedArray(new Uint8Array()); // Returns true
util.types.isTypedArray(new Float64Array()); // Returns true
```
See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
f
isUint16Array
Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance.
```js
util.types.isUint16Array(new ArrayBuffer()); // Returns false
util.types.isUint16Array(new Uint16Array()); // Returns true
util.types.isUint16Array(new Float64Array()); // Returns false
```
f
isUint32Array
Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance.
```js
util.types.isUint32Array(new ArrayBuffer()); // Returns false
util.types.isUint32Array(new Uint32Array()); // Returns true
util.types.isUint32Array(new Float64Array()); // Returns false
```
f
isUint8Array
Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance.
```js
util.types.isUint8Array(new ArrayBuffer()); // Returns false
util.types.isUint8Array(new Uint8Array()); // Returns true
util.types.isUint8Array(new Float64Array()); // Returns false
```
f
isUint8ClampedArray
Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance.
```js
util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
util.types.isUint8ClampedArray(new Float64Array()); // Returns false
```
f
isWeakMap
Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance.
```js
util.types.isWeakMap(new WeakMap()); // Returns true
```
f
isWeakSet
Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance.
```js
util.types.isWeakSet(new WeakSet()); // Returns true
```
node__util.d.ts
The `node:util` module supports the needs of Node.js internal APIs. Many of the utilities are useful for application and module developers as well. To access it: ```js import util from 'node:util'; ```f
aborted
Listens to abort event on the provided `signal` and
returns a promise that is fulfilled when the `signal` is
aborted. If the passed `resource` is garbage collected before the `signal` is
aborted, the returned promise shall remain pending indefinitely.
```js
import { aborted } from 'node:util';
const dependent = obtainSomethingAbortable();
aborted(dependent.signal, dependent).then(() => {
// Do something when dependent is aborted.
});
dependent.on('event', () => {
dependent.abort();
});
```
T
BackgroundColors
No documentation available
f
callbackify
Takes an `async` function (or a function that returns a `Promise`) and returns a
function following the error-first callback style, i.e. taking
an `(err, value) => ...` callback as the last argument. In the callback, the
first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value.
```js
import util from 'node:util';
async function fn() {
return 'hello world';
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
if (err) throw err;
console.log(ret);
});
```
Will print:
```text
hello world
```
The callback is executed asynchronously, and will have a limited stack trace.
If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit.
Since `null` has a special meaning as the first argument to a callback, if a
wrapped function rejects a `Promise` with a falsy value as a reason, the value
is wrapped in an `Error` with the original value stored in a field named `reason`.
```js
function fn() {
return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);
callbackFunction((err, ret) => {
// When the Promise was rejected with `null` it is wrapped with an Error and
// the original value is stored in `reason`.
err && Object.hasOwn(err, 'reason') && err.reason === null; // true
});
```
T
CustomInspectFunction
No documentation available
T
CustomPromisify
No documentation available
I
I
CustomPromisifySymbol
No documentation available
v
debug
No documentation available
f
debuglog
The `util.debuglog()` method is used to create a function that conditionally
writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that
environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op.
```js
import util from 'node:util';
const debuglog = util.debuglog('foo');
debuglog('hello from foo [%d]', 123);
```
If this program is run with `NODE_DEBUG=foo` in the environment, then
it will output something like:
```console
FOO 3245: hello from foo [123]
```
where `3245` is the process id. If it is not run with that
environment variable set, then it will not print anything.
The `section` supports wildcard also:
```js
import util from 'node:util';
const debuglog = util.debuglog('foo-bar');
debuglog('hi there, it\'s foo-bar [%d]', 2333);
```
if it is run with `NODE_DEBUG=foo*` in the environment, then it will output
something like:
```console
FOO-BAR 3257: hi there, it's foo-bar [2333]
```
Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`.
The optional `callback` argument can be used to replace the logging function
with a different function that doesn't have any initialization or
unnecessary wrapping.
```js
import util from 'node:util';
let debuglog = util.debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
debuglog = debug;
});
```
I
T
DebugLoggerFunction
No documentation available
f
deprecate
The `util.deprecate()` method wraps `fn` (which may be a function or class) in
such a way that it is marked as deprecated.
```js
import util from 'node:util';
exports.obsoleteFunction = util.deprecate(() => {
// Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
```
When called, `util.deprecate()` will return a function that will emit a `DeprecationWarning` using the `'warning'` event. The warning will
be emitted and printed to `stderr` the first time the returned function is
called. After the warning is emitted, the wrapped function is called without
emitting a warning.
If the same optional `code` is supplied in multiple calls to `util.deprecate()`,
the warning will be emitted only once for that `code`.
```js
import util from 'node:util';
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
```
If either the `--no-deprecation` or `--no-warnings` command-line flags are
used, or if the `process.noDeprecation` property is set to `true`_prior_ to
the first deprecation warning, the `util.deprecate()` method does nothing.
If the `--trace-deprecation` or `--trace-warnings` command-line flags are set,
or the `process.traceDeprecation` property is set to `true`, a warning and a
stack trace are printed to `stderr` the first time the deprecated function is
called.
If the `--throw-deprecation` command-line flag is set, or the `process.throwDeprecation` property is set to `true`, then an exception will be
thrown when the deprecated function is called.
The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`.
I
T
ExtractOptionValue
No documentation available
T
ForegroundColors
No documentation available
f
format
The `util.format()` method returns a formatted string using the first argument
as a `printf`-like format string which can contain zero or more format
specifiers. Each specifier is replaced with the converted value from the
corresponding argument. Supported specifiers are:
If a specifier does not have a corresponding argument, it is not replaced:
```js
util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
```
Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`.
If there are more arguments passed to the `util.format()` method than the
number of specifiers, the extra arguments are concatenated to the returned
string, separated by spaces:
```js
util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'
```
If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces:
```js
util.format(1, 2, 3);
// Returns: '1 2 3'
```
If only one argument is passed to `util.format()`, it is returned as it is
without any formatting:
```js
util.format('%% %s');
// Returns: '%% %s'
```
`util.format()` is a synchronous method that is intended as a debugging tool.
Some input values can have a significant performance overhead that can block the
event loop. Use this function with care and never in a hot code path.
f
formatWithOptions
This function is identical to [format](././node__util.d.ts/~/format), except in that it takes
an `inspectOptions` argument which specifies options that are passed along to [inspect](././node__util.d.ts/~/inspect).
```js
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
```
f
getSystemErrorMap
> [!WARNING] Deno compatibility
> This symbol is currently not supported.
Returns a Map of all system error codes available from the Node.js API.
The mapping between error codes and error names is platform-dependent.
See `Common System Errors` for the names of common errors.
```js
fs.access('file/that/does/not/exist', (err) => {
const errorMap = util.getSystemErrorMap();
const name = errorMap.get(err.errno);
console.error(name); // ENOENT
});
```
f
getSystemErrorName
Returns the string name for a numeric error code that comes from a Node.js API.
The mapping between error codes and error names is platform-dependent.
See `Common System Errors` for the names of common errors.
```js
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
```
T
IfDefaultsFalse
No documentation available
T
IfDefaultsTrue
No documentation available
f
inherits
Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and `extends` keywords to get language level inheritance support. Also note
that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179).
Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The
prototype of `constructor` will be set to a new object created from `superConstructor`.
This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`.
As an additional convenience, `superConstructor` will be accessible
through the `constructor.super_` property.
```js
import util from 'node:util';
import EventEmitter from 'node:events';
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
};
const stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"
```
ES6 example using `class` and `extends`:
```js
import EventEmitter from 'node:events';
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
```
f
N
inspect
The `util.inspect()` method returns a string representation of `object` that is
intended for debugging. The output of `util.inspect` may change at any time
and should not be depended upon programmatically. Additional `options` may be
passed that alter the result. `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make
an identifiable tag for an inspected value.
```js
class Foo {
get [Symbol.toStringTag]() {
return 'bar';
}
}
class Bar {}
const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });
util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz); // '[foo] {}'
```
Circular references point to their anchor by using a reference index:
```js
import { inspect } from 'node:util';
const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;
console.log(inspect(obj));
// {
// a: [ [Circular *1] ],
// b: { inner: [Circular *2], obj: [Circular *1] }
// }
```
The following example inspects all properties of the `util` object:
```js
import util from 'node:util';
console.log(util.inspect(util, { showHidden: true, depth: null }));
```
The following example highlights the effect of the `compact` option:
```js
import util from 'node:util';
const o = {
a: [1, 2, [[
'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' +
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
// { a:
// [ 1,
// 2,
// [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line
// 'test',
// 'foo' ] ],
// 4 ],
// b: Map(2) { 'za' => 1, 'zb' => 'test' } }
// Setting `compact` to false or an integer creates more reader friendly output.
console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));
// {
// a: [
// 1,
// 2,
// [
// [
// 'Lorem ipsum dolor sit amet,\n' +
// 'consectetur adipiscing elit, sed do eiusmod \n' +
// 'tempor incididunt ut labore et dolore magna aliqua.',
// 'test',
// 'foo'
// ]
// ],
// 4
// ],
// b: Map(2) {
// 'za' => 1,
// 'zb' => 'test'
// }
// }
// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a
// single line.
```
The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and
[`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be
inspected. If there are more entries than `maxArrayLength`, there is no
guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may
result in different output. Furthermore, entries
with no remaining strong references may be garbage collected at any time.
```js
import { inspect } from 'node:util';
const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);
console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
```
The `sorted` option ensures that an object's property insertion order does not
impact the result of `util.inspect()`.
```js
import { inspect } from 'node:util';
import assert from 'node:assert';
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
inspect(o2, { sorted: true }),
);
```
The `numericSeparator` option adds an underscore every three digits to all
numbers.
```js
import { inspect } from 'node:util';
const thousand = 1_000;
const million = 1_000_000;
const bigNumber = 123_456_789n;
const bigDecimal = 1_234.123_45;
console.log(inspect(thousand, { numericSeparator: true }));
// 1_000
console.log(inspect(million, { numericSeparator: true }));
// 1_000_000
console.log(inspect(bigNumber, { numericSeparator: true }));
// 123_456_789n
console.log(inspect(bigDecimal, { numericSeparator: true }));
// 1_234.123_45
```
`util.inspect()` is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MiB. Inputs that result in longer output will
be truncated.
v
inspect.colors
No documentation available
v
inspect.custom
That can be used to declare custom inspect functions.
v
inspect.defaultOptions
No documentation available
v
inspect.replDefaults
Allows changing inspect settings from the repl.
v
inspect.styles
No documentation available
I
I
f
isDeepStrictEqual
Returns `true` if there is deep strict equality between `val1` and `val2`.
Otherwise, returns `false`.
See `assert.deepStrictEqual()` for more information about deep strict
equality.
c
c
MIMEType
> [!WARNING] Deno compatibility
> This symbol is currently not supported.
An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/).
In accordance with browser conventions, all properties of `MIMEType` objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself.
A MIME string is a structured string containing multiple meaningful
components. When parsed, a `MIMEType` object is returned containing
properties for each of these components.
T
Modifiers
No documentation available
T
OptionToken
No documentation available
f
parseArgs
Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
```js
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
```
I
I
I
ParseArgsOptionsConfig
No documentation available
T
ParsedOptionToken
No documentation available
T
ParsedPositionals
No documentation available
T
ParsedPositionalToken
No documentation available
T
ParsedResults
No documentation available
T
ParsedTokens
No documentation available
T
ParsedValues
No documentation available
f
parseEnv
Stability: 1.1 - Active development
Given an example `.env` file:
```js
import { parseEnv } from 'node:util';
parseEnv('HELLO=world\nHELLO=oh my\n');
// Returns: { HELLO: 'oh my' }
```
T
PreciseParsedResults
No documentation available
T
PreciseTokenForOptions
No documentation available
f
N
promisify
Takes a function following the common error-first callback style, i.e. taking
an `(err, value) => ...` callback as the last argument, and returns a version
that returns promises.
```js
import util from 'node:util';
import fs from 'node:fs';
const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
// Do something with `stats`
}).catch((error) => {
// Handle the error.
});
```
Or, equivalently using `async function`s:
```js
import util from 'node:util';
import fs from 'node:fs';
const stat = util.promisify(fs.stat);
async function callStat() {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
}
callStat();
```
If there is an `original[util.promisify.custom]` property present, `promisify` will return its value, see `Custom promisified functions`.
`promisify()` assumes that `original` is a function taking a callback as its
final argument in all cases. If `original` is not a function, `promisify()` will throw an error. If `original` is a function but its last argument is not
an error-first callback, it will still be passed an error-first
callback as its last argument.
Using `promisify()` on class methods or other methods that use `this` may not
work as expected unless handled specially:
```js
import util from 'node:util';
class Foo {
constructor() {
this.a = 42;
}
bar(callback) {
callback(null, this.a);
}
}
const foo = new Foo();
const naiveBar = util.promisify(foo.bar);
// TypeError: Cannot read property 'a' of undefined
// naiveBar().then(a => console.log(a));
naiveBar.call(foo).then((a) => console.log(a)); // '42'
const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
```
v
promisify.custom
That can be used to declare custom promisified variants of functions.
f
stripVTControlCharacters
Returns `str` with any ANSI escape codes removed.
```js
console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
// Prints "value"
```
T
Style
No documentation available
f
styleText
Stability: 1.1 - Active development
This function returns a formatted text considering the `format` passed.
```js
import { styleText } from 'node:util';
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
```
`util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both:
```js
console.log(
util.styleText(['underline', 'italic'], 'My italic underlined message'),
);
```
When passing an array of formats, the order of the format applied is left to right so the following style
might overwrite the previous one.
```js
console.log(
util.styleText(['red', 'green'], 'text'), // green
);
```
The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v22.x/api/util.html#modifiers).
c
v
TextDecoder
An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API.
```js
const decoder = new TextDecoder();
const u8arr = new Uint8Array([72, 101, 108, 108, 111]);
console.log(decoder.decode(u8arr)); // Hello
```
c
v
TextEncoder
An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
instances of `TextEncoder` only support UTF-8 encoding.
```js
const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
```
The `TextEncoder` class is also available on the global object.
T
Token
No documentation available
T
TokenForOptions
No documentation available
f
toUSVString
Returns the `string` after replacing any surrogate code points
(or equivalently, any unpaired surrogate code units) with the
Unicode "replacement character" U+FFFD.
f
transferableAbortController
> [!WARNING] Deno compatibility
> This symbol is currently not supported.
Creates and returns an `AbortController` instance whose `AbortSignal` is marked
as transferable and can be used with `structuredClone()` or `postMessage()`.
f
transferableAbortSignal
> [!WARNING] Deno compatibility
> This symbol is currently not supported.
Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`.
```js
const signal = transferableAbortSignal(AbortSignal.timeout(100));
const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
```
N
types
No documentation available
f
types.isAnyArrayBuffer
Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or
[`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance.
See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`.
```js
util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
```
f
types.isArgumentsObject
Returns `true` if the value is an `arguments` object.
```js
function foo() {
util.types.isArgumentsObject(arguments); // Returns true
}
```
f
types.isArrayBuffer
Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance.
This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is
desirable to test for both; See `util.types.isAnyArrayBuffer()` for that.
```js
util.types.isArrayBuffer(new ArrayBuffer()); // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
```
f
types.isArrayBufferView
Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed
array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to
[`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
```js
util.types.isArrayBufferView(new Int8Array()); // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true
util.types.isArrayBufferView(new ArrayBuffer()); // false
```
f
types.isAsyncFunction
Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
util.types.isAsyncFunction(function foo() {}); // Returns false
util.types.isAsyncFunction(async function foo() {}); // Returns true
```
f
types.isBigInt64Array
Returns `true` if the value is a `BigInt64Array` instance.
```js
util.types.isBigInt64Array(new BigInt64Array()); // Returns true
util.types.isBigInt64Array(new BigUint64Array()); // Returns false
```
f
types.isBigUint64Array
Returns `true` if the value is a `BigUint64Array` instance.
```js
util.types.isBigUint64Array(new BigInt64Array()); // Returns false
util.types.isBigUint64Array(new BigUint64Array()); // Returns true
```
f
types.isBooleanObject
Returns `true` if the value is a boolean object, e.g. created
by `new Boolean()`.
```js
util.types.isBooleanObject(false); // Returns false
util.types.isBooleanObject(true); // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true)); // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true)); // Returns false
```
f
types.isBoxedPrimitive
Returns `true` if the value is any boxed primitive object, e.g. created
by `new Boolean()`, `new String()` or `Object(Symbol())`.
For example:
```js
util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
```
f
types.isCryptoKey
Returns `true` if `value` is a `CryptoKey`, `false` otherwise.
f
types.isDataView
Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance.
```js
const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab)); // Returns true
util.types.isDataView(new Float64Array()); // Returns false
```
See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
f
types.isDate
Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance.
```js
util.types.isDate(new Date()); // Returns true
```
f
types.isExternal
Returns `true` if the value is a native `External` value.
A native `External` value is a special type of object that contains a
raw C++ pointer (`void*`) for access from native code, and has no other
properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype.
```c
#include
#include
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
int* raw = (int*) malloc(1024);
napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
if (status != napi_ok) {
napi_throw_error(env, NULL, "napi_create_external failed");
return NULL;
}
return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
```
```js
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false
```
For further information on `napi_create_external`, refer to `napi_create_external()`.
f
types.isFloat32Array
Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance.
```js
util.types.isFloat32Array(new ArrayBuffer()); // Returns false
util.types.isFloat32Array(new Float32Array()); // Returns true
util.types.isFloat32Array(new Float64Array()); // Returns false
```
f
types.isFloat64Array
Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance.
```js
util.types.isFloat64Array(new ArrayBuffer()); // Returns false
util.types.isFloat64Array(new Uint8Array()); // Returns false
util.types.isFloat64Array(new Float64Array()); // Returns true
```
f
types.isGeneratorFunction
Returns `true` if the value is a generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
util.types.isGeneratorFunction(function foo() {}); // Returns false
util.types.isGeneratorFunction(function* foo() {}); // Returns true
```
f
types.isGeneratorObject
Returns `true` if the value is a generator object as returned from a
built-in generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.
```js
function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator); // Returns true
```
f
types.isInt16Array
Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance.
```js
util.types.isInt16Array(new ArrayBuffer()); // Returns false
util.types.isInt16Array(new Int16Array()); // Returns true
util.types.isInt16Array(new Float64Array()); // Returns false
```
f
types.isInt32Array
Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance.
```js
util.types.isInt32Array(new ArrayBuffer()); // Returns false
util.types.isInt32Array(new Int32Array()); // Returns true
util.types.isInt32Array(new Float64Array()); // Returns false
```
f
types.isInt8Array
Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance.
```js
util.types.isInt8Array(new ArrayBuffer()); // Returns false
util.types.isInt8Array(new Int8Array()); // Returns true
util.types.isInt8Array(new Float64Array()); // Returns false
```
f
types.isKeyObject
Returns `true` if `value` is a `KeyObject`, `false` otherwise.
f
types.isMap
Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
```js
util.types.isMap(new Map()); // Returns true
```
f
types.isMapIterator
Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance.
```js
const map = new Map();
util.types.isMapIterator(map.keys()); // Returns true
util.types.isMapIterator(map.values()); // Returns true
util.types.isMapIterator(map.entries()); // Returns true
util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
```
f
types.isModuleNamespaceObject
Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects).
```js
import * as ns from './a.js';
util.types.isModuleNamespaceObject(ns); // Returns true
```
f
types.isNativeError
Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects).
```js
console.log(util.types.isNativeError(new Error())); // true
console.log(util.types.isNativeError(new TypeError())); // true
console.log(util.types.isNativeError(new RangeError())); // true
```
Subclasses of the native error types are also native errors:
```js
class MyError extends Error {}
console.log(util.types.isNativeError(new MyError())); // true
```
A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors
which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors:
```js
import vm from 'node:vm';
const context = vm.createContext({});
const myError = vm.runInContext('new Error()', context);
console.log(util.types.isNativeError(myError)); // true
console.log(myError instanceof Error); // false
```
Conversely, `isNativeError()` returns `false` for all objects which were not
returned by the constructor of a native error. That includes values
which are `instanceof` native errors:
```js
const myError = { __proto__: Error.prototype };
console.log(util.types.isNativeError(myError)); // false
console.log(myError instanceof Error); // true
```
f
types.isNumberObject
Returns `true` if the value is a number object, e.g. created
by `new Number()`.
```js
util.types.isNumberObject(0); // Returns false
util.types.isNumberObject(new Number(0)); // Returns true
```
f
types.isPromise
Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
```js
util.types.isPromise(Promise.resolve(42)); // Returns true
```
f
types.isProxy
Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance.
```js
const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target); // Returns false
util.types.isProxy(proxy); // Returns true
```
f
types.isRegExp
Returns `true` if the value is a regular expression object.
```js
util.types.isRegExp(/abc/); // Returns true
util.types.isRegExp(new RegExp('abc')); // Returns true
```
f
types.isSet
Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
```js
util.types.isSet(new Set()); // Returns true
```
f
types.isSetIterator
Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance.
```js
const set = new Set();
util.types.isSetIterator(set.keys()); // Returns true
util.types.isSetIterator(set.values()); // Returns true
util.types.isSetIterator(set.entries()); // Returns true
util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
```
f
types.isStringObject
Returns `true` if the value is a string object, e.g. created
by `new String()`.
```js
util.types.isStringObject('foo'); // Returns false
util.types.isStringObject(new String('foo')); // Returns true
```
f
types.isSymbolObject
Returns `true` if the value is a symbol object, created
by calling `Object()` on a `Symbol` primitive.
```js
const symbol = Symbol('foo');
util.types.isSymbolObject(symbol); // Returns false
util.types.isSymbolObject(Object(symbol)); // Returns true
```
f
types.isTypedArray
Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance.
```js
util.types.isTypedArray(new ArrayBuffer()); // Returns false
util.types.isTypedArray(new Uint8Array()); // Returns true
util.types.isTypedArray(new Float64Array()); // Returns true
```
See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView).
f
types.isUint16Array
Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance.
```js
util.types.isUint16Array(new ArrayBuffer()); // Returns false
util.types.isUint16Array(new Uint16Array()); // Returns true
util.types.isUint16Array(new Float64Array()); // Returns false
```
f
types.isUint32Array
Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance.
```js
util.types.isUint32Array(new ArrayBuffer()); // Returns false
util.types.isUint32Array(new Uint32Array()); // Returns true
util.types.isUint32Array(new Float64Array()); // Returns false
```
f
types.isUint8Array
Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance.
```js
util.types.isUint8Array(new ArrayBuffer()); // Returns false
util.types.isUint8Array(new Uint8Array()); // Returns true
util.types.isUint8Array(new Float64Array()); // Returns false
```
f
types.isUint8ClampedArray
Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance.
```js
util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true
util.types.isUint8ClampedArray(new Float64Array()); // Returns false
```
f
types.isWeakMap
Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance.
```js
util.types.isWeakMap(new WeakMap()); // Returns true
```
f
types.isWeakSet
Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance.
```js
util.types.isWeakSet(new WeakSet()); // Returns true
```
f
isArray
Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray).
Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
```
f
isBoolean
Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isBoolean(1);
// Returns: false
util.isBoolean(0);
// Returns: false
util.isBoolean(false);
// Returns: true
```
f
isBuffer
Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isBuffer({ length: 0 });
// Returns: false
util.isBuffer([]);
// Returns: false
util.isBuffer(Buffer.from('hello world'));
// Returns: true
```
f
isDate
Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isDate(new Date());
// Returns: true
util.isDate(Date());
// false (without 'new' returns a String)
util.isDate({});
// Returns: false
```
f
isError
Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isError(new Error());
// Returns: true
util.isError(new TypeError());
// Returns: true
util.isError({ name: 'Error', message: 'an error occurred' });
// Returns: false
```
This method relies on `Object.prototype.toString()` behavior. It is
possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`.
```js
import util from 'node:util';
const obj = { name: 'Error', message: 'an error occurred' };
util.isError(obj);
// Returns: false
obj[Symbol.toStringTag] = 'Error';
util.isError(obj);
// Returns: true
```
f
isFunction
Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`.
```js
import util from 'node:util';
function Foo() {}
const Bar = () => {};
util.isFunction({});
// Returns: false
util.isFunction(Foo);
// Returns: true
util.isFunction(Bar);
// Returns: true
```
f
isNull
Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`.
```js
import util from 'node:util';
util.isNull(0);
// Returns: false
util.isNull(undefined);
// Returns: false
util.isNull(null);
// Returns: true
```
f
isNullOrUndefined
Returns `true` if the given `object` is `null` or `undefined`. Otherwise,
returns `false`.
```js
import util from 'node:util';
util.isNullOrUndefined(0);
// Returns: false
util.isNullOrUndefined(undefined);
// Returns: true
util.isNullOrUndefined(null);
// Returns: true
```
f
isNumber
Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isNumber(false);
// Returns: false
util.isNumber(Infinity);
// Returns: true
util.isNumber(0);
// Returns: true
util.isNumber(NaN);
// Returns: true
```
f
isObject
Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript).
Otherwise, returns `false`.
```js
import util from 'node:util';
util.isObject(5);
// Returns: false
util.isObject(null);
// Returns: false
util.isObject({});
// Returns: true
util.isObject(() => {});
// Returns: false
```
f
isPrimitive
Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`.
```js
import util from 'node:util';
util.isPrimitive(5);
// Returns: true
util.isPrimitive('foo');
// Returns: true
util.isPrimitive(false);
// Returns: true
util.isPrimitive(null);
// Returns: true
util.isPrimitive(undefined);
// Returns: true
util.isPrimitive({});
// Returns: false
util.isPrimitive(() => {});
// Returns: false
util.isPrimitive(/^$/);
// Returns: false
util.isPrimitive(new Date());
// Returns: false
```
f
isRegExp
Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isRegExp(/some regexp/);
// Returns: true
util.isRegExp(new RegExp('another regexp'));
// Returns: true
util.isRegExp({});
// Returns: false
```
f
isString
Returns `true` if the given `object` is a `string`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isString('');
// Returns: true
util.isString('foo');
// Returns: true
util.isString(String('foo'));
// Returns: true
util.isString(5);
// Returns: false
```
f
isSymbol
Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`.
```js
import util from 'node:util';
util.isSymbol(5);
// Returns: false
util.isSymbol('foo');
// Returns: false
util.isSymbol(Symbol('foo'));
// Returns: true
```
f
isUndefined
Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`.
```js
import util from 'node:util';
const foo = undefined;
util.isUndefined(5);
// Returns: false
util.isUndefined(foo);
// Returns: true
util.isUndefined(null);
// Returns: false
```
f
log
The `util.log()` method prints the given `string` to `stdout` with an included
timestamp.
```js
import util from 'node:util';
util.log('Timestamped message.');
```
node__v8.d.ts
> [!WARNING] Deno compatibility > `cachedDataVersionTag` and `getHeapStatistics`, `serialize` and `deserialize` are supported. > `setFlagsFromStrings` is a noop. > Other APIs are not supported and will throw and error. > The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: ```js import v8 from 'node:v8'; ```I
After
Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await.
I
Before
Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming.
The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise.
The before callback may be called many times in the case where many continuations have been made from the same promise.
f
cachedDataVersionTag
Returns an integer representing a version tag derived from the V8 version,
command-line flags, and detected CPU features. This is useful for determining
whether a `vm.Script` `cachedData` buffer is compatible with this instance
of V8.
```js
console.log(v8.cachedDataVersionTag()); // 3947234607
// The value returned by v8.cachedDataVersionTag() is derived from the V8
// version, command-line flags, and detected CPU features. Test that the value
// does indeed update when flags are toggled.
v8.setFlagsFromString('--allow_natives_syntax');
console.log(v8.cachedDataVersionTag()); // 183726201
```
c
DefaultDeserializer
A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`.
c
DefaultSerializer
A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only
stores the part of their underlying `ArrayBuffer`s that they are referring to.
f
deserialize
Uses a `DefaultDeserializer` with default options to read a JS value
from a buffer.
c
T
DoesZapCodeSpaceFlag
No documentation available
c
I
f
getHeapCodeStatistics
Get statistics about code and its metadata in the heap, see
V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the
following properties:
```js
{
code_and_metadata_size: 212208,
bytecode_and_metadata_size: 161368,
external_script_source_size: 1410794,
cpu_profiler_metadata_size: 0,
}
```
f
getHeapSnapshot
Generates a snapshot of the current V8 heap and returns a Readable
Stream that may be used to read the JSON serialized representation.
This JSON stream format is intended to be used with tools such as
Chrome DevTools. The JSON schema is undocumented and specific to the
V8 engine. Therefore, the schema may change from one version of V8 to the next.
Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.
Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.
```js
// Print heap snapshot to the console
import v8 from 'node:v8';
const stream = v8.getHeapSnapshot();
stream.pipe(process.stdout);
```
f
getHeapSpaceStatistics
Returns statistics about the V8 heap spaces, i.e. the segments which make up
the V8 heap. Neither the ordering of heap spaces, nor the availability of a
heap space can be guaranteed as the statistics are provided via the
V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the
next.
The value returned is an array of objects containing the following properties:
```json
[
{
"space_name": "new_space",
"space_size": 2063872,
"space_used_size": 951112,
"space_available_size": 80824,
"physical_space_size": 2063872
},
{
"space_name": "old_space",
"space_size": 3090560,
"space_used_size": 2493792,
"space_available_size": 0,
"physical_space_size": 3090560
},
{
"space_name": "code_space",
"space_size": 1260160,
"space_used_size": 644256,
"space_available_size": 960,
"physical_space_size": 1260160
},
{
"space_name": "map_space",
"space_size": 1094160,
"space_used_size": 201608,
"space_available_size": 0,
"physical_space_size": 1094160
},
{
"space_name": "large_object_space",
"space_size": 0,
"space_used_size": 0,
"space_available_size": 1490980608,
"physical_space_size": 0
}
]
```
f
getHeapStatistics
Returns an object with the following properties:
`does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap
garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
because it continuously touches all heap pages and that makes them less likely
to get swapped out by the operating system.
`number_of_native_contexts` The value of native\_context is the number of the
top-level contexts currently active. Increase of this number over time indicates
a memory leak.
`number_of_detached_contexts` The value of detached\_context is the number
of contexts that were detached and not yet garbage collected. This number
being non-zero indicates a potential memory leak.
`total_global_handles_size` The value of total\_global\_handles\_size is the
total memory size of V8 global handles.
`used_global_handles_size` The value of used\_global\_handles\_size is the
used memory size of V8 global handles.
`external_memory` The value of external\_memory is the memory size of array
buffers and external strings.
```js
{
total_heap_size: 7326976,
total_heap_size_executable: 4194304,
total_physical_size: 7326976,
total_available_size: 1152656,
used_heap_size: 3476208,
heap_size_limit: 1535115264,
malloced_memory: 16384,
peak_malloced_memory: 1127496,
does_zap_garbage: 0,
number_of_native_contexts: 1,
number_of_detached_contexts: 0,
total_global_handles_size: 8192,
used_global_handles_size: 3296,
external_memory: 318824
}
```
I
HeapCodeStatistics
No documentation available
I
HeapInfo
No documentation available
I
I
HeapSpaceInfo
No documentation available
I
HeapSpaceStatistics
No documentation available
I
I
HookCallbacks
Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or
around an await, and when the promise resolves or rejects.
Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and
`settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop.
I
Init
Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will
happen if a promise is created without ever getting a continuation.
I
v
promiseHooks
The `promiseHooks` interface can be used to track promise lifecycle events.
f
queryObjects
This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function)
provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain
in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should
avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the
application.
To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects
found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided
in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the
target objects during the search.
Only objects created in the current execution context are included in the results.
```js
import { queryObjects } from 'node:v8';
class A { foo = 'bar'; }
console.log(queryObjects(A)); // 0
const a = new A();
console.log(queryObjects(A)); // 1
// [ "A { foo: 'bar' }" ]
console.log(queryObjects(A, { format: 'summary' }));
class B extends A { bar = 'qux'; }
const b = new B();
console.log(queryObjects(B)); // 1
// [ "B { foo: 'bar', bar: 'qux' }" ]
console.log(queryObjects(B, { format: 'summary' }));
// Note that, when there are child classes inheriting from a constructor,
// the constructor also shows up in the prototype chain of the child
// classes's prototoype, so the child classes's prototoype would also be
// included in the result.
console.log(queryObjects(A)); // 3
// [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]
console.log(queryObjects(A, { format: 'summary' }));
```
f
serialize
Uses a `DefaultSerializer` to serialize `value` into a buffer.
`ERR_BUFFER_TOO_LARGE` will be thrown when trying to
serialize a huge object which requires buffer
larger than `buffer.constants.MAX_LENGTH`.
c
f
setFlagsFromString
The `v8.setFlagsFromString()` method can be used to programmatically set
V8 command-line flags. This method should be used with care. Changing settings
after the VM has started may result in unpredictable behavior, including
crashes and data loss; or it may simply do nothing.
The V8 options available for a version of Node.js may be determined by running `node --v8-options`.
Usage:
```js
// Print GC events to stdout for one minute.
import v8 from 'node:v8';
v8.setFlagsFromString('--trace_gc');
setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
```
f
setHeapSnapshotNearHeapLimit
The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once.
`limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information.
I
Settled
Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of Promise.resolve() or
Promise.reject().
I
StartupSnapshot
No documentation available
v
startupSnapshot
The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots.
```bash
$ node --snapshot-blob snapshot.blob --build-snapshot entry.js
$ node --snapshot-blob snapshot.blob
```
In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects
in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot.
For example, if the `entry.js` contains the following script:
```js
'use strict';
import fs from 'node:fs';
import zlib from 'node:zlib';
import path from 'node:path';
import assert from 'node:assert';
import v8 from '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);
```
The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process:
```bash
$ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1
```
Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot.
T
StartupSnapshotCallbackFn
No documentation available
f
stopCoverage
The `v8.stopCoverage()` method allows the user to stop the coverage collection
started by `NODE_V8_COVERAGE`, so that V8 can release the execution count
records and optimize code. This can be used in conjunction with [takeCoverage](././node__v8.d.ts/~/takeCoverage) if the user wants to collect the coverage on demand.
f
takeCoverage
The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple
times during the lifetime of the process. Each time the execution counter will
be reset and a new coverage report will be written to the directory specified
by `NODE_V8_COVERAGE`.
When the process is about to exit, one last coverage will still be written to
disk unless [stopCoverage](././node__v8.d.ts/~/stopCoverage) is invoked before the process exits.
f
writeHeapSnapshot
Generates a snapshot of the current V8 heap and writes it to a JSON
file. This file is intended to be used with tools such as Chrome
DevTools. The JSON schema is undocumented and specific to the V8
engine, and may change from one version of V8 to the next.
A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will
not contain any information about the workers, and vice versa.
Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.
Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.
```js
import { writeHeapSnapshot } from 'node:v8';
import {
Worker,
isMainThread,
parentPort,
} from 'node:worker_threads';
if (isMainThread) {
const worker = new Worker(__filename);
worker.once('message', (filename) => {
console.log(`worker heapdump: ${filename}`);
// Now get a heapdump for the main thread.
console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
});
// Tell the worker to create a heapdump.
worker.postMessage('heapdump');
} else {
parentPort.once('message', (message) => {
if (message === 'heapdump') {
// Generate a heapdump for the worker
// and return the filename to the parent.
parentPort.postMessage(writeHeapSnapshot());
}
});
}
```
node__vm.d.ts
The `node:vm` module enables compiling and running code within V8 Virtual Machine contexts. **The `node:vm` module is not a security** **mechanism. Do not use it to run untrusted code.** JavaScript code can be compiled and run immediately or compiled, saved, and run later. A common use case is to run the code in a different V8 Context. This means invoked code has a different global object than the invoking code. One can provide the context by `contextifying` an object. The invoked code treats any property in the context like a global variable. Any changes to global variables caused by the invoked code are reflected in the context object. ```js import vm from 'node:vm'; const x = 1; const context = { x: 2 }; vm.createContext(context); // Contextify the object. const code = 'x += 40; var y = 17;'; // `x` and `y` are global variables in the context. // Initially, x has the value 2 because that is the value of context.x. vm.runInContext(code, context); console.log(context.x); // 42 console.log(context.y); // 17 console.log(x); // 1; y is not defined. ```I
f
compileFunction
Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given `params`.
I
CompileFunctionOptions
No documentation available
N
constants
Returns an object containing commonly used constants for VM operations.
v
constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
Stability: 1.1 - Active development
A constant that can be used as the `importModuleDynamically` option to `vm.Script`
and `vm.compileFunction()` so that Node.js uses the default ESM loader from the main
context to load the requested module.
For detailed information, see [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v22.x/api/vm.html#support-of-dynamic-import-in-compilation-apis).
I
Context
No documentation available
f
createContext
> [!WARNING] Deno compatibility
> The `importModuleDynamically` parameter is not supported.
If given a `contextObject`, the `vm.createContext()` method will
[prepare that object](https://nodejs.org/docs/latest-v22.x/api/vm.html#what-does-it-mean-to-contextify-an-object)
and return a reference to it so that it can be used in `[runInContext](././node__vm.d.ts/~/runInContext)` or
[`script.runInContext()`](https://nodejs.org/docs/latest-v22.x/api/vm.html#scriptrunincontextcontextifiedobject-options). Inside such
scripts, the `contextObject` will be the global object, retaining all of its
existing properties but also having the built-in objects and functions any
standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global
variables will remain unchanged.
```js
import vm from 'node:vm';
global.globalVar = 3;
const context = { globalVar: 1 };
vm.createContext(context);
vm.runInContext('globalVar *= 2;', context);
console.log(context);
// Prints: { globalVar: 2 }
console.log(global.globalVar);
// Prints: 3
```
If `contextObject` is omitted (or passed explicitly as `undefined`), a new,
empty `contextified` object will be returned.
The `vm.createContext()` method is primarily useful for creating a single
context that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single context representing a
window's global object, then run all `