Welcome to the official API reference documentation for Node.js!
\nNode.js is a JavaScript runtime built on the V8 JavaScript engine.
", "miscs": [ { "textRaw": "Contributing", "name": "contributing", "type": "misc", "desc": "Report errors in this documentation in the issue tracker. See\nthe contributing guide for directions on how to submit pull requests.
", "displayName": "Contributing" }, { "textRaw": "Stability index", "name": "Stability index", "type": "misc", "desc": "Throughout the documentation are indications of a section's stability. Some APIs\nare so proven and so relied upon that they are unlikely to ever change at all.\nOthers are brand new and experimental, or known to be hazardous.
\nThe stability indexes are as follows:
\n\n\nStability: 0 - Deprecated. The feature may emit warnings. Backward\ncompatibility is not guaranteed.
\n
\n\nStability: 1 - Experimental. The feature is not subject to\nsemantic versioning rules. Non-backward compatible changes or removal may\noccur in any future release. Use of the feature is not recommended in\nproduction environments.
\nExperimental features are subdivided into stages:
\n\n
\n- 1.0 - Early development. Experimental features at this stage are unfinished\nand subject to substantial change.
\n- 1.1 - Active development. Experimental features at this stage are nearing\nminimum viability.
\n- 1.2 - Release candidate. Experimental features at this stage are hopefully\nready to become stable. No further breaking changes are anticipated but may\nstill occur in response to user feedback or the features' underlying\nspecification development. We encourage user testing and feedback so that\nwe can know that this feature is ready to be marked as stable.
\nExperimental features leave the experimental status typically either by\ngraduating to stable, or are removed without a deprecation cycle.
\n
\n\nStability: 2 - Stable. Compatibility with the npm ecosystem is a high\npriority.
\n
\n\nStability: 3 - Legacy. Although this feature is unlikely to be removed and is\nstill covered by semantic versioning guarantees, it is no longer actively\nmaintained, and other alternatives are available.
\n
Features are marked as legacy rather than being deprecated if their use does no\nharm, and they are widely relied upon within the npm ecosystem. Bugs found in\nlegacy features are unlikely to be fixed.
\nUse caution when making use of Experimental features, particularly when\nauthoring libraries. Users may not be aware that experimental features are being\nused. Bugs or behavior changes may surprise users when Experimental API\nmodifications occur. To avoid surprises, use of an Experimental feature may need\na command-line flag. Experimental features may also emit a warning.
" }, { "textRaw": "Stability overview", "name": "stability_overview", "type": "misc", "displayName": "Stability overview" }, { "textRaw": "JSON output", "name": "json_output", "type": "misc", "meta": { "added": [ "v0.6.12" ], "changes": [] }, "desc": "Every .html document has a corresponding .json document. This is for IDEs\nand other utilities that consume the documentation.
Node.js functions which wrap a system call will document that. The docs link\nto the corresponding man pages which describe how the system call works.
\nMost Unix system calls have Windows analogues. Still, behavior differences may\nbe unavoidable.
", "displayName": "System calls and man pages" } ], "source": "doc/api/documentation.md" }, { "textRaw": "Usage and example", "name": "Usage and example", "introduced_in": "v0.10.0", "type": "misc", "miscs": [ { "textRaw": "Usage", "name": "usage", "type": "misc", "desc": "node [options] [V8 options] [script.js | -e \"script\" | - ] [arguments]
Please see the Command-line options document for more information.
", "displayName": "Usage" }, { "textRaw": "Example", "name": "example", "type": "misc", "desc": "An example of a web server written with Node.js which responds with\n'Hello, World!':
Commands in this document start with $ or > to replicate how they would\nappear in a user's terminal. Do not include the $ and > characters. They are\nthere to show the start of each command.
Lines that don't start with $ or > character show the output of the previous\ncommand.
First, make sure to have downloaded and installed Node.js. See\nInstalling Node.js via package manager for further install information.
\nNow, create an empty project folder called projects, then navigate into it.
Linux and Mac:
\nmkdir ~/projects\ncd ~/projects\n\nWindows CMD:
\nmkdir %USERPROFILE%\\projects\ncd %USERPROFILE%\\projects\n\nWindows PowerShell:
\nmkdir $env:USERPROFILE\\projects\ncd $env:USERPROFILE\\projects\n\nNext, create a new source file in the projects\nfolder and call it hello-world.js.
Open hello-world.js in any preferred text editor and\npaste in the following content:
const http = require('node:http');\n\nconst hostname = '127.0.0.1';\nconst port = 3000;\n\nconst server = http.createServer((req, res) => {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/plain');\n res.end('Hello, World!\\n');\n});\n\nserver.listen(port, hostname, () => {\n console.log(`Server running at http://${hostname}:${port}/`);\n});\n\nSave the file. Then, in the terminal window, to run the hello-world.js file,\nenter:
node hello-world.js\n\nOutput like this should appear in the terminal:
\nServer running at http://127.0.0.1:3000/\n\nNow, open any preferred web browser and visit http://127.0.0.1:3000.
If the browser displays the string Hello, World!, that indicates\nthe server is working.
Addons are dynamically-linked shared objects written in C++. The\nrequire() function can load addons as ordinary Node.js modules.\nAddons provide an interface between JavaScript and C/C++ libraries.
There are three options for implementing addons:
\nnan (Native Abstractions for Node.js)Unless there is a need for direct access to functionality which is not
\nexposed by Node-API, use Node-API.\nRefer to C/C++ addons with Node-API for more information on\nNode-API.
When not using Node-API, implementing addons becomes more complex, requiring
\nknowledge of multiple components and APIs:
V8: the C++ library Node.js uses to provide the\nJavaScript implementation. It provides the mechanisms for creating objects,\ncalling functions, etc. The V8's API is documented mostly in the\nv8.h header file (deps/v8/include/v8.h in the Node.js source\ntree), and is also available online.
libuv: The C library that implements the Node.js event loop, its worker\nthreads and all of the asynchronous behaviors of the platform. It also\nserves as a cross-platform abstraction library, giving easy, POSIX-like\naccess across all major operating systems to many common system tasks, such\nas interacting with the file system, sockets, timers, and system events. libuv\nalso provides a threading abstraction similar to POSIX threads for\nmore sophisticated asynchronous addons that need to move beyond the\nstandard event loop. Addon authors should\navoid blocking the event loop with I/O or other time-intensive tasks by\noffloading work via libuv to non-blocking system operations, worker threads,\nor a custom use of libuv threads.
\nInternal Node.js libraries: Node.js itself exports C++ APIs that addons can\nuse, the most important of which is the node::ObjectWrap class.
Other statically linked libraries (including OpenSSL): These\nother libraries are located in the deps/ directory in the Node.js source\ntree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully\nre-exported by Node.js and may be used to various extents by addons. See\nLinking to libraries included with Node.js for additional information.
All of the following examples are available for download and may\nbe used as the starting-point for an addon.
", "miscs": [ { "textRaw": "Hello world", "name": "hello_world", "type": "misc", "desc": "This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:
\nmodule.exports.hello = () => 'world';\n\nFirst, create the file hello.cc:
// hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::NewStringType;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid Method(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n args.GetReturnValue().Set(String::NewFromUtf8(\n isolate, \"world\", NewStringType::kNormal).ToLocalChecked());\n}\n\nvoid Initialize(Local<Object> exports) {\n NODE_SET_METHOD(exports, \"hello\", Method);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n\n} // namespace demo\n\nAll Node.js addons must export an initialization function following\nthe pattern:
\nvoid Initialize(Local<Object> exports);\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n\nThere is no semi-colon after NODE_MODULE as it's not a function (see\nnode.h).
The module_name must match the filename of the final binary (excluding\nthe .node suffix).
In the hello.cc example, then, the initialization function is Initialize\nand the addon module name is addon.
When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as\nthe first parameter of NODE_MODULE() will ensure that the name of the final\nbinary will be passed to NODE_MODULE().
Addons defined with NODE_MODULE() can not be loaded in multiple contexts or\nmultiple threads at the same time.
There are environments in which Node.js addons may need to be loaded multiple\ntimes in multiple contexts. For example, the Electron runtime runs multiple\ninstances of Node.js in a single process. Each instance will have its own\nrequire() cache, and thus each instance will need a native addon to behave\ncorrectly when loaded via require(). This means that the addon\nmust support multiple initializations.
A context-aware addon can be constructed by using the macro\nNODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js\nwill expect to find when it loads an addon. An addon can thus be initialized as\nin the following example:
using namespace v8;\n\nextern \"C\" NODE_MODULE_EXPORT void\nNODE_MODULE_INITIALIZER(Local<Object> exports,\n Local<Value> module,\n Local<Context> context) {\n /* Perform addon initialization steps here. */\n}\n\nAnother option is to use the macro NODE_MODULE_INIT(), which will also\nconstruct a context-aware addon. Unlike NODE_MODULE(), which is used to\nconstruct an addon around a given addon initializer function,\nNODE_MODULE_INIT() serves as the declaration of such an initializer to be\nfollowed by a function body.
The following three variables may be used inside the function body following an\ninvocation of NODE_MODULE_INIT():
Local<Object> exports,Local<Value> module, andLocal<Context> contextBuilding a context-aware addon requires careful management of global static data\nto ensure stability and correctness. Since the addon may be loaded multiple\ntimes, potentially even from different threads, any global static data stored\nin the addon must be properly protected, and must not contain any persistent\nreferences to JavaScript objects. The reason for this is that JavaScript\nobjects are only valid in one context, and will likely cause a crash when\naccessed from the wrong context or from a different thread than the one on which\nthey were created.
\nThe context-aware addon can be structured to avoid global static data by\nperforming the following steps:
\nstatic void DeleteInstance(void* data) {\n // Cast `data` to an instance of the class and delete it.\n}\n\nnew keyword.node::AddEnvironmentCleanupHook(), passing it the above-created\ninstance and a pointer to DeleteInstance(). This will ensure the instance is\ndeleted when the environment is torn down.v8::External, andv8::External to all methods exposed to JavaScript by passing it\nto v8::FunctionTemplate::New() or v8::Function::New() which creates the\nnative-backed JavaScript functions. The third parameter of\nv8::FunctionTemplate::New() or v8::Function::New() accepts the\nv8::External and makes it available in the native callback using the\nv8::FunctionCallbackInfo::Data() method.This will ensure that the per-addon-instance data reaches each binding that can\nbe called from JavaScript. The per-addon-instance data must also be passed into\nany asynchronous callbacks the addon may create.
\nThe following example illustrates the implementation of a context-aware addon:
\n#include <node.h>\n\nusing namespace v8;\n\nclass AddonData {\n public:\n explicit AddonData(Isolate* isolate):\n call_count(0) {\n // Ensure this per-addon-instance data is deleted at environment cleanup.\n node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);\n }\n\n // Per-addon data.\n int call_count;\n\n static void DeleteInstance(void* data) {\n delete static_cast<AddonData*>(data);\n }\n};\n\nstatic void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {\n // Retrieve the per-addon-instance data.\n AddonData* data =\n reinterpret_cast<AddonData*>(info.Data().As<External>()->Value());\n data->call_count++;\n info.GetReturnValue().Set((double)data->call_count);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n Isolate* isolate = Isolate::GetCurrent();\n\n // Create a new instance of `AddonData` for this instance of the addon and\n // tie its life cycle to that of the Node.js environment.\n AddonData* data = new AddonData(isolate);\n\n // Wrap the data in a `v8::External` so we can pass it to the method we\n // expose.\n Local<External> external = External::New(isolate, data);\n\n // Expose the method `Method` to JavaScript, and make sure it receives the\n // per-addon-instance data we created above by passing `external` as the\n // third parameter to the `FunctionTemplate` constructor.\n exports->Set(context,\n String::NewFromUtf8(isolate, \"method\").ToLocalChecked(),\n FunctionTemplate::New(isolate, Method, external)\n ->GetFunction(context).ToLocalChecked()).FromJust();\n}\n",
"modules": [
{
"textRaw": "Worker support",
"name": "worker_support",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v14.8.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34572",
"description": "Cleanup hooks may now be asynchronous."
}
]
},
"desc": "In order to be loaded from multiple Node.js environments,\nsuch as a main thread and a Worker thread, an add-on needs to either:
\nNODE_MODULE_INIT() as described aboveIn order to support Worker threads, addons need to clean up any resources\nthey may have allocated when such a thread exits. This can be achieved through\nthe usage of the AddEnvironmentCleanupHook() function:
void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n void (*fun)(void* arg),\n void* arg);\n\nThis function adds a hook that will run before a given Node.js instance shuts\ndown. If necessary, such hooks can be removed before they are run using\nRemoveEnvironmentCleanupHook(), which has the same signature. Callbacks are\nrun in last-in first-out order.
If necessary, there is an additional pair of AddEnvironmentCleanupHook()\nand RemoveEnvironmentCleanupHook() overloads, where the cleanup hook takes a\ncallback function. This can be used for shutting down asynchronous resources,\nsuch as any libuv handles registered by the addon.
The following addon.cc uses AddEnvironmentCleanupHook:
// addon.cc\n#include <node.h>\n#include <assert.h>\n#include <stdlib.h>\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\n// Note: In a real-world application, do not rely on static/global data.\nstatic char cookie[] = \"yum yum\";\nstatic int cleanup_cb1_called = 0;\nstatic int cleanup_cb2_called = 0;\n\nstatic void cleanup_cb1(void* arg) {\n Isolate* isolate = static_cast<Isolate*>(arg);\n HandleScope scope(isolate);\n Local<Object> obj = Object::New(isolate);\n assert(!obj.IsEmpty()); // assert VM is still alive\n assert(obj->IsObject());\n cleanup_cb1_called++;\n}\n\nstatic void cleanup_cb2(void* arg) {\n assert(arg == static_cast<void*>(cookie));\n cleanup_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n assert(cleanup_cb1_called == 1);\n assert(cleanup_cb2_called == 1);\n}\n\n// Initialize this addon to be context-aware.\nNODE_MODULE_INIT(/* exports, module, context */) {\n Isolate* isolate = Isolate::GetCurrent();\n\n AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}\n\nTest in JavaScript by running:
\n// test.js\nrequire('./build/Release/addon');\n",
"displayName": "Worker support"
}
],
"displayName": "Context-aware addons"
},
{
"textRaw": "Building",
"name": "building",
"type": "module",
"desc": "Once the source code has been written, it must be compiled into the binary\naddon.node file. To do so, create a file called binding.gyp in the\ntop-level of the project describing the build configuration of the module\nusing a JSON-like format. This file is used by node-gyp, a tool written\nspecifically to compile Node.js addons.
{\n \"targets\": [\n {\n \"target_name\": \"addon\",\n \"sources\": [ \"hello.cc\" ]\n }\n ]\n}\n\nA version of the node-gyp utility is bundled and distributed with\nNode.js as part of npm. This version is not made directly available for\ndevelopers to use and is intended only to support the ability to use the\nnpm install command to compile and install addons. Developers who wish to\nuse node-gyp directly can install it using the command\nnpm install -g node-gyp. See the node-gyp installation instructions for\nmore information, including platform-specific requirements.
Once the binding.gyp file has been created, use node-gyp configure to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory.
Next, invoke the node-gyp build command to generate the compiled addon.node\nfile. This will be put into the build/Release/ directory.
When using npm install to install a Node.js addon, npm uses its own bundled\nversion of node-gyp to perform this same set of actions, generating a\ncompiled version of the addon for the user's platform on demand.
Once built, the binary addon can be used from within Node.js by pointing\nrequire() to the built addon.node module:
// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n\nBecause the exact path to the compiled addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/), addons can use\nthe bindings package to load the compiled module.
While the bindings package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a try…catch pattern similar to:
try {\n return require('./build/Release/addon.node');\n} catch (err) {\n return require('./build/Debug/addon.node');\n}\n",
"displayName": "Building"
},
{
"textRaw": "Linking to libraries included with Node.js",
"name": "linking_to_libraries_included_with_node.js",
"type": "module",
"desc": "Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All\naddons are required to link to V8 and may link to any of the other dependencies\nas well. Typically, this is as simple as including the appropriate\n#include <...> statements (e.g. #include <v8.h>) and node-gyp will locate\nthe appropriate headers automatically. However, there are a few caveats to be\naware of:
When node-gyp runs, it will detect the specific release version of Node.js\nand download either the full source tarball or just the headers. If the full\nsource is downloaded, addons will have complete access to the full set of\nNode.js dependencies. However, if only the Node.js headers are downloaded,\nthen only the symbols exported by Node.js will be available.
node-gyp can be run using the --nodedir flag pointing at a local Node.js\nsource image. Using this option, the addon will have access to the full set of\ndependencies.
The filename extension of the compiled addon binary is .node (as opposed\nto .dll or .so). The require() function is written to look for\nfiles with the .node file extension and initialize those as dynamically-linked\nlibraries.
When calling require(), the .node extension can usually be\nomitted and Node.js will still find and initialize the addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file addon.js in the same directory as the binary addon.node,\nthen require('addon') will give precedence to the addon.js file\nand load it instead.
Each of the examples illustrated in this document directly use the\nNode.js and V8 APIs for implementing addons. The V8 API can, and has, changed\ndramatically from one V8 release to the next (and one major Node.js release to\nthe next). With each change, addons may need to be updated and recompiled in\norder to continue functioning. The Node.js release schedule is designed to\nminimize the frequency and impact of such changes but there is little that\nNode.js can do to ensure stability of the V8 APIs.
\nThe Native Abstractions for Node.js (or nan) provide a set of tools that\naddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the nan examples for an\nillustration of how it can be used.
Node-API is an API for building native addons. It is independent from\nthe underlying JavaScript runtime (e.g. V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross versions of Node.js. It is intended to insulate addons from\nchanges in the underlying JavaScript engine and allow modules\ncompiled for one version to run on later versions of Node.js without\nrecompilation. Addons are built/packaged with the same approach/tools\noutlined in this document (node-gyp, etc.). The only difference is the\nset of APIs that are used by the native code. Instead of using the V8\nor Native Abstractions for Node.js APIs, the functions available\nin the Node-API are used.
\nCreating and maintaining an addon that benefits from the ABI stability\nprovided by Node-API carries with it certain\nimplementation considerations.
\nTo use Node-API in the above \"Hello world\" example, replace the content of\nhello.cc with the following. All other instructions remain the same.
// hello.cc using Node-API\n#include <node_api.h>\n\nnamespace demo {\n\nnapi_value Method(napi_env env, napi_callback_info args) {\n napi_value greeting;\n napi_status status;\n\n status = napi_create_string_utf8(env, \"world\", NAPI_AUTO_LENGTH, &greeting);\n if (status != napi_ok) return nullptr;\n return greeting;\n}\n\nnapi_value init(napi_env env, napi_value exports) {\n napi_status status;\n napi_value fn;\n\n status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);\n if (status != napi_ok) return nullptr;\n\n status = napi_set_named_property(env, exports, \"hello\", fn);\n if (status != napi_ok) return nullptr;\n return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, init)\n\n} // namespace demo\n\nThe functions available and how to use them are documented in\nC/C++ addons with Node-API.
", "displayName": "Node-API" }, { "textRaw": "Addon examples", "name": "addon_examples", "type": "misc", "desc": "Following are some example addons intended to help developers get started. The\nexamples use the V8 APIs. Refer to the online V8 reference\nfor help with the various V8 calls, and V8's Embedder's Guide for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.
\nEach of these examples using the following binding.gyp file:
{\n \"targets\": [\n {\n \"target_name\": \"addon\",\n \"sources\": [ \"addon.cc\" ]\n }\n ]\n}\n\nIn cases where there is more than one .cc file, simply add the additional\nfilename to the sources array:
\"sources\": [\"addon.cc\", \"myexample.cc\"]\n\nOnce the binding.gyp file is ready, the example addons can be configured and\nbuilt using node-gyp:
node-gyp configure build\n",
"modules": [
{
"textRaw": "Function arguments",
"name": "function_arguments",
"type": "module",
"desc": "Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.
\nThe following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the \"add\" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n // Check the number of arguments passed.\n if (args.Length() < 2) {\n // Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate,\n \"Wrong number of arguments\").ToLocalChecked()));\n return;\n }\n\n // Check the argument types\n if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate,\n \"Wrong arguments\").ToLocalChecked()));\n return;\n }\n\n // Perform the operation\n double value =\n args[0].As<Number>()->Value() + args[1].As<Number>()->Value();\n Local<Number> num = Number::New(isolate, value);\n\n // Set the return value (using the passed in\n // FunctionCallbackInfo<Value>&)\n args.GetReturnValue().Set(num);\n}\n\nvoid Init(Local<Object> exports) {\n NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n} // namespace demo\n\nOnce compiled, the example addon can be required and used from within Node.js:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n",
"displayName": "Function arguments"
},
{
"textRaw": "Callbacks",
"name": "callbacks",
"type": "module",
"desc": "It is common practice within addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cb = Local<Function>::Cast(args[0]);\n const unsigned argc = 1;\n Local<Value> argv[argc] = {\n String::NewFromUtf8(isolate,\n \"hello world\").ToLocalChecked() };\n cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n NODE_SET_METHOD(module, \"exports\", RunCallback);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n} // namespace demo\n\nThis example uses a two-argument form of Init() that receives the full\nmodule object as the second argument. This allows the addon to completely\noverwrite exports with a single function instead of adding the function as a\nproperty of exports.
To test it, run the following JavaScript:
\n// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n console.log(msg);\n// Prints: 'hello world'\n});\n\nIn this example, the callback function is invoked synchronously.
", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "type": "module", "desc": "Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty msg that echoes the string passed to createObject():
// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n Local<Object> obj = Object::New(isolate);\n obj->Set(context,\n String::NewFromUtf8(isolate,\n \"msg\").ToLocalChecked(),\n args[0]->ToString(context).ToLocalChecked())\n .FromJust();\n\n args.GetReturnValue().Set(obj);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n} // namespace demo\n\nTo test it in JavaScript:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n",
"displayName": "Object factory"
},
{
"textRaw": "Function factory",
"name": "function_factory",
"type": "module",
"desc": "Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n args.GetReturnValue().Set(String::NewFromUtf8(\n isolate, \"hello world\").ToLocalChecked());\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n Local<Context> context = isolate->GetCurrentContext();\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n Local<Function> fn = tpl->GetFunction(context).ToLocalChecked();\n\n // omit this to make it anonymous\n fn->SetName(String::NewFromUtf8(\n isolate, \"theFunction\").ToLocalChecked());\n\n args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n NODE_SET_METHOD(module, \"exports\", CreateFunction);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, Init)\n\n} // namespace demo\n\nTo test:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n",
"displayName": "Function factory"
},
{
"textRaw": "Wrapping C++ objects",
"name": "wrapping_c++_objects",
"type": "module",
"desc": "It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new operator:
// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Local;\nusing v8::Object;\n\nvoid InitAll(Local<Object> exports) {\n MyObject::Init(exports);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n} // namespace demo\n\nThen, in myobject.h, the wrapper class inherits from node::ObjectWrap:
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init(v8::Local<v8::Object> exports);\n\n private:\n explicit MyObject(double value = 0);\n ~MyObject();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n double value_;\n};\n\n} // namespace demo\n\n#endif\n\nIn myobject.cc, implement the various methods that are to be exposed.\nIn the following code, the method plusOne() is exposed by adding it to the\nconstructor's prototype:
// myobject.cc\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n Isolate* isolate = Isolate::GetCurrent();\n Local<Context> context = isolate->GetCurrentContext();\n\n Local<ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);\n addon_data_tpl->SetInternalFieldCount(1); // 1 field for the MyObject::New()\n Local<Object> addon_data =\n addon_data_tpl->NewInstance(context).ToLocalChecked();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n // Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n Local<Function> constructor = tpl->GetFunction(context).ToLocalChecked();\n addon_data->SetInternalField(0, constructor);\n exports->Set(context, String::NewFromUtf8(\n isolate, \"MyObject\").ToLocalChecked(),\n constructor).FromJust();\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ?\n 0 : args[0]->NumberValue(context).FromMaybe(0);\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons =\n args.Data().As<Object>()->GetInternalField(0)\n .As<Value>().As<Function>();\n Local<Object> result =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n obj->value_ += 1;\n\n args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n} // namespace demo\n\nTo build this example, the myobject.cc file must be added to the\nbinding.gyp:
{\n \"targets\": [\n {\n \"target_name\": \"addon\",\n \"sources\": [\n \"addon.cc\",\n \"myobject.cc\"\n ]\n }\n ]\n}\n\nTest it with:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nThe destructor for a wrapper object will run when the object is\ngarbage-collected. For destructor testing, there are command-line flags that\ncan be used to make it possible to force garbage collection. These flags are\nprovided by the underlying V8 JavaScript engine. They are subject to change\nor removal at any time. They are not documented by Node.js or V8, and they\nshould never be used outside of testing.
\nDuring shutdown of the process or worker threads destructors are not called\nby the JS engine. Therefore it's the responsibility of the user to track\nthese objects and ensure proper destruction to avoid resource leaks.
", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "type": "module", "desc": "Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript new operator:
const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n\nFirst, the createObject() method is implemented in addon.cc:
// addon.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n MyObject::Init();\n\n NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n} // namespace demo\n\nIn myobject.h, the static method NewInstance() is added to handle\ninstantiating the object. This method takes the place of using new in\nJavaScript:
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init();\n static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n\n private:\n explicit MyObject(double value = 0);\n ~MyObject();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n static v8::Global<v8::Function> constructor;\n double value_;\n};\n\n} // namespace demo\n\n#endif\n\nThe implementation in myobject.cc is similar to the previous example:
// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n Isolate* isolate = Isolate::GetCurrent();\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n // Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"plusOne\", PlusOne);\n\n Local<Context> context = isolate->GetCurrentContext();\n constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n AddEnvironmentCleanupHook(isolate, [](void*) {\n constructor.Reset();\n }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ?\n 0 : args[0]->NumberValue(context).FromMaybe(0);\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(instance);\n }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n const unsigned argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n obj->value_ += 1;\n\n args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n} // namespace demo\n\nOnce again, to build this example, the myobject.cc file must be added to the\nbinding.gyp:
{\n \"targets\": [\n {\n \"target_name\": \"addon\",\n \"sources\": [\n \"addon.cc\",\n \"myobject.cc\"\n ]\n }\n ]\n}\n\nTest it with:
\n// test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n",
"displayName": "Factory of wrapped objects"
},
{
"textRaw": "Passing wrapped objects around",
"name": "passing_wrapped_objects_around",
"type": "module",
"desc": "In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\nnode::ObjectWrap::Unwrap. The following examples shows a function add()\nthat can take two MyObject objects as input arguments:
// addon.cc\n#include <node.h>\n#include <node_object_wrap.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n MyObject::NewInstance(args);\n}\n\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n args[0]->ToObject(context).ToLocalChecked());\n MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n args[1]->ToObject(context).ToLocalChecked());\n\n double sum = obj1->value() + obj2->value();\n args.GetReturnValue().Set(Number::New(isolate, sum));\n}\n\nvoid InitAll(Local<Object> exports) {\n MyObject::Init();\n\n NODE_SET_METHOD(exports, \"createObject\", CreateObject);\n NODE_SET_METHOD(exports, \"add\", Add);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n} // namespace demo\n\nIn myobject.h, a new public method is added to allow access to private values\nafter unwrapping the object.
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init();\n static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);\n inline double value() const { return value_; }\n\n private:\n explicit MyObject(double value = 0);\n ~MyObject();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n static v8::Global<v8::Function> constructor;\n double value_;\n};\n\n} // namespace demo\n\n#endif\n\nThe implementation of myobject.cc remains similar to the previous version:
// myobject.cc\n#include <node.h>\n#include \"myobject.h\"\n\nnamespace demo {\n\nusing node::AddEnvironmentCleanupHook;\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Global;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// Warning! This is not thread-safe, this addon cannot be used for worker\n// threads.\nGlobal<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n Isolate* isolate = Isolate::GetCurrent();\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"MyObject\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Local<Context> context = isolate->GetCurrentContext();\n constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());\n\n AddEnvironmentCleanupHook(isolate, [](void*) {\n constructor.Reset();\n }, nullptr);\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Context> context = isolate->GetCurrentContext();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ?\n 0 : args[0]->NumberValue(context).FromMaybe(0);\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(instance);\n }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n const unsigned argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n args.GetReturnValue().Set(instance);\n}\n\n} // namespace demo\n\nTest it with:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n",
"displayName": "Passing wrapped objects around"
}
],
"displayName": "Addon examples"
}
],
"source": "doc/api/addons.md"
},
{
"textRaw": "Node-API",
"name": "Node-API",
"introduced_in": "v8.0.0",
"type": "misc",
"stability": 2,
"stabilityText": "Stable",
"desc": "Node-API (formerly N-API) is an API for building native Addons. It is\nindependent from the underlying JavaScript runtime (for example, V8) and is\nmaintained as part of Node.js itself. This API will be Application Binary\nInterface (ABI) stable across versions of Node.js. It is intended to insulate\naddons from changes in the underlying JavaScript engine and allow modules\ncompiled for one major version to run on later major versions of Node.js without\nrecompilation. The ABI Stability guide provides a more in-depth explanation.
\nAddons are built/packaged with the same approach/tools outlined in the section\ntitled C++ Addons. The only difference is the set of APIs that are used by\nthe native code. Instead of using the V8 or Native Abstractions for Node.js\nAPIs, the functions available in Node-API are used.
\nAPIs exposed by Node-API are generally used to create and manipulate\nJavaScript values. Concepts and operations generally map to ideas specified\nin the ECMA-262 Language Specification. The APIs have the following\nproperties:
\nnapi_status. This\nstatus indicates whether the API call succeeded or failed.napi_value.napi_get_last_error_info. More information can be found in the error\nhandling section Error handling.Node-API is a C API that ensures ABI stability across Node.js versions\nand different compiler levels. With this stability guarantee, it is possible\nto write addons in other programming languages on top of Node-API. Refer\nto language and engine bindings for more programming languages and engines\nsupport details.
\nnode-addon-api is the official C++ binding that provides a more efficient way to\nwrite C++ code that calls Node-API. This wrapper is a header-only library that offers an inlinable C++ API.\nBinaries built with node-addon-api will depend on the symbols of the Node-API\nC-based functions exported by Node.js. The following code snippet is an example\nof node-addon-api:
Object obj = Object::New(env);\nobj[\"foo\"] = String::New(env, \"bar\");\n\nThe above node-addon-api C++ code is equivalent to the following C-based\nNode-API code:
napi_status status;\nnapi_value object, string;\nstatus = napi_create_object(env, &object);\nif (status != napi_ok) {\n napi_throw_error(env, ...);\n return;\n}\n\nstatus = napi_create_string_utf8(env, \"bar\", NAPI_AUTO_LENGTH, &string);\nif (status != napi_ok) {\n napi_throw_error(env, ...);\n return;\n}\n\nstatus = napi_set_named_property(env, object, \"foo\", string);\nif (status != napi_ok) {\n napi_throw_error(env, ...);\n return;\n}\n\nThe end result is that the addon only uses the exported C APIs. Even though\nthe addon is written in C++, it still gets the benefits of the ABI stability\nprovided by the C Node-API.
\nWhen using node-addon-api instead of the C APIs, start with the API docs\nfor node-addon-api.
The Node-API Resource offers\nan excellent orientation and tips for developers just getting started with\nNode-API and node-addon-api. Additional media resources can be found on the\nNode-API Media page.
Although Node-API provides an ABI stability guarantee, other parts of Node.js do\nnot, and any external libraries used from the addon may not. In particular,\nnone of the following APIs provide an ABI stability guarantee across major\nversions:
\nthe Node.js C++ APIs available via any of
\n#include <node.h>\n#include <node_buffer.h>\n#include <node_version.h>\n#include <node_object_wrap.h>\n\nthe libuv APIs which are also included with Node.js and available via
\n#include <uv.h>\n\nthe V8 API available via
\n#include <v8.h>\n\nThus, for an addon to remain ABI-compatible across Node.js major versions, it\nmust use Node-API exclusively by restricting itself to using
\n#include <node_api.h>\n\nand by checking, for all external libraries that it uses, that the external\nlibrary makes ABI stability guarantees similar to Node-API.
", "modules": [ { "textRaw": "Enum values in ABI stability", "name": "enum_values_in_abi_stability", "type": "module", "desc": "All enum data types defined in Node-API should be considered as a fixed size\nint32_t value. Bit flag enum types should be explicitly documented, and they\nwork with bit operators like bit-OR (|) as a bit value. Unless otherwise\ndocumented, an enum type should be considered to be extensible.
A new enum value will be added at the end of the enum definition. An enum value\nwill not be removed or renamed.
\nFor an enum type returned from a Node-API function, or provided as an out\nparameter of a Node-API function, the value is an integer value and an addon\nshould handle unknown values. New values are allowed to be introduced without\na version guard. For example, when checking napi_status in switch statements,\nan addon should include a default branch, as new status codes may be introduced\nin newer Node.js versions.
For an enum type used in an in-parameter, the result of passing an unknown\ninteger value to Node-API functions is undefined unless otherwise documented.\nA new value is added with a version guard to indicate the Node-API version in\nwhich it was introduced. For example, napi_get_all_property_names can be\nextended with new enum value of napi_key_filter.
For an enum type used in both in-parameters and out-parameters, new values are\nallowed to be introduced without a version guard.
", "displayName": "Enum values in ABI stability" } ], "displayName": "Implications of ABI stability" }, { "textRaw": "Building", "name": "building", "type": "misc", "desc": "Unlike modules written in JavaScript, developing and deploying Node.js\nnative addons using Node-API requires an additional set of tools. Besides the\nbasic tools required to develop for Node.js, the native addon developer\nrequires a toolchain that can compile C and C++ code into a binary. In\naddition, depending upon how the native addon is deployed, the user of\nthe native addon will also need to have a C/C++ toolchain installed.
\nFor Linux developers, the necessary C/C++ toolchain packages are readily\navailable. GCC is widely used in the Node.js community to build and\ntest across a variety of platforms. For many developers, the LLVM\ncompiler infrastructure is also a good choice.
\nFor Mac developers, Xcode offers all the required compiler tools.\nHowever, it is not necessary to install the entire Xcode IDE. The following\ncommand installs the necessary toolchain:
\nxcode-select --install\n\nFor Windows developers, Visual Studio offers all the required compiler\ntools. However, it is not necessary to install the entire Visual Studio\nIDE. The following command installs the necessary toolchain:
\nnpm install --global windows-build-tools\n\nThe sections below describe the additional tools available for developing\nand deploying Node.js native addons.
", "modules": [ { "textRaw": "Build tools", "name": "build_tools", "type": "module", "desc": "Both the tools listed here require that users of the native\naddon have a C/C++ toolchain installed in order to successfully install\nthe native addon.
", "modules": [ { "textRaw": "node-gyp", "name": "node-gyp", "type": "module", "desc": "node-gyp is a build system based on the gyp-next fork of\nGoogle's GYP tool and comes bundled with npm. GYP, and therefore node-gyp,\nrequires that Python be installed.
\nHistorically, node-gyp has been the tool of choice for building native\naddons. It has widespread adoption and documentation. However, some\ndevelopers have run into limitations in node-gyp.
", "displayName": "node-gyp" }, { "textRaw": "CMake.js", "name": "cmake.js", "type": "module", "desc": "CMake.js is an alternative build system based on CMake.
\nCMake.js is a good choice for projects that already use CMake or for\ndevelopers affected by limitations in node-gyp. build_with_cmake is an\nexample of a CMake-based native addon project.
The three tools listed here permit native addon developers and maintainers\nto create and upload binaries to public or private servers. These tools are\ntypically integrated with CI/CD build systems like Travis CI and\nAppVeyor to build and upload binaries for a variety of platforms and\narchitectures. These binaries are then available for download by users who\ndo not need to have a C/C++ toolchain installed.
", "modules": [ { "textRaw": "node-pre-gyp", "name": "node-pre-gyp", "type": "module", "desc": "node-pre-gyp is a tool based on node-gyp that adds the ability to\nupload binaries to a server of the developer's choice. node-pre-gyp has\nparticularly good support for uploading binaries to Amazon S3.
", "displayName": "node-pre-gyp" }, { "textRaw": "prebuild", "name": "prebuild", "type": "module", "desc": "prebuild is a tool that supports builds using either node-gyp or\nCMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild\nuploads binaries only to GitHub releases. prebuild is a good choice for\nGitHub projects using CMake.js.
", "displayName": "prebuild" }, { "textRaw": "prebuildify", "name": "prebuildify", "type": "module", "desc": "prebuildify is a tool based on node-gyp. The advantage of prebuildify is\nthat the built binaries are bundled with the native addon when it's\nuploaded to npm. The binaries are downloaded from npm and are immediately\navailable to the module user when the native addon is installed.
", "displayName": "prebuildify" } ], "displayName": "Uploading precompiled binaries" } ], "displayName": "Building" }, { "textRaw": "Usage", "name": "usage", "type": "misc", "desc": "In order to use the Node-API functions, include the file node_api.h which\nis located in the src directory in the node development tree:
#include <node_api.h>\n\nThis will opt into the default NAPI_VERSION for the given release of Node.js.\nIn order to ensure compatibility with specific versions of Node-API, the version\ncan be specified explicitly when including the header:
#define NAPI_VERSION 3\n#include <node_api.h>\n\nThis restricts the Node-API surface to just the functionality that was available\nin the specified (and earlier) versions.
\nSome of the Node-API surface is experimental and requires explicit opt-in:
\n#define NAPI_EXPERIMENTAL\n#include <node_api.h>\n\nIn this case the entire API surface, including any experimental APIs, will be\navailable to the module code.
\nOccasionally, experimental features are introduced that affect already-released\nand stable APIs. These features can be disabled by an opt-out:
\n#define NAPI_EXPERIMENTAL\n#define NODE_API_EXPERIMENTAL_<FEATURE_NAME>_OPT_OUT\n#include <node_api.h>\n\nwhere <FEATURE_NAME> is the name of an experimental feature that affects both\nexperimental and stable APIs.
Up until version 9, Node-API versions were additive and versioned\nindependently from Node.js. This meant that any version was\nan extension to the previous version in that it had all of\nthe APIs from the previous version with some additions. Each\nNode.js version only supported a single Node-API version.\nFor example v18.15.0 supports only Node-API version 8. ABI stability was\nachieved because 8 was a strict superset of all previous versions.
\nAs of version 9, while Node-API versions continue to be versioned\nindependently, an add-on that ran with Node-API version 9 may need\ncode updates to run with Node-API version 10. ABI stability\nis maintained, however, because Node.js versions that support\nNode-API versions higher than 8 will support all versions\nbetween 8 and the highest version they support and will default\nto providing the version 8 APIs unless an add-on opts into a\nhigher Node-API version. This approach provides the flexibility\nof better optimizing existing Node-API functions while\nmaintaining ABI stability. Existing add-ons can continue to run without\nrecompilation using an earlier version of Node-API. If an add-on\nneeds functionality from a newer Node-API version, changes to existing\ncode and recompilation will be needed to use those new functions anyway.
\nIn versions of Node.js that support Node-API version 9 and later, defining\nNAPI_VERSION=X and using the existing add-on initialization macros\nwill bake in the requested Node-API version that will be used at runtime\ninto the add-on. If NAPI_VERSION is not set it will default to 8.
This table may not be up to date in older streams, the most up to date\ninformation is in the latest API documentation in:\nNode-API version matrix
\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Node-API version | Supported In |
|---|---|
| 10 | v22.14.0+, 23.6.0+ and all later versions |
| 9 | v18.17.0+, 20.3.0+, 21.0.0 and all later versions |
| 8 | v12.22.0+, v14.17.0+, v15.12.0+, 16.0.0 and all later versions |
| 7 | v10.23.0+, v12.19.0+, v14.12.0+, 15.0.0 and all later versions |
| 6 | v10.20.0+, v12.17.0+, 14.0.0 and all later versions |
| 5 | v10.17.0+, v12.11.0+, 13.0.0 and all later versions |
| 4 | v10.16.0+, v11.8.0+, 12.0.0 and all later versions |
| 3 | v6.14.2*, 8.11.2+, v9.11.0+*, 10.0.0 and all later versions |
| 2 | v8.10.0+*, v9.3.0+*, 10.0.0 and all later versions |
| 1 | v8.6.0+**, v9.0.0+*, 10.0.0 and all later versions |
* Node-API was experimental.
\n** Node.js 8.0.0 included Node-API as experimental. It was released as\nNode-API version 1 but continued to evolve until Node.js 8.6.0. The API is\ndifferent in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or\nlater.
\nEach API documented for Node-API will have a header named added in:, and APIs\nwhich are stable will have the additional header Node-API version:.\nAPIs are directly usable when using a Node.js version which supports\nthe Node-API version shown in Node-API version: or higher.\nWhen using a Node.js version that does not support the\nNode-API version: listed or if there is no Node-API version: listed,\nthen the API will only be available if\n#define NAPI_EXPERIMENTAL precedes the inclusion of node_api.h\nor js_native_api.h. If an API appears not to be available on\na version of Node.js which is later than the one shown in added in: then\nthis is most likely the reason for the apparent absence.
The Node-APIs associated strictly with accessing ECMAScript features from native\ncode can be found separately in js_native_api.h and js_native_api_types.h.\nThe APIs defined in these headers are included in node_api.h and\nnode_api_types.h. The headers are structured in this way in order to allow\nimplementations of Node-API outside of Node.js. For those implementations the\nNode.js specific APIs may not be applicable.
The Node.js-specific parts of an addon can be separated from the code that\nexposes the actual functionality to the JavaScript environment so that the\nlatter may be used with multiple implementations of Node-API. In the example\nbelow, addon.c and addon.h refer only to js_native_api.h. This ensures\nthat addon.c can be reused to compile against either the Node.js\nimplementation of Node-API or any implementation of Node-API outside of Node.js.
addon_node.c is a separate file that contains the Node.js specific entry point\nto the addon and which instantiates the addon by calling into addon.c when the\naddon is loaded into a Node.js environment.
// addon.h\n#ifndef _ADDON_H_\n#define _ADDON_H_\n#include <js_native_api.h>\nnapi_value create_addon(napi_env env);\n#endif // _ADDON_H_\n\n// addon.c\n#include \"addon.h\"\n\n#define NODE_API_CALL(env, call) \\\n do { \\\n napi_status status = (call); \\\n if (status != napi_ok) { \\\n const napi_extended_error_info* error_info = NULL; \\\n napi_get_last_error_info((env), &error_info); \\\n const char* err_message = error_info->error_message; \\\n bool is_pending; \\\n napi_is_exception_pending((env), &is_pending); \\\n /* If an exception is already pending, don't rethrow it */ \\\n if (!is_pending) { \\\n const char* message = (err_message == NULL) \\\n ? \"empty error message\" \\\n : err_message; \\\n napi_throw_error((env), NULL, message); \\\n } \\\n return NULL; \\\n } \\\n } while(0)\n\nstatic napi_value\nDoSomethingUseful(napi_env env, napi_callback_info info) {\n // Do something useful.\n return NULL;\n}\n\nnapi_value create_addon(napi_env env) {\n napi_value result;\n NODE_API_CALL(env, napi_create_object(env, &result));\n\n napi_value exported_function;\n NODE_API_CALL(env, napi_create_function(env,\n \"doSomethingUseful\",\n NAPI_AUTO_LENGTH,\n DoSomethingUseful,\n NULL,\n &exported_function));\n\n NODE_API_CALL(env, napi_set_named_property(env,\n result,\n \"doSomethingUseful\",\n exported_function));\n\n return result;\n}\n\n// addon_node.c\n#include <node_api.h>\n#include \"addon.h\"\n\nNAPI_MODULE_INIT(/* napi_env env, napi_value exports */) {\n // This function body is expected to return a `napi_value`.\n // The variables `napi_env env` and `napi_value exports` may be used within\n // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.\n return create_addon(env);\n}\n",
"displayName": "Node-API version matrix"
},
{
"textRaw": "Environment life cycle APIs",
"name": "environment_life_cycle_apis",
"type": "misc",
"desc": "Section Agents of the ECMAScript Language Specification defines the concept\nof an \"Agent\" as a self-contained environment in which JavaScript code runs.\nMultiple such Agents may be started and terminated either concurrently or in\nsequence by the process.
\nA Node.js environment corresponds to an ECMAScript Agent. In the main process,\nan environment is created at startup, and additional environments can be created\non separate threads to serve as worker threads. When Node.js is embedded in\nanother application, the main thread of the application may also construct and\ndestroy a Node.js environment multiple times during the life cycle of the\napplication process such that each Node.js environment created by the\napplication may, in turn, during its life cycle create and destroy additional\nenvironments as worker threads.
\nFrom the perspective of a native addon this means that the bindings it provides\nmay be called multiple times, from multiple contexts, and even concurrently from\nmultiple threads.
\nNative addons may need to allocate global state which they use during\ntheir life cycle of an Node.js environment such that the state can be\nunique to each instance of the addon.
\nTo this end, Node-API provides a way to associate data such that its life cycle\nis tied to the life cycle of a Node.js environment.
", "modules": [ { "textRaw": "`napi_set_instance_data`", "name": "`napi_set_instance_data`", "type": "module", "meta": { "added": [ "v12.8.0", "v10.20.0" ], "changes": [], "napiVersion": [ 6 ] }, "desc": "napi_status napi_set_instance_data(node_api_basic_env env,\n void* data,\n napi_finalize finalize_cb,\n void* finalize_hint);\n\n[in] env: The environment that the Node-API call is invoked under.[in] data: The data item to make available to bindings of this instance.[in] finalize_cb: The function to call when the environment is being torn\ndown. The function receives data so that it might free it.\nnapi_finalize provides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.Returns napi_ok if the API succeeded.
This API associates data with the currently running Node.js environment. data\ncan later be retrieved using napi_get_instance_data(). Any existing data\nassociated with the currently running Node.js environment which was set by means\nof a previous call to napi_set_instance_data() will be overwritten. If a\nfinalize_cb was provided by the previous call, it will not be called.
napi_status napi_get_instance_data(node_api_basic_env env,\n void** data);\n\n[in] env: The environment that the Node-API call is invoked under.[out] data: The data item that was previously associated with the currently\nrunning Node.js environment by a call to napi_set_instance_data().Returns napi_ok if the API succeeded.
This API retrieves data that was previously associated with the currently\nrunning Node.js environment via napi_set_instance_data(). If no data is set,\nthe call will succeed and data will be set to NULL.
Node-API exposes the following fundamental data types as abstractions that are\nconsumed by the various APIs. These APIs should be treated as opaque,\nintrospectable only with other Node-API calls.
", "modules": [ { "textRaw": "`napi_status`", "name": "`napi_status`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "Integral status code indicating the success or failure of a Node-API call.\nCurrently, the following status codes are supported.
\ntypedef enum {\n napi_ok,\n napi_invalid_arg,\n napi_object_expected,\n napi_string_expected,\n napi_name_expected,\n napi_function_expected,\n napi_number_expected,\n napi_boolean_expected,\n napi_array_expected,\n napi_generic_failure,\n napi_pending_exception,\n napi_cancelled,\n napi_escape_called_twice,\n napi_handle_scope_mismatch,\n napi_callback_scope_mismatch,\n napi_queue_full,\n napi_closing,\n napi_bigint_expected,\n napi_date_expected,\n napi_arraybuffer_expected,\n napi_detachable_arraybuffer_expected,\n napi_would_deadlock, /* unused */\n napi_no_external_buffers_allowed,\n napi_cannot_run_js\n} napi_status;\n\nIf additional information is required upon an API returning a failed status,\nit can be obtained by calling napi_get_last_error_info.
typedef struct {\n const char* error_message;\n void* engine_reserved;\n uint32_t engine_error_code;\n napi_status error_code;\n} napi_extended_error_info;\n\nerror_message: UTF8-encoded string containing a VM-neutral description of\nthe error.engine_reserved: Reserved for VM-specific error details. This is currently\nnot implemented for any VM.engine_error_code: VM-specific error code. This is currently\nnot implemented for any VM.error_code: The Node-API status code that originated with the last error.See the Error handling section for additional information.
", "displayName": "`napi_extended_error_info`" }, { "textRaw": "`napi_env`", "name": "`napi_env`", "type": "module", "desc": "napi_env is used to represent a context that the underlying Node-API\nimplementation can use to persist VM-specific state. This structure is passed\nto native functions when they're invoked, and it must be passed back when\nmaking Node-API calls. Specifically, the same napi_env that was passed in when\nthe initial native function was called must be passed to any subsequent\nnested Node-API calls. Caching the napi_env for the purpose of general reuse,\nand passing the napi_env between instances of the same addon running on\ndifferent Worker threads is not allowed. The napi_env becomes invalid\nwhen an instance of a native addon is unloaded. Notification of this event is\ndelivered through the callbacks given to napi_add_env_cleanup_hook and\nnapi_set_instance_data.
This variant of napi_env is passed to synchronous finalizers\n(node_api_basic_finalize). There is a subset of Node-APIs which accept\na parameter of type node_api_basic_env as their first argument. These APIs do\nnot access the state of the JavaScript engine and are thus safe to call from\nsynchronous finalizers. Passing a parameter of type napi_env to these APIs is\nallowed, however, passing a parameter of type node_api_basic_env to APIs that\naccess the JavaScript engine state is not allowed. Attempting to do so without\na cast will produce a compiler warning or an error when add-ons are compiled\nwith flags which cause them to emit warnings and/or errors when incorrect\npointer types are passed into a function. Calling such APIs from a synchronous\nfinalizer will ultimately result in the termination of the application.
This is an opaque pointer that is used to represent a JavaScript value.
", "displayName": "`napi_value`" }, { "textRaw": "`napi_threadsafe_function`", "name": "`napi_threadsafe_function`", "type": "module", "meta": { "added": [ "v10.6.0" ], "changes": [], "napiVersion": [ 4 ] }, "desc": "This is an opaque pointer that represents a JavaScript function which can be\ncalled asynchronously from multiple threads via\nnapi_call_threadsafe_function().
A value to be given to napi_release_threadsafe_function() to indicate whether\nthe thread-safe function is to be closed immediately (napi_tsfn_abort) or\nmerely released (napi_tsfn_release) and thus available for subsequent use via\nnapi_acquire_threadsafe_function() and napi_call_threadsafe_function().
typedef enum {\n napi_tsfn_release,\n napi_tsfn_abort\n} napi_threadsafe_function_release_mode;\n",
"displayName": "`napi_threadsafe_function_release_mode`"
},
{
"textRaw": "`napi_threadsafe_function_call_mode`",
"name": "`napi_threadsafe_function_call_mode`",
"type": "module",
"meta": {
"added": [
"v10.6.0"
],
"changes": [],
"napiVersion": [
4
]
},
"desc": "A value to be given to napi_call_threadsafe_function() to indicate whether\nthe call should block whenever the queue associated with the thread-safe\nfunction is full.
typedef enum {\n napi_tsfn_nonblocking,\n napi_tsfn_blocking\n} napi_threadsafe_function_call_mode;\n",
"displayName": "`napi_threadsafe_function_call_mode`"
},
{
"textRaw": "Node-API memory management types",
"name": "node-api_memory_management_types",
"type": "module",
"modules": [
{
"textRaw": "`napi_handle_scope`",
"name": "`napi_handle_scope`",
"type": "module",
"desc": "This is an abstraction used to control and modify the lifetime of objects\ncreated within a particular scope. In general, Node-API values are created\nwithin the context of a handle scope. When a native method is called from\nJavaScript, a default handle scope will exist. If the user does not explicitly\ncreate a new handle scope, Node-API values will be created in the default handle\nscope. For any invocations of code outside the execution of a native method\n(for instance, during a libuv callback invocation), the module is required to\ncreate a scope before invoking any functions that can result in the creation\nof JavaScript values.
\nHandle scopes are created using napi_open_handle_scope and are destroyed\nusing napi_close_handle_scope. Closing the scope can indicate to the GC\nthat all napi_values created during the lifetime of the handle scope are no\nlonger referenced from the current stack frame.
For more details, review the Object lifetime management.
", "displayName": "`napi_handle_scope`" }, { "textRaw": "`napi_escapable_handle_scope`", "name": "`napi_escapable_handle_scope`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "Escapable handle scopes are a special type of handle scope to return values\ncreated within a particular handle scope to a parent scope.
", "displayName": "`napi_escapable_handle_scope`" }, { "textRaw": "`napi_ref`", "name": "`napi_ref`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "This is the abstraction to use to reference a napi_value. This allows for\nusers to manage the lifetimes of JavaScript values, including defining their\nminimum lifetimes explicitly.
For more details, review the Object lifetime management.
", "displayName": "`napi_ref`" }, { "textRaw": "`napi_type_tag`", "name": "`napi_type_tag`", "type": "module", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [], "napiVersion": [ 8 ] }, "desc": "A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID\nwith which JavaScript objects or externals can be \"tagged\" in order to\nensure that they are of a certain type. This is a stronger check than\nnapi_instanceof, because the latter can report a false positive if the\nobject's prototype has been manipulated. Type-tagging is most useful in\nconjunction with napi_wrap because it ensures that the pointer retrieved\nfrom a wrapped object can be safely cast to the native type corresponding to the\ntype tag that had been previously applied to the JavaScript object.
typedef struct {\n uint64_t lower;\n uint64_t upper;\n} napi_type_tag;\n",
"displayName": "`napi_type_tag`"
},
{
"textRaw": "`napi_async_cleanup_hook_handle`",
"name": "`napi_async_cleanup_hook_handle`",
"type": "module",
"meta": {
"added": [
"v14.10.0",
"v12.19.0"
],
"changes": []
},
"desc": "An opaque value returned by napi_add_async_cleanup_hook. It must be passed\nto napi_remove_async_cleanup_hook when the chain of asynchronous cleanup\nevents completes.
Opaque datatype that is passed to a callback function. It can be used for\ngetting additional information about the context in which the callback was\ninvoked.
", "displayName": "`napi_callback_info`" }, { "textRaw": "`napi_callback`", "name": "`napi_callback`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "Function pointer type for user-provided native functions which are to be\nexposed to JavaScript via Node-API. Callback functions should satisfy the\nfollowing signature:
\ntypedef napi_value (*napi_callback)(napi_env, napi_callback_info);\n\nUnless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside a napi_callback is not necessary.
Function pointer type for add-on provided functions that allow the user to be\nnotified when externally-owned data is ready to be cleaned up because the\nobject it was associated with has been garbage-collected. The user must provide\na function satisfying the following signature which would get called upon the\nobject's collection. Currently, node_api_basic_finalize can be used for\nfinding out when objects that have external data are collected.
typedef void (*node_api_basic_finalize)(node_api_basic_env env,\n void* finalize_data,\n void* finalize_hint);\n\nUnless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.
\nSince these functions may be called while the JavaScript engine is in a state\nwhere it cannot execute JavaScript code, only Node-APIs which accept a\nnode_api_basic_env as their first parameter may be called.\nnode_api_post_finalizer can be used to schedule Node-API calls that\nrequire access to the JavaScript engine's state to run after the current\ngarbage collection cycle has completed.
In the case of node_api_create_external_string_latin1 and\nnode_api_create_external_string_utf16 the env parameter may be null,\nbecause external strings can be collected during the latter part of environment\nshutdown.
Change History:
\nexperimental (NAPI_EXPERIMENTAL):
Only Node-API calls that accept a node_api_basic_env as their first\nparameter may be called, otherwise the application will be terminated with an\nappropriate error message. This feature can be turned off by defining\nNODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT.
Function pointer type for add-on provided function that allow the user to\nschedule a group of calls to Node-APIs in response to a garbage collection\nevent, after the garbage collection cycle has completed. These function\npointers can be used with node_api_post_finalizer.
typedef void (*napi_finalize)(napi_env env,\n void* finalize_data,\n void* finalize_hint);\n\nChange History:
\nexperimental (NAPI_EXPERIMENTAL is defined):
A function of this type may no longer be used as a finalizer, except with\nnode_api_post_finalizer. node_api_basic_finalize must be used\ninstead. This feature can be turned off by defining\nNODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT.
Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:
\ntypedef void (*napi_async_execute_callback)(napi_env env, void* data);\n\nImplementations of this function must avoid making Node-API calls that execute\nJavaScript or interact with JavaScript objects. Node-API calls should be in the\nnapi_async_complete_callback instead. Do not use the napi_env parameter as\nit will likely result in execution of JavaScript.
Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:
\ntypedef void (*napi_async_complete_callback)(napi_env env,\n napi_status status,\n void* data);\n\nUnless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.
", "displayName": "`napi_async_complete_callback`" }, { "textRaw": "`napi_threadsafe_function_call_js`", "name": "`napi_threadsafe_function_call_js`", "type": "module", "meta": { "added": [ "v10.6.0" ], "changes": [], "napiVersion": [ 4 ] }, "desc": "Function pointer used with asynchronous thread-safe function calls. The callback\nwill be called on the main thread. Its purpose is to use a data item arriving\nvia the queue from one of the secondary threads to construct the parameters\nnecessary for a call into JavaScript, usually via napi_call_function, and then\nmake the call into JavaScript.
The data arriving from the secondary thread via the queue is given in the data\nparameter and the JavaScript function to call is given in the js_callback\nparameter.
Node-API sets up the environment prior to calling this callback, so it is\nsufficient to call the JavaScript function via napi_call_function rather than\nvia napi_make_callback.
Callback functions must satisfy the following signature:
\ntypedef void (*napi_threadsafe_function_call_js)(napi_env env,\n napi_value js_callback,\n void* context,\n void* data);\n\n[in] env: The environment to use for API calls, or NULL if the thread-safe\nfunction is being torn down and data may need to be freed.[in] js_callback: The JavaScript function to call, or NULL if the\nthread-safe function is being torn down and data may need to be freed. It\nmay also be NULL if the thread-safe function was created without\njs_callback.[in] context: The optional data with which the thread-safe function was\ncreated.[in] data: Data created by the secondary thread. It is the responsibility of\nthe callback to convert this native data to JavaScript values (with Node-API\nfunctions) that can be passed as parameters when js_callback is invoked.\nThis pointer is managed entirely by the threads and this callback. Thus this\ncallback should free the data.Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.
", "displayName": "`napi_threadsafe_function_call_js`" }, { "textRaw": "`napi_cleanup_hook`", "name": "`napi_cleanup_hook`", "type": "module", "meta": { "added": [ "v19.2.0", "v18.13.0" ], "changes": [], "napiVersion": [ 3 ] }, "desc": "Function pointer used with napi_add_env_cleanup_hook. It will be called\nwhen the environment is being torn down.
Callback functions must satisfy the following signature:
\ntypedef void (*napi_cleanup_hook)(void* data);\n\n[in] data: The data that was passed to napi_add_env_cleanup_hook.Function pointer used with napi_add_async_cleanup_hook. It will be called\nwhen the environment is being torn down.
Callback functions must satisfy the following signature:
\ntypedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,\n void* data);\n\n[in] handle: The handle that must be passed to\nnapi_remove_async_cleanup_hook after completion of the asynchronous\ncleanup.[in] data: The data that was passed to napi_add_async_cleanup_hook.The body of the function should initiate the asynchronous cleanup actions at the\nend of which handle must be passed in a call to\nnapi_remove_async_cleanup_hook.
Node-API uses both return values and JavaScript exceptions for error handling.\nThe following sections explain the approach for each case.
", "modules": [ { "textRaw": "Return values", "name": "return_values", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "All of the Node-API functions share the same error handling pattern. The\nreturn type of all API functions is napi_status.
The return value will be napi_ok if the request was successful and\nno uncaught JavaScript exception was thrown. If an error occurred AND\nan exception was thrown, the napi_status value for the error\nwill be returned. If an exception was thrown, and no error occurred,\nnapi_pending_exception will be returned.
In cases where a return value other than napi_ok or\nnapi_pending_exception is returned, napi_is_exception_pending\nmust be called to check if an exception is pending.\nSee the section on exceptions for more details.
The full set of possible napi_status values is defined\nin napi_api_types.h.
The napi_status return value provides a VM-independent representation of\nthe error which occurred. In some cases it is useful to be able to get\nmore detailed information, including a string representing the error as well as\nVM (engine)-specific information.
In order to retrieve this information napi_get_last_error_info\nis provided which returns a napi_extended_error_info structure.\nThe format of the napi_extended_error_info structure is as follows:
typedef struct napi_extended_error_info {\n const char* error_message;\n void* engine_reserved;\n uint32_t engine_error_code;\n napi_status error_code;\n};\n\nerror_message: Textual representation of the error that occurred.engine_reserved: Opaque handle reserved for engine use only.engine_error_code: VM specific error code.error_code: Node-API status code for the last error.napi_get_last_error_info returns the information for the last\nNode-API call that was made.
Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.
", "modules": [ { "textRaw": "`napi_get_last_error_info`", "name": "`napi_get_last_error_info`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status\nnapi_get_last_error_info(node_api_basic_env env,\n const napi_extended_error_info** result);\n\n[in] env: The environment that the API is invoked under.[out] result: The napi_extended_error_info structure with more\ninformation about the error.Returns napi_ok if the API succeeded.
This API retrieves a napi_extended_error_info structure with information\nabout the last error that occurred.
The content of the napi_extended_error_info returned is only valid up until\na Node-API function is called on the same env. This includes a call to\nnapi_is_exception_pending so it may often be necessary to make a copy\nof the information so that it can be used later. The pointer returned\nin error_message points to a statically-defined string so it is safe to use\nthat pointer if you have copied it out of the error_message field (which will\nbe overwritten) before another Node-API function was called.
Do not rely on the content or format of any of the extended information as it\nis not subject to SemVer and may change at any time. It is intended only for\nlogging purposes.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_get_last_error_info`" } ], "displayName": "Return values" }, { "textRaw": "Exceptions", "name": "exceptions", "type": "module", "desc": "Any Node-API function call may result in a pending JavaScript exception. This is\nthe case for any of the API functions, even those that may not cause the\nexecution of JavaScript.
\nIf the napi_status returned by a function is napi_ok then no\nexception is pending and no additional action is required. If the\nnapi_status returned is anything other than napi_ok or\nnapi_pending_exception, in order to try to recover and continue\ninstead of simply returning immediately, napi_is_exception_pending\nmust be called in order to determine if an exception is pending or not.
In many cases when a Node-API function is called and an exception is\nalready pending, the function will return immediately with a\nnapi_status of napi_pending_exception. However, this is not the case\nfor all functions. Node-API allows a subset of the functions to be\ncalled to allow for some minimal cleanup before returning to JavaScript.\nIn that case, napi_status will reflect the status for the function. It\nwill not reflect previous pending exceptions. To avoid confusion, check\nthe error status after every function call.
When an exception is pending one of two approaches can be employed.
\nThe first approach is to do any appropriate cleanup and then return so that\nexecution will return to JavaScript. As part of the transition back to\nJavaScript, the exception will be thrown at the point in the JavaScript\ncode where the native method was invoked. The behavior of most Node-API calls\nis unspecified while an exception is pending, and many will simply return\nnapi_pending_exception, so do as little as possible and then return to\nJavaScript where the exception can be handled.
The second approach is to try to handle the exception. There will be cases\nwhere the native code can catch the exception, take the appropriate action,\nand then continue. This is only recommended in specific cases\nwhere it is known that the exception can be safely handled. In these\ncases napi_get_and_clear_last_exception can be used to get and\nclear the exception. On success, result will contain the handle to\nthe last JavaScript Object thrown. If it is determined, after\nretrieving the exception, the exception cannot be handled after all\nit can be re-thrown it with napi_throw where error is the\nJavaScript value to be thrown.
The following utility functions are also available in case native code\nneeds to throw an exception or determine if a napi_value is an instance\nof a JavaScript Error object: napi_throw_error,\nnapi_throw_type_error, napi_throw_range_error, node_api_throw_syntax_error and napi_is_error.
The following utility functions are also available in case native\ncode needs to create an Error object: napi_create_error,\nnapi_create_type_error, napi_create_range_error and node_api_create_syntax_error,\nwhere result is the napi_value that refers to the newly created\nJavaScript Error object.
The Node.js project is adding error codes to all of the errors\ngenerated internally. The goal is for applications to use these\nerror codes for all error checking. The associated error messages\nwill remain, but will only be meant to be used for logging and\ndisplay with the expectation that the message can change without\nSemVer applying. In order to support this model with Node-API, both\nin internal functionality and for module specific functionality\n(as its good practice), the throw_ and create_ functions\ntake an optional code parameter which is the string for the code\nto be added to the error object. If the optional parameter is NULL\nthen no code will be associated with the error. If a code is provided,\nthe name associated with the error is also updated to be:
originalName [code]\n\nwhere originalName is the original name associated with the error\nand code is the code that was provided. For example, if the code\nis 'ERR_ERROR_1' and a TypeError is being created the name will be:
TypeError [ERR_ERROR_1]\n",
"modules": [
{
"textRaw": "`napi_throw`",
"name": "`napi_throw`",
"type": "module",
"meta": {
"added": [
"v8.0.0"
],
"changes": [],
"napiVersion": [
1
]
},
"desc": "NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);\n\n[in] env: The environment that the API is invoked under.[in] error: The JavaScript value to be thrown.Returns napi_ok if the API succeeded.
This API throws the JavaScript value provided.
", "displayName": "`napi_throw`" }, { "textRaw": "`napi_throw_error`", "name": "`napi_throw_error`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_throw_error(napi_env env,\n const char* code,\n const char* msg);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.Returns napi_ok if the API succeeded.
This API throws a JavaScript Error with the text provided.
NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,\n const char* code,\n const char* msg);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.Returns napi_ok if the API succeeded.
This API throws a JavaScript TypeError with the text provided.
NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,\n const char* code,\n const char* msg);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.Returns napi_ok if the API succeeded.
This API throws a JavaScript RangeError with the text provided.
NAPI_EXTERN napi_status node_api_throw_syntax_error(napi_env env,\n const char* code,\n const char* msg);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional error code to be set on the error.[in] msg: C string representing the text to be associated with the error.Returns napi_ok if the API succeeded.
This API throws a JavaScript SyntaxError with the text provided.
NAPI_EXTERN napi_status napi_is_error(napi_env env,\n napi_value value,\n bool* result);\n\n[in] env: The environment that the API is invoked under.[in] value: The napi_value to be checked.[out] result: Boolean value that is set to true if napi_value represents\nan error, false otherwise.Returns napi_ok if the API succeeded.
This API queries a napi_value to check if it represents an error object.
NAPI_EXTERN napi_status napi_create_error(napi_env env,\n napi_value code,\n napi_value msg,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional napi_value with the string for the error code to be\nassociated with the error.[in] msg: napi_value that references a JavaScript string to be used as\nthe message for the Error.[out] result: napi_value representing the error created.Returns napi_ok if the API succeeded.
This API returns a JavaScript Error with the text provided.
NAPI_EXTERN napi_status napi_create_type_error(napi_env env,\n napi_value code,\n napi_value msg,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional napi_value with the string for the error code to be\nassociated with the error.[in] msg: napi_value that references a JavaScript string to be used as\nthe message for the Error.[out] result: napi_value representing the error created.Returns napi_ok if the API succeeded.
This API returns a JavaScript TypeError with the text provided.
NAPI_EXTERN napi_status napi_create_range_error(napi_env env,\n napi_value code,\n napi_value msg,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional napi_value with the string for the error code to be\nassociated with the error.[in] msg: napi_value that references a JavaScript string to be used as\nthe message for the Error.[out] result: napi_value representing the error created.Returns napi_ok if the API succeeded.
This API returns a JavaScript RangeError with the text provided.
NAPI_EXTERN napi_status node_api_create_syntax_error(napi_env env,\n napi_value code,\n napi_value msg,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] code: Optional napi_value with the string for the error code to be\nassociated with the error.[in] msg: napi_value that references a JavaScript string to be used as\nthe message for the Error.[out] result: napi_value representing the error created.Returns napi_ok if the API succeeded.
This API returns a JavaScript SyntaxError with the text provided.
napi_status napi_get_and_clear_last_exception(napi_env env,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[out] result: The exception if one is pending, NULL otherwise.Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_get_and_clear_last_exception`" }, { "textRaw": "`napi_is_exception_pending`", "name": "`napi_is_exception_pending`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_is_exception_pending(napi_env env, bool* result);\n\n[in] env: The environment that the API is invoked under.[out] result: Boolean value that is set to true if an exception is pending.Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_is_exception_pending`" }, { "textRaw": "`napi_fatal_exception`", "name": "`napi_fatal_exception`", "type": "module", "meta": { "added": [ "v9.10.0" ], "changes": [], "napiVersion": [ 3 ] }, "desc": "napi_status napi_fatal_exception(napi_env env, napi_value err);\n\n[in] env: The environment that the API is invoked under.[in] err: The error that is passed to 'uncaughtException'.Trigger an 'uncaughtException' in JavaScript. Useful if an async\ncallback throws an exception with no way to recover.
In the event of an unrecoverable error in a native addon, a fatal error can be\nthrown to immediately terminate the process.
", "modules": [ { "textRaw": "`napi_fatal_error`", "name": "`napi_fatal_error`", "type": "module", "meta": { "added": [ "v8.2.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_NO_RETURN void napi_fatal_error(const char* location,\n size_t location_len,\n const char* message,\n size_t message_len);\n\n[in] location: Optional location at which the error occurred.[in] location_len: The length of the location in bytes, or\nNAPI_AUTO_LENGTH if it is null-terminated.[in] message: The message associated with the error.[in] message_len: The length of the message in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.The function call does not return, the process will be terminated.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_fatal_error`" } ], "displayName": "Fatal errors" } ], "displayName": "Error handling" }, { "textRaw": "Object lifetime management", "name": "object_lifetime_management", "type": "misc", "desc": "As Node-API calls are made, handles to objects in the heap for the underlying\nVM may be returned as napi_values. These handles must hold the\nobjects 'live' until they are no longer required by the native code,\notherwise the objects could be collected before the native code was\nfinished using them.
As object handles are returned they are associated with a\n'scope'. The lifespan for the default scope is tied to the lifespan\nof the native method call. The result is that, by default, handles\nremain valid and the objects associated with these handles will be\nheld live for the lifespan of the native method call.
\nIn many cases, however, it is necessary that the handles remain valid for\neither a shorter or longer lifespan than that of the native method.\nThe sections which follow describe the Node-API functions that can be used\nto change the handle lifespan from the default.
", "modules": [ { "textRaw": "Making handle lifespan shorter than that of the native method", "name": "making_handle_lifespan_shorter_than_that_of_the_native_method", "type": "module", "desc": "It is often necessary to make the lifespan of handles shorter than\nthe lifespan of a native method. For example, consider a native method\nthat has a loop which iterates through the elements in a large array:
\nfor (int i = 0; i < 1000000; i++) {\n napi_value result;\n napi_status status = napi_get_element(env, object, i, &result);\n if (status != napi_ok) {\n break;\n }\n // do something with element\n}\n\nThis would result in a large number of handles being created, consuming\nsubstantial resources. In addition, even though the native code could only\nuse the most recent handle, all of the associated objects would also be\nkept alive since they all share the same scope.
\nTo handle this case, Node-API provides the ability to establish a new 'scope' to\nwhich newly created handles will be associated. Once those handles\nare no longer required, the scope can be 'closed' and any handles associated\nwith the scope are invalidated. The methods available to open/close scopes are\nnapi_open_handle_scope and napi_close_handle_scope.
Node-API only supports a single nested hierarchy of scopes. There is only one\nactive scope at any time, and all new handles will be associated with that\nscope while it is active. Scopes must be closed in the reverse order from\nwhich they are opened. In addition, all scopes created within a native method\nmust be closed before returning from that method.
\nTaking the earlier example, adding calls to napi_open_handle_scope and\nnapi_close_handle_scope would ensure that at most a single handle\nis valid throughout the execution of the loop:
for (int i = 0; i < 1000000; i++) {\n napi_handle_scope scope;\n napi_status status = napi_open_handle_scope(env, &scope);\n if (status != napi_ok) {\n break;\n }\n napi_value result;\n status = napi_get_element(env, object, i, &result);\n if (status != napi_ok) {\n break;\n }\n // do something with element\n status = napi_close_handle_scope(env, scope);\n if (status != napi_ok) {\n break;\n }\n}\n\nWhen nesting scopes, there are cases where a handle from an\ninner scope needs to live beyond the lifespan of that scope. Node-API supports\nan 'escapable scope' in order to support this case. An escapable scope\nallows one handle to be 'promoted' so that it 'escapes' the\ncurrent scope and the lifespan of the handle changes from the current\nscope to that of the outer scope.
\nThe methods available to open/close escapable scopes are\nnapi_open_escapable_handle_scope and\nnapi_close_escapable_handle_scope.
The request to promote a handle is made through napi_escape_handle which\ncan only be called once.
NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,\n napi_handle_scope* result);\n\n[in] env: The environment that the API is invoked under.[out] result: napi_value representing the new scope.Returns napi_ok if the API succeeded.
This API opens a new scope.
", "displayName": "`napi_open_handle_scope`" }, { "textRaw": "`napi_close_handle_scope`", "name": "`napi_close_handle_scope`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,\n napi_handle_scope scope);\n\n[in] env: The environment that the API is invoked under.[in] scope: napi_value representing the scope to be closed.Returns napi_ok if the API succeeded.
This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_close_handle_scope`" }, { "textRaw": "`napi_open_escapable_handle_scope`", "name": "`napi_open_escapable_handle_scope`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status\n napi_open_escapable_handle_scope(napi_env env,\n napi_handle_scope* result);\n\n[in] env: The environment that the API is invoked under.[out] result: napi_value representing the new scope.Returns napi_ok if the API succeeded.
This API opens a new scope from which one object can be promoted\nto the outer scope.
", "displayName": "`napi_open_escapable_handle_scope`" }, { "textRaw": "`napi_close_escapable_handle_scope`", "name": "`napi_close_escapable_handle_scope`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status\n napi_close_escapable_handle_scope(napi_env env,\n napi_handle_scope scope);\n\n[in] env: The environment that the API is invoked under.[in] scope: napi_value representing the scope to be closed.Returns napi_ok if the API succeeded.
This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_close_escapable_handle_scope`" }, { "textRaw": "`napi_escape_handle`", "name": "`napi_escape_handle`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_escape_handle(napi_env env,\n napi_escapable_handle_scope scope,\n napi_value escapee,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] scope: napi_value representing the current scope.[in] escapee: napi_value representing the JavaScript Object to be\nescaped.[out] result: napi_value representing the handle to the escaped Object\nin the outer scope.Returns napi_ok if the API succeeded.
This API promotes the handle to the JavaScript object so that it is valid\nfor the lifetime of the outer scope. It can only be called once per scope.\nIf it is called more than once an error will be returned.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_escape_handle`" } ], "displayName": "Making handle lifespan shorter than that of the native method" }, { "textRaw": "References to values with a lifespan longer than that of the native method", "name": "references_to_values_with_a_lifespan_longer_than_that_of_the_native_method", "type": "module", "desc": "In some cases, an addon will need to be able to create and reference values\nwith a lifespan longer than that of a single native method invocation. For\nexample, to create a constructor and later use that constructor\nin a request to create instances, it must be possible to reference\nthe constructor object across many different instance creation requests. This\nwould not be possible with a normal handle returned as a napi_value as\ndescribed in the earlier section. The lifespan of a normal handle is\nmanaged by scopes and all scopes must be closed before the end of a native\nmethod.
Node-API provides methods for creating persistent references to values.\nCurrently Node-API only allows references to be created for a\nlimited set of value types, including object, external, function, and symbol.
\nEach reference has an associated count with a value of 0 or higher,\nwhich determines whether the reference will keep the corresponding value alive.\nReferences with a count of 0 do not prevent values from being collected.\nValues of object (object, function, external) and symbol types are becoming\n'weak' references and can still be accessed while they are not collected.\nAny count greater than 0 will prevent the values from being collected.
\nSymbol values have different flavors. The true weak reference behavior is\nonly supported by local symbols created with the napi_create_symbol function\nor the JavaScript Symbol() constructor calls. Globally registered symbols\ncreated with the node_api_symbol_for function or JavaScript Symbol.for()\nfunction calls remain always strong references because the garbage collector\ndoes not collect them. The same is true for well-known symbols such as\nSymbol.iterator. They are also never collected by the garbage collector.
References can be created with an initial reference count. The count can\nthen be modified through napi_reference_ref and\nnapi_reference_unref. If an object is collected while the count\nfor a reference is 0, all subsequent calls to\nget the object associated with the reference napi_get_reference_value\nwill return NULL for the returned napi_value. An attempt to call\nnapi_reference_ref for a reference whose object has been collected\nresults in an error.
References must be deleted once they are no longer required by the addon. When\na reference is deleted, it will no longer prevent the corresponding object from\nbeing collected. Failure to delete a persistent reference results in\na 'memory leak' with both the native memory for the persistent reference and\nthe corresponding object on the heap being retained forever.
\nThere can be multiple persistent references created which refer to the same\nobject, each of which will either keep the object live or not based on its\nindividual count. Multiple persistent references to the same object\ncan result in unexpectedly keeping alive native memory. The native structures\nfor a persistent reference must be kept alive until finalizers for the\nreferenced object are executed. If a new persistent reference is created\nfor the same object, the finalizers for that object will not be\nrun and the native memory pointed by the earlier persistent reference\nwill not be freed. This can be avoided by calling\nnapi_delete_reference in addition to napi_reference_unref when possible.
Change History:
\nVersion 10 (NAPI_VERSION is defined as 10 or higher):
References can be created for all value types. The new supported value\ntypes do not support weak reference semantic and the values of these types\nare released when the reference count becomes 0 and cannot be accessed from\nthe reference anymore.
\nNAPI_EXTERN napi_status napi_create_reference(napi_env env,\n napi_value value,\n uint32_t initial_refcount,\n napi_ref* result);\n\n[in] env: The environment that the API is invoked under.[in] value: The napi_value for which a reference is being created.[in] initial_refcount: Initial reference count for the new reference.[out] result: napi_ref pointing to the new reference.Returns napi_ok if the API succeeded.
This API creates a new reference with the specified reference count\nto the value passed in.
", "displayName": "`napi_create_reference`" }, { "textRaw": "`napi_delete_reference`", "name": "`napi_delete_reference`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);\n\n[in] env: The environment that the API is invoked under.[in] ref: napi_ref to be deleted.Returns napi_ok if the API succeeded.
This API deletes the reference passed in.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_delete_reference`" }, { "textRaw": "`napi_reference_ref`", "name": "`napi_reference_ref`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_reference_ref(napi_env env,\n napi_ref ref,\n uint32_t* result);\n\n[in] env: The environment that the API is invoked under.[in] ref: napi_ref for which the reference count will be incremented.[out] result: The new reference count.Returns napi_ok if the API succeeded.
This API increments the reference count for the reference\npassed in and returns the resulting reference count.
", "displayName": "`napi_reference_ref`" }, { "textRaw": "`napi_reference_unref`", "name": "`napi_reference_unref`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_reference_unref(napi_env env,\n napi_ref ref,\n uint32_t* result);\n\n[in] env: The environment that the API is invoked under.[in] ref: napi_ref for which the reference count will be decremented.[out] result: The new reference count.Returns napi_ok if the API succeeded.
This API decrements the reference count for the reference\npassed in and returns the resulting reference count.
", "displayName": "`napi_reference_unref`" }, { "textRaw": "`napi_get_reference_value`", "name": "`napi_get_reference_value`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,\n napi_ref ref,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] ref: The napi_ref for which the corresponding value is\nbeing requested.[out] result: The napi_value referenced by the napi_ref.Returns napi_ok if the API succeeded.
If still valid, this API returns the napi_value representing the\nJavaScript value associated with the napi_ref. Otherwise, result\nwill be NULL.
While a Node.js process typically releases all its resources when exiting,\nembedders of Node.js, or future Worker support, may require addons to register\nclean-up hooks that will be run once the current Node.js environment exits.
\nNode-API provides functions for registering and un-registering such callbacks.\nWhen those callbacks are run, all resources that are being held by the addon\nshould be freed up.
", "modules": [ { "textRaw": "`napi_add_env_cleanup_hook`", "name": "`napi_add_env_cleanup_hook`", "type": "module", "meta": { "added": [ "v10.2.0" ], "changes": [], "napiVersion": [ 3 ] }, "desc": "NODE_EXTERN napi_status napi_add_env_cleanup_hook(node_api_basic_env env,\n napi_cleanup_hook fun,\n void* arg);\n\nRegisters fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits.
A function can safely be specified multiple times with different\narg values. In that case, it will be called multiple times as well.\nProviding the same fun and arg values multiple times is not allowed\nand will lead the process to abort.
The hooks will be called in reverse order, i.e. the most recently added one\nwill be called first.
\nRemoving this hook can be done by using napi_remove_env_cleanup_hook.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.
For asynchronous cleanup, napi_add_async_cleanup_hook is available.
NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(node_api_basic_env env,\n void (*fun)(void* arg),\n void* arg);\n\nUnregisters fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits. Both the argument and the function value\nneed to be exact matches.
The function must have originally been registered\nwith napi_add_env_cleanup_hook, otherwise the process will abort.
NAPI_EXTERN napi_status napi_add_async_cleanup_hook(\n node_api_basic_env env,\n napi_async_cleanup_hook hook,\n void* arg,\n napi_async_cleanup_hook_handle* remove_handle);\n\n[in] env: The environment that the API is invoked under.[in] hook: The function pointer to call at environment teardown.[in] arg: The pointer to pass to hook when it gets called.[out] remove_handle: Optional handle that refers to the asynchronous cleanup\nhook.Registers hook, which is a function of type napi_async_cleanup_hook, as\na function to be run with the remove_handle and arg parameters once the\ncurrent Node.js environment exits.
Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.
Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.
If remove_handle is not NULL, an opaque value will be stored in it\nthat must later be passed to napi_remove_async_cleanup_hook,\nregardless of whether the hook has already been invoked.\nTypically, that happens when the resource for which this hook was added\nis being torn down anyway.
NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(\n napi_async_cleanup_hook_handle remove_handle);\n\n[in] remove_handle: The handle to an asynchronous cleanup hook that was\ncreated with napi_add_async_cleanup_hook.Unregisters the cleanup hook corresponding to remove_handle. This will prevent\nthe hook from being executed, unless it has already started executing.\nThis must be called on any napi_async_cleanup_hook_handle value obtained\nfrom napi_add_async_cleanup_hook.
The Node.js environment may be torn down at an arbitrary time as soon as\npossible with JavaScript execution disallowed, like on the request of\nworker.terminate(). When the environment is being torn down, the\nregistered napi_finalize callbacks of JavaScript objects, thread-safe\nfunctions and environment instance data are invoked immediately and\nindependently.
The invocation of napi_finalize callbacks is scheduled after the manually\nregistered cleanup hooks. In order to ensure a proper order of addon\nfinalization during environment shutdown to avoid use-after-free in the\nnapi_finalize callback, addons should register a cleanup hook with\nnapi_add_env_cleanup_hook and napi_add_async_cleanup_hook to manually\nrelease the allocated resource in a proper order.
Node-API modules are registered in a manner similar to other modules\nexcept that instead of using the NODE_MODULE macro the following\nis used:
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n\nThe next difference is the signature for the Init method. For a Node-API\nmodule it is as follows:
napi_value Init(napi_env env, napi_value exports);\n\nThe return value from Init is treated as the exports object for the module.\nThe Init method is passed an empty object via the exports parameter as a\nconvenience. If Init returns NULL, the parameter passed as exports is\nexported by the module. Node-API modules cannot modify the module object but\ncan specify anything as the exports property of the module.
To add the method hello as a function so that it can be called as a method\nprovided by the addon:
napi_value Init(napi_env env, napi_value exports) {\n napi_status status;\n napi_property_descriptor desc = {\n \"hello\",\n NULL,\n Method,\n NULL,\n NULL,\n NULL,\n napi_writable | napi_enumerable | napi_configurable,\n NULL\n };\n status = napi_define_properties(env, exports, 1, &desc);\n if (status != napi_ok) return NULL;\n return exports;\n}\n\nTo set a function to be returned by the require() for the addon:
napi_value Init(napi_env env, napi_value exports) {\n napi_value method;\n napi_status status;\n status = napi_create_function(env, \"exports\", NAPI_AUTO_LENGTH, Method, NULL, &method);\n if (status != napi_ok) return NULL;\n return method;\n}\n\nTo define a class so that new instances can be created (often used with\nObject wrap):
\n// NOTE: partial example, not all referenced code is included\nnapi_value Init(napi_env env, napi_value exports) {\n napi_status status;\n napi_property_descriptor properties[] = {\n { \"value\", NULL, NULL, GetValue, SetValue, NULL, napi_writable | napi_configurable, NULL },\n DECLARE_NAPI_METHOD(\"plusOne\", PlusOne),\n DECLARE_NAPI_METHOD(\"multiply\", Multiply),\n };\n\n napi_value cons;\n status =\n napi_define_class(env, \"MyObject\", New, NULL, 3, properties, &cons);\n if (status != napi_ok) return NULL;\n\n status = napi_create_reference(env, cons, 1, &constructor);\n if (status != napi_ok) return NULL;\n\n status = napi_set_named_property(env, exports, \"MyObject\", cons);\n if (status != napi_ok) return NULL;\n\n return exports;\n}\n\nYou can also use the NAPI_MODULE_INIT macro, which acts as a shorthand\nfor NAPI_MODULE and defining an Init function:
NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) {\n napi_value answer;\n napi_status result;\n\n status = napi_create_int64(env, 42, &answer);\n if (status != napi_ok) return NULL;\n\n status = napi_set_named_property(env, exports, \"answer\", answer);\n if (status != napi_ok) return NULL;\n\n return exports;\n}\n\nThe parameters env and exports are provided to the body of the\nNAPI_MODULE_INIT macro.
All Node-API addons are context-aware, meaning they may be loaded multiple\ntimes. There are a few design considerations when declaring such a module.\nThe documentation on context-aware addons provides more details.
\nThe variables env and exports will be available inside the function body\nfollowing the macro invocation.
For more details on setting properties on objects, see the section on\nWorking with JavaScript properties.
\nFor more details on building addon modules in general, refer to the existing\nAPI.
", "displayName": "Module registration" }, { "textRaw": "Working with JavaScript values", "name": "working_with_javascript_values", "type": "misc", "desc": "Node-API exposes a set of APIs to create all types of JavaScript values.\nSome of these types are documented under Section language types\nof the ECMAScript Language Specification.
\nFundamentally, these APIs are used to do one of the following:
\nundefined and nullNode-API values are represented by the type napi_value.\nAny Node-API call that requires a JavaScript value takes in a napi_value.\nIn some cases, the API does check the type of the napi_value up-front.\nHowever, for better performance, it's better for the caller to make sure that\nthe napi_value in question is of the JavaScript type expected by the API.
typedef enum {\n napi_key_include_prototypes,\n napi_key_own_only\n} napi_key_collection_mode;\n\nDescribes the Keys/Properties filter enums:
napi_key_collection_mode limits the range of collected properties.
napi_key_own_only limits the collected properties to the given\nobject only. napi_key_include_prototypes will include all keys\nof the objects's prototype chain as well.
typedef enum {\n napi_key_all_properties = 0,\n napi_key_writable = 1,\n napi_key_enumerable = 1 << 1,\n napi_key_configurable = 1 << 2,\n napi_key_skip_strings = 1 << 3,\n napi_key_skip_symbols = 1 << 4\n} napi_key_filter;\n\nProperty filter bit flag. This works with bit operators to build a composite filter.
", "displayName": "`napi_key_filter`" }, { "textRaw": "`napi_key_conversion`", "name": "`napi_key_conversion`", "type": "module", "meta": { "added": [ "v13.7.0", "v12.17.0", "v10.20.0" ], "changes": [], "napiVersion": [ 6 ] }, "desc": "typedef enum {\n napi_key_keep_numbers,\n napi_key_numbers_to_strings\n} napi_key_conversion;\n\nnapi_key_numbers_to_strings will convert integer indexes to\nstrings. napi_key_keep_numbers will return numbers for integer\nindexes.
typedef enum {\n // ES6 types (corresponds to typeof)\n napi_undefined,\n napi_null,\n napi_boolean,\n napi_number,\n napi_string,\n napi_symbol,\n napi_object,\n napi_function,\n napi_external,\n napi_bigint,\n} napi_valuetype;\n\nDescribes the type of a napi_value. This generally corresponds to the types\ndescribed in Section language types of the ECMAScript Language Specification.\nIn addition to types in that section, napi_valuetype can also represent\nFunctions and Objects with external data.
A JavaScript value of type napi_external appears in JavaScript as a plain\nobject such that no properties can be set on it, and no prototype.
typedef enum {\n napi_int8_array,\n napi_uint8_array,\n napi_uint8_clamped_array,\n napi_int16_array,\n napi_uint16_array,\n napi_int32_array,\n napi_uint32_array,\n napi_float32_array,\n napi_float64_array,\n napi_bigint64_array,\n napi_biguint64_array,\n napi_float16_array,\n} napi_typedarray_type;\n\nThis represents the underlying binary scalar datatype of the TypedArray.\nElements of this enum correspond to\nSection TypedArray objects of the ECMAScript Language Specification.
napi_status napi_create_array(napi_env env, napi_value* result)\n\n[in] env: The environment that the Node-API call is invoked under.[out] result: A napi_value representing a JavaScript Array.Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript Array type.\nJavaScript arrays are described in\nSection Array objects of the ECMAScript Language Specification.
napi_status napi_create_array_with_length(napi_env env,\n size_t length,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] length: The initial length of the Array.[out] result: A napi_value representing a JavaScript Array.Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript Array type.\nThe Array's length property is set to the passed-in length parameter.\nHowever, the underlying buffer is not guaranteed to be pre-allocated by the VM\nwhen the array is created. That behavior is left to the underlying VM\nimplementation. If the buffer must be a contiguous block of memory that can be\ndirectly read and/or written via C, consider using\nnapi_create_external_arraybuffer.
JavaScript arrays are described in\nSection Array objects of the ECMAScript Language Specification.
", "displayName": "`napi_create_array_with_length`" }, { "textRaw": "`napi_create_arraybuffer`", "name": "`napi_create_arraybuffer`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_create_arraybuffer(napi_env env,\n size_t byte_length,\n void** data,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] length: The length in bytes of the array buffer to create.[out] data: Pointer to the underlying byte buffer of the ArrayBuffer.\ndata can optionally be ignored by passing NULL.[out] result: A napi_value representing a JavaScript ArrayBuffer.Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript ArrayBuffer.\nArrayBuffers are used to represent fixed-length binary data buffers. They are\nnormally used as a backing-buffer for TypedArray objects.\nThe ArrayBuffer allocated will have an underlying byte buffer whose size is\ndetermined by the length parameter that's passed in.\nThe underlying buffer is optionally returned back to the caller in case the\ncaller wants to directly manipulate the buffer. This buffer can only be\nwritten to directly from native code. To write to this buffer from JavaScript,\na typed array or DataView object would need to be created.
JavaScript ArrayBuffer objects are described in\nSection ArrayBuffer objects of the ECMAScript Language Specification.
napi_status napi_create_buffer(napi_env env,\n size_t size,\n void** data,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] size: Size in bytes of the underlying buffer.[out] data: Raw pointer to the underlying buffer.\ndata can optionally be ignored by passing NULL.[out] result: A napi_value representing a node::Buffer.Returns napi_ok if the API succeeded.
This API allocates a node::Buffer object. While this is still a\nfully-supported data structure, in most cases using a TypedArray will suffice.
napi_status napi_create_buffer_copy(napi_env env,\n size_t length,\n const void* data,\n void** result_data,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] size: Size in bytes of the input buffer (should be the same as the size\nof the new buffer).[in] data: Raw pointer to the underlying buffer to copy from.[out] result_data: Pointer to the new Buffer's underlying data buffer.\nresult_data can optionally be ignored by passing NULL.[out] result: A napi_value representing a node::Buffer.Returns napi_ok if the API succeeded.
This API allocates a node::Buffer object and initializes it with data copied\nfrom the passed-in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.
napi_status napi_create_date(napi_env env,\n double time,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] time: ECMAScript time value in milliseconds since 01 January, 1970 UTC.[out] result: A napi_value representing a JavaScript Date.Returns napi_ok if the API succeeded.
This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.
\nThis API allocates a JavaScript Date object.
JavaScript Date objects are described in\nSection Date objects of the ECMAScript Language Specification.
napi_status napi_create_external(napi_env env,\n void* data,\n napi_finalize finalize_cb,\n void* finalize_hint,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] data: Raw pointer to the external data.[in] finalize_cb: Optional callback to call when the external value is being\ncollected. napi_finalize provides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.[out] result: A napi_value representing an external value.Returns napi_ok if the API succeeded.
This API allocates a JavaScript value with external data attached to it. This\nis used to pass external data through JavaScript code, so it can be retrieved\nlater by native code using napi_get_value_external.
The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created has been garbage collected.
The created value is not an object, and therefore does not support additional\nproperties. It is considered a distinct value type: calling napi_typeof() with\nan external value yields napi_external.
napi_status\nnapi_create_external_arraybuffer(napi_env env,\n void* external_data,\n size_t byte_length,\n napi_finalize finalize_cb,\n void* finalize_hint,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] external_data: Pointer to the underlying byte buffer of the\nArrayBuffer.[in] byte_length: The length in bytes of the underlying buffer.[in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.[out] result: A napi_value representing a JavaScript ArrayBuffer.Returns napi_ok if the API succeeded.
Some runtimes other than Node.js have dropped support for external buffers.\nOn runtimes other than Node.js this method may return\nnapi_no_external_buffers_allowed to indicate that external\nbuffers are not supported. One such runtime is Electron as\ndescribed in this issue\nelectron/issues/35801.
In order to maintain broadest compatibility with all runtimes\nyou may define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED in your addon before\nincludes for the node-api headers. Doing so will hide the 2 functions\nthat create external buffers. This will ensure a compilation error\noccurs if you accidentally use one of these methods.
This API returns a Node-API value corresponding to a JavaScript ArrayBuffer.\nThe underlying byte buffer of the ArrayBuffer is externally allocated and\nmanaged. The caller must ensure that the byte buffer remains valid until the\nfinalize callback is called.
The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created has been garbage collected.
JavaScript ArrayBuffers are described in\nSection ArrayBuffer objects of the ECMAScript Language Specification.
napi_status napi_create_external_buffer(napi_env env,\n size_t length,\n void* data,\n napi_finalize finalize_cb,\n void* finalize_hint,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] length: Size in bytes of the input buffer (should be the same as the\nsize of the new buffer).[in] data: Raw pointer to the underlying buffer to expose to JavaScript.[in] finalize_cb: Optional callback to call when the ArrayBuffer is being\ncollected. napi_finalize provides more details.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.[out] result: A napi_value representing a node::Buffer.Returns napi_ok if the API succeeded.
Some runtimes other than Node.js have dropped support for external buffers.\nOn runtimes other than Node.js this method may return\nnapi_no_external_buffers_allowed to indicate that external\nbuffers are not supported. One such runtime is Electron as\ndescribed in this issue\nelectron/issues/35801.
In order to maintain broadest compatibility with all runtimes\nyou may define NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED in your addon before\nincludes for the node-api headers. Doing so will hide the 2 functions\nthat create external buffers. This will ensure a compilation error\noccurs if you accidentally use one of these methods.
This API allocates a node::Buffer object and initializes it with data\nbacked by the passed in buffer. While this is still a fully-supported data\nstructure, in most cases using a TypedArray will suffice.
The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created has been garbage collected.
For Node.js >=4 Buffers are Uint8Arrays.
napi_status napi_create_object(napi_env env, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[out] result: A napi_value representing a JavaScript Object.Returns napi_ok if the API succeeded.
This API allocates a default JavaScript Object.\nIt is the equivalent of doing new Object() in JavaScript.
The JavaScript Object type is described in Section object type of the\nECMAScript Language Specification.
napi_status node_api_create_object_with_properties(napi_env env,\n napi_value prototype_or_null,\n const napi_value* property_names,\n const napi_value* property_values,\n size_t property_count,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] prototype_or_null: The prototype object for the new object. Can be a\nnapi_value representing a JavaScript object to use as the prototype, a\nnapi_value representing JavaScript null, or a nullptr that will be converted to null.[in] property_names: Array of napi_value representing the property names.[in] property_values: Array of napi_value representing the property values.[in] property_count: Number of properties in the arrays.[out] result: A napi_value representing a JavaScript Object.Returns napi_ok if the API succeeded.
This API creates a JavaScript Object with the specified prototype and\nproperties. This is more efficient than calling napi_create_object followed\nby multiple napi_set_property calls, as it can create the object with all\nproperties atomically, avoiding potential V8 map transitions.
The arrays property_names and property_values must have the same length\nspecified by property_count. The properties are added to the object in the\norder they appear in the arrays.
napi_status napi_create_symbol(napi_env env,\n napi_value description,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] description: Optional napi_value which refers to a JavaScript\nstring to be set as the description for the symbol.[out] result: A napi_value representing a JavaScript symbol.Returns napi_ok if the API succeeded.
This API creates a JavaScript symbol value from a UTF8-encoded C string.
The JavaScript symbol type is described in Section symbol type\nof the ECMAScript Language Specification.
napi_status node_api_symbol_for(napi_env env,\n const char* utf8description,\n size_t length,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] utf8description: UTF-8 C string representing the text to be used as the\ndescription for the symbol.[in] length: The length of the description string in bytes, or\nNAPI_AUTO_LENGTH if it is null-terminated.[out] result: A napi_value representing a JavaScript symbol.Returns napi_ok if the API succeeded.
This API searches in the global registry for an existing symbol with the given\ndescription. If the symbol already exists it will be returned, otherwise a new\nsymbol will be created in the registry.
\nThe JavaScript symbol type is described in Section symbol type of the ECMAScript\nLanguage Specification.
napi_status napi_create_typedarray(napi_env env,\n napi_typedarray_type type,\n size_t length,\n napi_value arraybuffer,\n size_t byte_offset,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] type: Scalar datatype of the elements within the TypedArray.[in] length: Number of elements in the TypedArray.[in] arraybuffer: ArrayBuffer underlying the typed array.[in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the TypedArray.[out] result: A napi_value representing a JavaScript TypedArray.Returns napi_ok if the API succeeded.
This API creates a JavaScript TypedArray object over an existing\nArrayBuffer. TypedArray objects provide an array-like view over an\nunderlying data buffer where each element has the same underlying binary scalar\ndatatype.
It's required that (length * size_of_element) + byte_offset should\nbe <= the size in bytes of the array passed in. If not, a RangeError exception\nis raised.
JavaScript TypedArray objects are described in\nSection TypedArray objects of the ECMAScript Language Specification.
napi_status NAPI_CDECL node_api_create_buffer_from_arraybuffer(napi_env env,\n napi_value arraybuffer,\n size_t byte_offset,\n size_t byte_length,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] arraybuffer: The ArrayBuffer from which the buffer will be created.[in] byte_offset: The byte offset within the ArrayBuffer from which to start creating the buffer.[in] byte_length: The length in bytes of the buffer to be created from the ArrayBuffer.[out] result: A napi_value representing the created JavaScript Buffer object.Returns napi_ok if the API succeeded.
This API creates a JavaScript Buffer object from an existing ArrayBuffer.\nThe Buffer object is a Node.js-specific class that provides a way to work with binary data directly in JavaScript.
The byte range [byte_offset, byte_offset + byte_length)\nmust be within the bounds of the ArrayBuffer. If byte_offset + byte_length\nexceeds the size of the ArrayBuffer, a RangeError exception is raised.
napi_status napi_create_dataview(napi_env env,\n size_t byte_length,\n napi_value arraybuffer,\n size_t byte_offset,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] length: Number of elements in the DataView.[in] arraybuffer: ArrayBuffer or SharedArrayBuffer underlying the\nDataView.[in] byte_offset: The byte offset within the ArrayBuffer from which to\nstart projecting the DataView.[out] result: A napi_value representing a JavaScript DataView.Returns napi_ok if the API succeeded.
This API creates a JavaScript DataView object over an existing ArrayBuffer\nor SharedArrayBuffer. DataView objects provide an array-like view over an\nunderlying data buffer, but one which allows items of different size and type in\nthe ArrayBuffer or SharedArrayBuffer.
It is required that byte_length + byte_offset is less than or equal to the\nsize in bytes of the array passed in. If not, a RangeError exception is\nraised.
JavaScript DataView objects are described in\nSection DataView objects of the ECMAScript Language Specification.
napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript number.Returns napi_ok if the API succeeded.
This API is used to convert from the C int32_t type to the JavaScript\nnumber type.
The JavaScript number type is described in\nSection number type of the ECMAScript Language Specification.
napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: Unsigned integer value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript number.Returns napi_ok if the API succeeded.
This API is used to convert from the C uint32_t type to the JavaScript\nnumber type.
The JavaScript number type is described in\nSection number type of the ECMAScript Language Specification.
napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript number.Returns napi_ok if the API succeeded.
This API is used to convert from the C int64_t type to the JavaScript\nnumber type.
The JavaScript number type is described in Section number type\nof the ECMAScript Language Specification. Note the complete range of int64_t\ncannot be represented with full precision in JavaScript. Integer values\noutside the range of Number.MIN_SAFE_INTEGER -(2**53 - 1) -\nNumber.MAX_SAFE_INTEGER (2**53 - 1) will lose precision.
napi_status napi_create_double(napi_env env, double value, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: Double-precision value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript number.Returns napi_ok if the API succeeded.
This API is used to convert from the C double type to the JavaScript\nnumber type.
The JavaScript number type is described in\nSection number type of the ECMAScript Language Specification.
napi_status napi_create_bigint_int64(napi_env env,\n int64_t value,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] value: Integer value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript BigInt.Returns napi_ok if the API succeeded.
This API converts the C int64_t type to the JavaScript BigInt type.
napi_status napi_create_bigint_uint64(napi_env env,\n uint64_t value,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] value: Unsigned integer value to be represented in JavaScript.[out] result: A napi_value representing a JavaScript BigInt.Returns napi_ok if the API succeeded.
This API converts the C uint64_t type to the JavaScript BigInt type.
napi_status napi_create_bigint_words(napi_env env,\n int sign_bit,\n size_t word_count,\n const uint64_t* words,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] sign_bit: Determines if the resulting BigInt will be positive or\nnegative.[in] word_count: The length of the words array.[in] words: An array of uint64_t little-endian 64-bit words.[out] result: A napi_value representing a JavaScript BigInt.Returns napi_ok if the API succeeded.
This API converts an array of unsigned 64-bit words into a single BigInt\nvalue.
The resulting BigInt is calculated as: (–1)sign_bit (words[0]\n× (264)0 + words[1] × (264)1 + …)
napi_status napi_create_string_latin1(napi_env env,\n const char* str,\n size_t length,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.[out] result: A napi_value representing a JavaScript string.Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from an ISO-8859-1-encoded C\nstring. The native string is copied.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status\nnode_api_create_external_string_latin1(napi_env env,\n char* str,\n size_t length,\n napi_finalize finalize_callback,\n void* finalize_hint,\n napi_value* result,\n bool* copied);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.[in] finalize_callback: The function to call when the string is being\ncollected. The function will be called with the following parameters:\n[in] env: The environment in which the add-on is running. This value\nmay be null if the string is being collected as part of the termination\nof the worker or the main Node.js instance.[in] data: This is the value str as a void* pointer.[in] finalize_hint: This is the value finalize_hint that was given\nto the API.\nnapi_finalize provides more details.\nThis parameter is optional. Passing a null value means that the add-on\ndoesn't need to be notified when the corresponding JavaScript string is\ncollected.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.[out] result: A napi_value representing a JavaScript string.[out] copied: Whether the string was copied. If it was, the finalizer will\nalready have been invoked to destroy str.Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from an ISO-8859-1-encoded C\nstring. The native string may not be copied and must thus exist for the entire\nlife cycle of the JavaScript value.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status napi_create_string_utf16(napi_env env,\n const char16_t* str,\n size_t length,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.[out] result: A napi_value representing a JavaScript string.Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF16-LE-encoded C string.\nThe native string is copied.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status\nnode_api_create_external_string_utf16(napi_env env,\n char16_t* str,\n size_t length,\n napi_finalize finalize_callback,\n void* finalize_hint,\n napi_value* result,\n bool* copied);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.[in] finalize_callback: The function to call when the string is being\ncollected. The function will be called with the following parameters:\n[in] env: The environment in which the add-on is running. This value\nmay be null if the string is being collected as part of the termination\nof the worker or the main Node.js instance.[in] data: This is the value str as a void* pointer.[in] finalize_hint: This is the value finalize_hint that was given\nto the API.\nnapi_finalize provides more details.\nThis parameter is optional. Passing a null value means that the add-on\ndoesn't need to be notified when the corresponding JavaScript string is\ncollected.[in] finalize_hint: Optional hint to pass to the finalize callback during\ncollection.[out] result: A napi_value representing a JavaScript string.[out] copied: Whether the string was copied. If it was, the finalizer will\nalready have been invoked to destroy str.Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF16-LE-encoded C string.\nThe native string may not be copied and must thus exist for the entire life\ncycle of the JavaScript value.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status napi_create_string_utf8(napi_env env,\n const char* str,\n size_t length,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF8-encoded string.[in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.[out] result: A napi_value representing a JavaScript string.Returns napi_ok if the API succeeded.
This API creates a JavaScript string value from a UTF8-encoded C string.\nThe native string is copied.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
Many JavaScript engines including V8 use internalized strings as keys\nto set and get property values. They typically use a hash table to create\nand lookup such strings. While it adds some cost per key creation, it improves\nthe performance after that by enabling comparison of string pointers instead\nof the whole strings.
\nIf a new JavaScript string is intended to be used as a property key, then for\nsome JavaScript engines it will be more efficient to use the functions in this\nsection. Otherwise, use the napi_create_string_utf8 or\nnode_api_create_external_string_utf8 series functions as there may be\nadditional overhead in creating/storing strings with the property key\ncreation methods.
napi_status NAPI_CDECL node_api_create_property_key_latin1(napi_env env,\n const char* str,\n size_t length,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing an ISO-8859-1-encoded string.[in] length: The length of the string in bytes, or NAPI_AUTO_LENGTH if it\nis null-terminated.[out] result: A napi_value representing an optimized JavaScript string\nto be used as a property key for objects.Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from\nan ISO-8859-1-encoded C string to be used as a property key for objects.\nThe native string is copied. In contrast with napi_create_string_latin1,\nsubsequent calls to this function with the same str pointer may benefit from a speedup\nin the creation of the requested napi_value, depending on the engine.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status NAPI_CDECL node_api_create_property_key_utf16(napi_env env,\n const char16_t* str,\n size_t length,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF16-LE-encoded string.[in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.[out] result: A napi_value representing an optimized JavaScript string\nto be used as a property key for objects.Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from\na UTF16-LE-encoded C string to be used as a property key for objects.\nThe native string is copied.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status NAPI_CDECL node_api_create_property_key_utf8(napi_env env,\n const char* str,\n size_t length,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] str: Character buffer representing a UTF8-encoded string.[in] length: The length of the string in two-byte code units, or\nNAPI_AUTO_LENGTH if it is null-terminated.[out] result: A napi_value representing an optimized JavaScript string\nto be used as a property key for objects.Returns napi_ok if the API succeeded.
This API creates an optimized JavaScript string value from\na UTF8-encoded C string to be used as a property key for objects.\nThe native string is copied.
The JavaScript string type is described in\nSection string type of the ECMAScript Language Specification.
napi_status napi_get_array_length(napi_env env,\n napi_value value,\n uint32_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing the JavaScript Array whose length is\nbeing queried.[out] result: uint32 representing length of the array.Returns napi_ok if the API succeeded.
This API returns the length of an array.
\nArray length is described in Section Array instance length of the ECMAScript Language\nSpecification.
napi_status napi_get_arraybuffer_info(napi_env env,\n napi_value arraybuffer,\n void** data,\n size_t* byte_length)\n\n[in] env: The environment that the API is invoked under.[in] arraybuffer: napi_value representing the ArrayBuffer or SharedArrayBuffer being queried.[out] data: The underlying data buffer of the ArrayBuffer or SharedArrayBuffer\nis 0, this may be NULL or any other pointer value.[out] byte_length: Length in bytes of the underlying data buffer.Returns napi_ok if the API succeeded.
This API is used to retrieve the underlying data buffer of an ArrayBuffer or SharedArrayBuffer and its length.
WARNING: Use caution while using this API. The lifetime of the underlying data\nbuffer is managed by the ArrayBuffer or SharedArrayBuffer even after it's returned. A\npossible safe way to use this API is in conjunction with\nnapi_create_reference, which can be used to guarantee control over the\nlifetime of the ArrayBuffer or SharedArrayBuffer. It's also safe to use the returned data buffer\nwithin the same callback as long as there are no calls to other APIs that might\ntrigger a GC.
napi_status napi_get_buffer_info(napi_env env,\n napi_value value,\n void** data,\n size_t* length)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing the node::Buffer or Uint8Array\nbeing queried.[out] data: The underlying data buffer of the node::Buffer or\nUint8Array. If length is 0, this may be NULL or any other pointer value.[out] length: Length in bytes of the underlying data buffer.Returns napi_ok if the API succeeded.
This method returns the identical data and byte_length as\nnapi_get_typedarray_info. And napi_get_typedarray_info accepts a\nnode::Buffer (a Uint8Array) as the value too.
This API is used to retrieve the underlying data buffer of a node::Buffer\nand its length.
Warning: Use caution while using this API since the underlying data buffer's\nlifetime is not guaranteed if it's managed by the VM.
", "displayName": "`napi_get_buffer_info`" }, { "textRaw": "`napi_get_prototype`", "name": "`napi_get_prototype`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_prototype(napi_env env,\n napi_value object,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] object: napi_value representing JavaScript Object whose prototype\nto return. This returns the equivalent of Object.getPrototypeOf (which is\nnot the same as the function's prototype property).[out] result: napi_value representing prototype of the given object.Returns napi_ok if the API succeeded.
napi_status napi_get_typedarray_info(napi_env env,\n napi_value typedarray,\n napi_typedarray_type* type,\n size_t* length,\n void** data,\n napi_value* arraybuffer,\n size_t* byte_offset)\n\n[in] env: The environment that the API is invoked under.[in] typedarray: napi_value representing the TypedArray whose\nproperties to query.[out] type: Scalar datatype of the elements within the TypedArray.[out] length: The number of elements in the TypedArray.[out] data: The data buffer underlying the TypedArray adjusted by\nthe byte_offset value so that it points to the first element in the\nTypedArray. If the length of the array is 0, this may be NULL or\nany other pointer value.[out] arraybuffer: The ArrayBuffer underlying the TypedArray.[out] byte_offset: The byte offset within the underlying native array\nat which the first element of the arrays is located. The value for the data\nparameter has already been adjusted so that data points to the first element\nin the array. Therefore, the first byte of the native array would be at\ndata - byte_offset.Returns napi_ok if the API succeeded.
This API returns various properties of a typed array.
\nAny of the out parameters may be NULL if that property is unneeded.
Warning: Use caution while using this API since the underlying data buffer\nis managed by the VM.
", "displayName": "`napi_get_typedarray_info`" }, { "textRaw": "`napi_get_dataview_info`", "name": "`napi_get_dataview_info`", "type": "module", "meta": { "added": [ "v8.3.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_dataview_info(napi_env env,\n napi_value dataview,\n size_t* byte_length,\n void** data,\n napi_value* arraybuffer,\n size_t* byte_offset)\n\n[in] env: The environment that the API is invoked under.[in] dataview: napi_value representing the DataView whose\nproperties to query.[out] byte_length: Number of bytes in the DataView.[out] data: The data buffer underlying the DataView.\nIf byte_length is 0, this may be NULL or any other pointer value.[out] arraybuffer: ArrayBuffer underlying the DataView.[out] byte_offset: The byte offset within the data buffer from which\nto start projecting the DataView.Returns napi_ok if the API succeeded.
Any of the out parameters may be NULL if that property is unneeded.
This API returns various properties of a DataView.
napi_status napi_get_date_value(napi_env env,\n napi_value value,\n double* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing a JavaScript Date.[out] result: Time value as a double represented as milliseconds since\nmidnight at the beginning of 01 January, 1970 UTC.This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.
\nReturns napi_ok if the API succeeded. If a non-date napi_value is passed\nin it returns napi_date_expected.
This API returns the C double primitive of time value for the given JavaScript\nDate.
napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript Boolean.[out] result: C boolean primitive equivalent of the given JavaScript\nBoolean.Returns napi_ok if the API succeeded. If a non-boolean napi_value is\npassed in it returns napi_boolean_expected.
This API returns the C boolean primitive equivalent of the given JavaScript\nBoolean.
napi_status napi_get_value_double(napi_env env,\n napi_value value,\n double* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript number.[out] result: C double primitive equivalent of the given JavaScript\nnumber.Returns napi_ok if the API succeeded. If a non-number napi_value is passed\nin it returns napi_number_expected.
This API returns the C double primitive equivalent of the given JavaScript\nnumber.
napi_status napi_get_value_bigint_int64(napi_env env,\n napi_value value,\n int64_t* result,\n bool* lossless);\n\n[in] env: The environment that the API is invoked under[in] value: napi_value representing JavaScript BigInt.[out] result: C int64_t primitive equivalent of the given JavaScript\nBigInt.[out] lossless: Indicates whether the BigInt value was converted\nlosslessly.Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.
This API returns the C int64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.
napi_status napi_get_value_bigint_uint64(napi_env env,\n napi_value value,\n uint64_t* result,\n bool* lossless);\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript BigInt.[out] result: C uint64_t primitive equivalent of the given JavaScript\nBigInt.[out] lossless: Indicates whether the BigInt value was converted\nlosslessly.Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.
This API returns the C uint64_t primitive equivalent of the given JavaScript\nBigInt. If needed it will truncate the value, setting lossless to false.
napi_status napi_get_value_bigint_words(napi_env env,\n napi_value value,\n int* sign_bit,\n size_t* word_count,\n uint64_t* words);\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript BigInt.[out] sign_bit: Integer representing if the JavaScript BigInt is positive\nor negative.[in/out] word_count: Must be initialized to the length of the words\narray. Upon return, it will be set to the actual number of words that\nwould be needed to store this BigInt.[out] words: Pointer to a pre-allocated 64-bit word array.Returns napi_ok if the API succeeded.
This API converts a single BigInt value into a sign bit, 64-bit little-endian\narray, and the number of elements in the array. sign_bit and words may be\nboth set to NULL, in order to get only word_count.
napi_status napi_get_value_external(napi_env env,\n napi_value value,\n void** result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript external value.[out] result: Pointer to the data wrapped by the JavaScript external value.Returns napi_ok if the API succeeded. If a non-external napi_value is\npassed in it returns napi_invalid_arg.
This API retrieves the external data pointer that was previously passed to\nnapi_create_external().
napi_status napi_get_value_int32(napi_env env,\n napi_value value,\n int32_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript number.[out] result: C int32 primitive equivalent of the given JavaScript\nnumber.Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in napi_number_expected.
This API returns the C int32 primitive equivalent\nof the given JavaScript number.
If the number exceeds the range of the 32 bit integer, then the result is\ntruncated to the equivalent of the bottom 32 bits. This can result in a large\npositive number becoming a negative number if the value is > 231 - 1.
\nNon-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.
napi_status napi_get_value_int64(napi_env env,\n napi_value value,\n int64_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript number.[out] result: C int64 primitive equivalent of the given JavaScript\nnumber.Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.
This API returns the C int64 primitive equivalent of the given JavaScript\nnumber.
number values outside the range of Number.MIN_SAFE_INTEGER\n-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose\nprecision.
Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.
napi_status napi_get_value_string_latin1(napi_env env,\n napi_value value,\n char* buf,\n size_t bufsize,\n size_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript string.[in] buf: Buffer to write the ISO-8859-1-encoded string into. If NULL is\npassed in, the length of the string in bytes and excluding the null terminator\nis returned in result.[in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string is truncated and null-terminated.\nIf this value is zero, then the string is not returned and no changes are done\nto the buffer.[out] result: Number of bytes copied into the buffer, excluding the null\nterminator.Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.
This API returns the ISO-8859-1-encoded string corresponding the value passed\nin.
", "displayName": "`napi_get_value_string_latin1`" }, { "textRaw": "`napi_get_value_string_utf8`", "name": "`napi_get_value_string_utf8`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_value_string_utf8(napi_env env,\n napi_value value,\n char* buf,\n size_t bufsize,\n size_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript string.[in] buf: Buffer to write the UTF8-encoded string into. If NULL is passed\nin, the length of the string in bytes and excluding the null terminator is\nreturned in result.[in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string is truncated and null-terminated.\nIf this value is zero, then the string is not returned and no changes are done\nto the buffer.[out] result: Number of bytes copied into the buffer, excluding the null\nterminator.Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.
This API returns the UTF8-encoded string corresponding the value passed in.
", "displayName": "`napi_get_value_string_utf8`" }, { "textRaw": "`napi_get_value_string_utf16`", "name": "`napi_get_value_string_utf16`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_value_string_utf16(napi_env env,\n napi_value value,\n char16_t* buf,\n size_t bufsize,\n size_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript string.[in] buf: Buffer to write the UTF16-LE-encoded string into. If NULL is\npassed in, the length of the string in 2-byte code units and excluding the\nnull terminator is returned.[in] bufsize: Size of the destination buffer. When this value is\ninsufficient, the returned string is truncated and null-terminated.\nIf this value is zero, then the string is not returned and no changes are done\nto the buffer.[out] result: Number of 2-byte code units copied into the buffer, excluding\nthe null terminator.Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.
This API returns the UTF16-encoded string corresponding the value passed in.
", "displayName": "`napi_get_value_string_utf16`" }, { "textRaw": "`napi_get_value_uint32`", "name": "`napi_get_value_uint32`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_value_uint32(napi_env env,\n napi_value value,\n uint32_t* result)\n\n[in] env: The environment that the API is invoked under.[in] value: napi_value representing JavaScript number.[out] result: C primitive equivalent of the given napi_value as a\nuint32_t.Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.
This API returns the C primitive equivalent of the given napi_value as a\nuint32_t.
napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The value of the boolean to retrieve.[out] result: napi_value representing JavaScript Boolean singleton to\nretrieve.Returns napi_ok if the API succeeded.
This API is used to return the JavaScript singleton object that is used to\nrepresent the given boolean value.
", "displayName": "`napi_get_boolean`" }, { "textRaw": "`napi_get_global`", "name": "`napi_get_global`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_global(napi_env env, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[out] result: napi_value representing JavaScript global object.Returns napi_ok if the API succeeded.
This API returns the global object.
napi_status napi_get_null(napi_env env, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[out] result: napi_value representing JavaScript null object.Returns napi_ok if the API succeeded.
This API returns the null object.
napi_status napi_get_undefined(napi_env env, napi_value* result)\n\n[in] env: The environment that the API is invoked under.[out] result: napi_value representing JavaScript Undefined value.Returns napi_ok if the API succeeded.
This API returns the Undefined object.
", "displayName": "`napi_get_undefined`" } ], "displayName": "Functions to get global instances" } ], "displayName": "Working with JavaScript values" }, { "textRaw": "Working with JavaScript values and abstract operations", "name": "working_with_javascript_values_and_abstract_operations", "type": "misc", "desc": "Node-API exposes a set of APIs to perform some abstract operations on JavaScript\nvalues.
\nThese APIs support doing one of the following:
\nnumber or\nstring).napi_status napi_coerce_to_bool(napi_env env,\n napi_value value,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result: napi_value representing the coerced JavaScript Boolean.Returns napi_ok if the API succeeded.
This API implements the abstract operation ToBoolean() as defined in\nSection ToBoolean of the ECMAScript Language Specification.
napi_status napi_coerce_to_number(napi_env env,\n napi_value value,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result: napi_value representing the coerced JavaScript number.Returns napi_ok if the API succeeded.
This API implements the abstract operation ToNumber() as defined in\nSection ToNumber of the ECMAScript Language Specification.\nThis function potentially runs JS code if the passed-in value is an\nobject.
napi_status napi_coerce_to_object(napi_env env,\n napi_value value,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result: napi_value representing the coerced JavaScript Object.Returns napi_ok if the API succeeded.
This API implements the abstract operation ToObject() as defined in\nSection ToObject of the ECMAScript Language Specification.
napi_status napi_coerce_to_string(napi_env env,\n napi_value value,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to coerce.[out] result: napi_value representing the coerced JavaScript string.Returns napi_ok if the API succeeded.
This API implements the abstract operation ToString() as defined in\nSection ToString of the ECMAScript Language Specification.\nThis function potentially runs JS code if the passed-in value is an\nobject.
napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value whose type to query.[out] result: The type of the JavaScript value.Returns napi_ok if the API succeeded.
napi_invalid_arg if the type of value is not a known ECMAScript type and\nvalue is not an External value.This API represents behavior similar to invoking the typeof Operator on\nthe object as defined in Section typeof operator of the ECMAScript Language\nSpecification. However, there are some differences:
null as a separate type, while ECMAScript typeof would detect\nobject.If value has a type that is invalid, an error is returned.
napi_status napi_instanceof(napi_env env,\n napi_value object,\n napi_value constructor,\n bool* result)\n\n[in] env: The environment that the API is invoked under.[in] object: The JavaScript value to check.[in] constructor: The JavaScript function object of the constructor function\nto check against.[out] result: Boolean that is set to true if object instanceof constructor\nis true.Returns napi_ok if the API succeeded.
This API represents invoking the instanceof Operator on the object as\ndefined in Section instanceof operator of the ECMAScript Language Specification.
napi_status napi_is_array(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given object is an array.Returns napi_ok if the API succeeded.
This API represents invoking the IsArray operation on the object\nas defined in Section IsArray of the ECMAScript Language Specification.
napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given object is an ArrayBuffer.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is an array buffer.
napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents a node::Buffer or\nUint8Array object.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a buffer or Uint8Array.\nnapi_is_typedarray should be preferred if the caller needs to check if the\nvalue is a Uint8Array.
napi_status napi_is_date(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents a JavaScript Date\nobject.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a date.
napi_status napi_is_error(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents an Error object.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is an Error.
napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents a TypedArray.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a typed array.
napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents a DataView.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a DataView.
napi_status napi_strict_equals(napi_env env,\n napi_value lhs,\n napi_value rhs,\n bool* result)\n\n[in] env: The environment that the API is invoked under.[in] lhs: The JavaScript value to check.[in] rhs: The JavaScript value to check against.[out] result: Whether the two napi_value objects are equal.Returns napi_ok if the API succeeded.
This API represents the invocation of the Strict Equality algorithm as\ndefined in Section IsStrctEqual of the ECMAScript Language Specification.
", "displayName": "`napi_strict_equals`" }, { "textRaw": "`napi_detach_arraybuffer`", "name": "`napi_detach_arraybuffer`", "type": "module", "meta": { "added": [ "v13.0.0", "v12.16.0", "v10.22.0" ], "changes": [], "napiVersion": [ 7 ] }, "desc": "napi_status napi_detach_arraybuffer(napi_env env,\n napi_value arraybuffer)\n\n[in] env: The environment that the API is invoked under.[in] arraybuffer: The JavaScript ArrayBuffer to be detached.Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is\npassed in it returns napi_detachable_arraybuffer_expected.
Generally, an ArrayBuffer is non-detachable if it has been detached before.\nThe engine may impose additional conditions on whether an ArrayBuffer is\ndetachable. For example, V8 requires that the ArrayBuffer be external,\nthat is, created with napi_create_external_arraybuffer.
This API represents the invocation of the ArrayBuffer detach operation as\ndefined in Section detachArrayBuffer of the ECMAScript Language Specification.
napi_status napi_is_detached_arraybuffer(napi_env env,\n napi_value arraybuffer,\n bool* result)\n\n[in] env: The environment that the API is invoked under.[in] arraybuffer: The JavaScript ArrayBuffer to be checked.[out] result: Whether the arraybuffer is detached.Returns napi_ok if the API succeeded.
The ArrayBuffer is considered detached if its internal data is null.
This API represents the invocation of the ArrayBuffer IsDetachedBuffer\noperation as defined in Section isDetachedBuffer of the ECMAScript Language\nSpecification.
napi_status node_api_is_sharedarraybuffer(napi_env env, napi_value value, bool* result)\n\n[in] env: The environment that the API is invoked under.[in] value: The JavaScript value to check.[out] result: Whether the given napi_value represents a SharedArrayBuffer.Returns napi_ok if the API succeeded.
This API checks if the Object passed in is a SharedArrayBuffer.
napi_status node_api_create_sharedarraybuffer(napi_env env,\n size_t byte_length,\n void** data,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] byte_length: The length in bytes of the shared array buffer to create.[out] data: Pointer to the underlying byte buffer of the SharedArrayBuffer.\ndata can optionally be ignored by passing NULL.[out] result: A napi_value representing a JavaScript SharedArrayBuffer.Returns napi_ok if the API succeeded.
This API returns a Node-API value corresponding to a JavaScript SharedArrayBuffer.\nSharedArrayBuffers are used to represent fixed-length binary data buffers that\ncan be shared across multiple workers.
The SharedArrayBuffer allocated will have an underlying byte buffer whose size is\ndetermined by the byte_length parameter that's passed in.\nThe underlying buffer is optionally returned back to the caller in case the\ncaller wants to directly manipulate the buffer. This buffer can only be\nwritten to directly from native code. To write to this buffer from JavaScript,\na typed array or DataView object would need to be created.
JavaScript SharedArrayBuffer objects are described in\nSection SharedArrayBuffer objects of the ECMAScript Language Specification.
Node-API exposes a set of APIs to get and set properties on JavaScript\nobjects.
\nProperties in JavaScript are represented as a tuple of a key and a value.\nFundamentally, all property keys in Node-API can be represented in one of the\nfollowing forms:
\nuint32_tnapi_value. This can\nbe a napi_value representing a string, number, or symbol.Node-API values are represented by the type napi_value.\nAny Node-API call that requires a JavaScript value takes in a napi_value.\nHowever, it's the caller's responsibility to make sure that the\nnapi_value in question is of the JavaScript type expected by the API.
The APIs documented in this section provide a simple interface to\nget and set properties on arbitrary JavaScript objects represented by\nnapi_value.
For instance, consider the following JavaScript code snippet:
\nconst obj = {};\nobj.myProp = 123;\n\nThe equivalent can be done using Node-API values with the following snippet:
\nnapi_status status = napi_generic_failure;\n\n// const obj = {}\nnapi_value obj, value;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 123\nstatus = napi_create_int32(env, 123, &value);\nif (status != napi_ok) return status;\n\n// obj.myProp = 123\nstatus = napi_set_named_property(env, obj, \"myProp\", value);\nif (status != napi_ok) return status;\n\nIndexed properties can be set in a similar manner. Consider the following\nJavaScript snippet:
\nconst arr = [];\narr[123] = 'hello';\n\nThe equivalent can be done using Node-API values with the following snippet:
\nnapi_status status = napi_generic_failure;\n\n// const arr = [];\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// Create a napi_value for 'hello'\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &value);\nif (status != napi_ok) return status;\n\n// arr[123] = 'hello';\nstatus = napi_set_element(env, arr, 123, value);\nif (status != napi_ok) return status;\n\nProperties can be retrieved using the APIs described in this section.\nConsider the following JavaScript snippet:
\nconst arr = [];\nconst value = arr[123];\n\nThe following is the approximate equivalent of the Node-API counterpart:
\nnapi_status status = napi_generic_failure;\n\n// const arr = []\nnapi_value arr, value;\nstatus = napi_create_array(env, &arr);\nif (status != napi_ok) return status;\n\n// const value = arr[123]\nstatus = napi_get_element(env, arr, 123, &value);\nif (status != napi_ok) return status;\n\nFinally, multiple properties can also be defined on an object for performance\nreasons. Consider the following JavaScript:
\nconst obj = {};\nObject.defineProperties(obj, {\n 'foo': { value: 123, writable: true, configurable: true, enumerable: true },\n 'bar': { value: 456, writable: true, configurable: true, enumerable: true },\n});\n\nThe following is the approximate equivalent of the Node-API counterpart:
\nnapi_status status = napi_status_generic_failure;\n\n// const obj = {};\nnapi_value obj;\nstatus = napi_create_object(env, &obj);\nif (status != napi_ok) return status;\n\n// Create napi_values for 123 and 456\nnapi_value fooValue, barValue;\nstatus = napi_create_int32(env, 123, &fooValue);\nif (status != napi_ok) return status;\nstatus = napi_create_int32(env, 456, &barValue);\nif (status != napi_ok) return status;\n\n// Set the properties\nnapi_property_descriptor descriptors[] = {\n { \"foo\", NULL, NULL, NULL, NULL, fooValue, napi_writable | napi_configurable, NULL },\n { \"bar\", NULL, NULL, NULL, NULL, barValue, napi_writable | napi_configurable, NULL }\n}\nstatus = napi_define_properties(env,\n obj,\n sizeof(descriptors) / sizeof(descriptors[0]),\n descriptors);\nif (status != napi_ok) return status;\n",
"modules": [
{
"textRaw": "Structures",
"name": "structures",
"type": "module",
"modules": [
{
"textRaw": "`napi_property_attributes`",
"name": "`napi_property_attributes`",
"type": "module",
"meta": {
"changes": [
{
"version": "v14.12.0",
"pr-url": "https://github.com/nodejs/node/pull/35214",
"description": "added `napi_default_method` and `napi_default_property`."
}
]
},
"desc": "typedef enum {\n napi_default = 0,\n napi_writable = 1 << 0,\n napi_enumerable = 1 << 1,\n napi_configurable = 1 << 2,\n\n // Used with napi_define_class to distinguish static properties\n // from instance properties. Ignored by napi_define_properties.\n napi_static = 1 << 10,\n\n // Default for class methods.\n napi_default_method = napi_writable | napi_configurable,\n\n // Default for object properties, like in JS obj[prop].\n napi_default_jsproperty = napi_writable |\n napi_enumerable |\n napi_configurable,\n} napi_property_attributes;\n\nnapi_property_attributes are bit flags used to control the behavior of\nproperties set on a JavaScript object. Other than napi_static they\ncorrespond to the attributes listed in Section property attributes\nof the ECMAScript Language Specification.\nThey can be one or more of the following bit flags:
napi_default: No explicit attributes are set on the property. By default, a\nproperty is read only, not enumerable and not configurable.napi_writable: The property is writable.napi_enumerable: The property is enumerable.napi_configurable: The property is configurable as defined in\nSection property attributes of the ECMAScript Language Specification.napi_static: The property will be defined as a static property on a class as\nopposed to an instance property, which is the default. This is used only by\nnapi_define_class. It is ignored by napi_define_properties.napi_default_method: Like a method in a JS class, the property is\nconfigurable and writeable, but not enumerable.napi_default_jsproperty: Like a property set via assignment in JavaScript,\nthe property is writable, enumerable, and configurable.typedef struct {\n // One of utf8name or name should be NULL.\n const char* utf8name;\n napi_value name;\n\n napi_callback method;\n napi_callback getter;\n napi_callback setter;\n napi_value value;\n\n napi_property_attributes attributes;\n void* data;\n} napi_property_descriptor;\n\nutf8name: Optional string describing the key for the property,\nencoded as UTF8. One of utf8name or name must be provided for the\nproperty.name: Optional napi_value that points to a JavaScript string or symbol\nto be used as the key for the property. One of utf8name or name must\nbe provided for the property.value: The value that's retrieved by a get access of the property if the\nproperty is a data property. If this is passed in, set getter, setter,\nmethod and data to NULL (since these members won't be used).getter: A function to call when a get access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is accessed from JavaScript code (or if a get on the property is\nperformed using a Node-API call). napi_callback provides more details.setter: A function to call when a set access of the property is performed.\nIf this is passed in, set value and method to NULL (since these members\nwon't be used). The given function is called implicitly by the runtime when\nthe property is set from JavaScript code (or if a set on the property is\nperformed using a Node-API call). napi_callback provides more details.method: Set this to make the property descriptor object's value\nproperty to be a JavaScript function represented by method. If this is\npassed in, set value, getter and setter to NULL (since these members\nwon't be used). napi_callback provides more details.attributes: The attributes associated with the particular property. See\nnapi_property_attributes.data: The callback data passed into method, getter and setter if this\nfunction is invoked.napi_status napi_get_property_names(napi_env env,\n napi_value object,\n napi_value* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. The API can be used to\niterate over result using napi_get_array_length\nand napi_get_element.Returns napi_ok if the API succeeded.
This API returns the names of the enumerable properties of object as an array\nof strings. The properties of object whose key is a symbol will not be\nincluded.
napi_get_all_property_names(napi_env env,\n napi_value object,\n napi_key_collection_mode key_mode,\n napi_key_filter key_filter,\n napi_key_conversion key_conversion,\n napi_value* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[in] key_mode: Whether to retrieve prototype properties as well.[in] key_filter: Which properties to retrieve\n(enumerable/readable/writable).[in] key_conversion: Whether to convert numbered property keys to strings.[out] result: A napi_value representing an array of JavaScript values\nthat represent the property names of the object. napi_get_array_length\nand napi_get_element can be used to iterate over result.Returns napi_ok if the API succeeded.
This API returns an array containing the names of the available properties\nof this object.
", "displayName": "`napi_get_all_property_names`" }, { "textRaw": "`napi_set_property`", "name": "`napi_set_property`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_set_property(napi_env env,\n napi_value object,\n napi_value key,\n napi_value value);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the property.[in] key: The name of the property to set.[in] value: The property value.Returns napi_ok if the API succeeded.
This API set a property on the Object passed in.
napi_status napi_get_property(napi_env env,\n napi_value object,\n napi_value key,\n napi_value* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] key: The name of the property to retrieve.[out] result: The value of the property.Returns napi_ok if the API succeeded.
This API gets the requested property from the Object passed in.
napi_status napi_has_property(napi_env env,\n napi_value object,\n napi_value key,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the property whose existence to check.[out] result: Whether the property exists on the object or not.Returns napi_ok if the API succeeded.
This API checks if the Object passed in has the named property.
napi_status napi_delete_property(napi_env env,\n napi_value object,\n napi_value key,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the property to delete.[out] result: Whether the property deletion succeeded or not. result can\noptionally be ignored by passing NULL.Returns napi_ok if the API succeeded.
This API attempts to delete the key own property from object.
napi_status napi_has_own_property(napi_env env,\n napi_value object,\n napi_value key,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] key: The name of the own property whose existence to check.[out] result: Whether the own property exists on the object or not.Returns napi_ok if the API succeeded.
This API checks if the Object passed in has the named own property. key must\nbe a string or a symbol, or an error will be thrown. Node-API will not\nperform any conversion between data types.
napi_status napi_set_named_property(napi_env env,\n napi_value object,\n const char* utf8Name,\n napi_value value);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the property.[in] utf8Name: The name of the property to set.[in] value: The property value.Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_set_property with a napi_value\ncreated from the string passed in as utf8Name.
napi_status napi_get_named_property(napi_env env,\n napi_value object,\n const char* utf8Name,\n napi_value* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] utf8Name: The name of the property to get.[out] result: The value of the property.Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_get_property with a napi_value\ncreated from the string passed in as utf8Name.
napi_status napi_has_named_property(napi_env env,\n napi_value object,\n const char* utf8Name,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] utf8Name: The name of the property whose existence to check.[out] result: Whether the property exists on the object or not.Returns napi_ok if the API succeeded.
This method is equivalent to calling napi_has_property with a napi_value\ncreated from the string passed in as utf8Name.
napi_status napi_set_element(napi_env env,\n napi_value object,\n uint32_t index,\n napi_value value);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to set the properties.[in] index: The index of the property to set.[in] value: The property value.Returns napi_ok if the API succeeded.
This API sets an element on the Object passed in.
napi_status napi_get_element(napi_env env,\n napi_value object,\n uint32_t index,\n napi_value* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the property.[in] index: The index of the property to get.[out] result: The value of the property.Returns napi_ok if the API succeeded.
This API gets the element at the requested index.
", "displayName": "`napi_get_element`" }, { "textRaw": "`napi_has_element`", "name": "`napi_has_element`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_has_element(napi_env env,\n napi_value object,\n uint32_t index,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] index: The index of the property whose existence to check.[out] result: Whether the property exists on the object or not.Returns napi_ok if the API succeeded.
This API returns if the Object passed in has an element at the\nrequested index.
napi_status napi_delete_element(napi_env env,\n napi_value object,\n uint32_t index,\n bool* result);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to query.[in] index: The index of the property to delete.[out] result: Whether the element deletion succeeded or not. result can\noptionally be ignored by passing NULL.Returns napi_ok if the API succeeded.
This API attempts to delete the specified index from object.
napi_status napi_define_properties(napi_env env,\n napi_value object,\n size_t property_count,\n const napi_property_descriptor* properties);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object from which to retrieve the properties.[in] property_count: The number of elements in the properties array.[in] properties: The array of property descriptors.Returns napi_ok if the API succeeded.
This method allows the efficient definition of multiple properties on a given\nobject. The properties are defined using property descriptors (see\nnapi_property_descriptor). Given an array of such property descriptors,\nthis API will set the properties on the object one at a time, as defined by\nDefineOwnProperty() (described in Section DefineOwnProperty of the ECMA-262\nspecification).
napi_status napi_object_freeze(napi_env env,\n napi_value object);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to freeze.Returns napi_ok if the API succeeded.
This method freezes a given object. This prevents new properties from\nbeing added to it, existing properties from being removed, prevents\nchanging the enumerability, configurability, or writability of existing\nproperties, and prevents the values of existing properties from being changed.\nIt also prevents the object's prototype from being changed. This is described\nin Section 19.1.2.6 of the\nECMA-262 specification.
", "displayName": "`napi_object_freeze`" }, { "textRaw": "`napi_object_seal`", "name": "`napi_object_seal`", "type": "module", "meta": { "added": [ "v14.14.0", "v12.20.0" ], "changes": [], "napiVersion": [ 8 ] }, "desc": "napi_status napi_object_seal(napi_env env,\n napi_value object);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object to seal.Returns napi_ok if the API succeeded.
This method seals a given object. This prevents new properties from being\nadded to it, as well as marking all existing properties as non-configurable.\nThis is described in Section 19.1.2.20\nof the ECMA-262 specification.
", "displayName": "`napi_object_seal`" }, { "textRaw": "`node_api_set_prototype`", "name": "`node_api_set_prototype`", "type": "module", "meta": { "added": [ "v25.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "napi_status node_api_set_prototype(napi_env env,\n napi_value object,\n napi_value value);\n\n[in] env: The environment that the Node-API call is invoked under.[in] object: The object on which to set the prototype.[in] value: The prototype value.Returns napi_ok if the API succeeded.
This API sets the prototype of the Object passed in.
Node-API provides a set of APIs that allow JavaScript code to\ncall back into native code. Node-APIs that support calling back\ninto native code take in a callback functions represented by\nthe napi_callback type. When the JavaScript VM calls back to\nnative code, the napi_callback function provided is invoked. The APIs\ndocumented in this section allow the callback function to do the\nfollowing:
napi_value back from the callback.Additionally, Node-API provides a set of functions which allow calling\nJavaScript functions from native code. One can either call a function\nlike a regular JavaScript function call, or as a constructor\nfunction.
\nAny non-NULL data which is passed to this API via the data field of the\nnapi_property_descriptor items can be associated with object and freed\nwhenever object is garbage-collected by passing both object and the data to\nnapi_add_finalizer.
NAPI_EXTERN napi_status napi_call_function(napi_env env,\n napi_value recv,\n napi_value func,\n size_t argc,\n const napi_value* argv,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] recv: The this value passed to the called function.[in] func: napi_value representing the JavaScript function to be invoked.[in] argc: The count of elements in the argv array.[in] argv: Array of napi_values representing JavaScript values passed in\nas arguments to the function.[out] result: napi_value representing the JavaScript object returned.Returns napi_ok if the API succeeded.
This method allows a JavaScript function object to be called from a native\nadd-on. This is the primary mechanism of calling back from the add-on's\nnative code into JavaScript. For the special case of calling into JavaScript\nafter an async operation, see napi_make_callback.
A sample use case might look as follows. Consider the following JavaScript\nsnippet:
\nfunction AddTwo(num) {\n return num + 2;\n}\nglobal.AddTwo = AddTwo;\n\nThen, the above function can be invoked from a native add-on using the\nfollowing code:
\n// Get the function named \"AddTwo\" on the global object\nnapi_value global, add_two, arg;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"AddTwo\", &add_two);\nif (status != napi_ok) return;\n\n// const arg = 1337\nstatus = napi_create_int32(env, 1337, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// AddTwo(arg);\nnapi_value return_val;\nstatus = napi_call_function(env, global, add_two, argc, argv, &return_val);\nif (status != napi_ok) return;\n\n// Convert the result back to a native type\nint32_t result;\nstatus = napi_get_value_int32(env, return_val, &result);\nif (status != napi_ok) return;\n",
"displayName": "`napi_call_function`"
},
{
"textRaw": "`napi_create_function`",
"name": "`napi_create_function`",
"type": "module",
"meta": {
"added": [
"v8.0.0"
],
"changes": [],
"napiVersion": [
1
]
},
"desc": "napi_status napi_create_function(napi_env env,\n const char* utf8name,\n size_t length,\n napi_callback cb,\n void* data,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] utf8Name: Optional name of the function encoded as UTF8. This is\nvisible within JavaScript as the new function object's name property.[in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH if\nit is null-terminated.[in] cb: The native function which should be called when this function\nobject is invoked. napi_callback provides more details.[in] data: User-provided data context. This will be passed back into the\nfunction when invoked later.[out] result: napi_value representing the JavaScript function object for\nthe newly created function.Returns napi_ok if the API succeeded.
This API allows an add-on author to create a function object in native code.\nThis is the primary mechanism to allow calling into the add-on's native code\nfrom JavaScript.
\nThe newly created function is not automatically visible from script after this\ncall. Instead, a property must be explicitly set on any object that is visible\nto JavaScript, in order for the function to be accessible from script.
\nIn order to expose a function as part of the\nadd-on's module exports, set the newly created function on the exports\nobject. A sample module might look as follows:
\nnapi_value SayHello(napi_env env, napi_callback_info info) {\n printf(\"Hello\\n\");\n return NULL;\n}\n\nnapi_value Init(napi_env env, napi_value exports) {\n napi_status status;\n\n napi_value fn;\n status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn);\n if (status != napi_ok) return NULL;\n\n status = napi_set_named_property(env, exports, \"sayHello\", fn);\n if (status != napi_ok) return NULL;\n\n return exports;\n}\n\nNAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n\nGiven the above code, the add-on can be used from JavaScript as follows:
\nconst myaddon = require('./addon');\nmyaddon.sayHello();\n\nThe string passed to require() is the name of the target in binding.gyp\nresponsible for creating the .node file.
Any non-NULL data which is passed to this API via the data parameter can\nbe associated with the resulting JavaScript function (which is returned in the\nresult parameter) and freed whenever the function is garbage-collected by\npassing both the JavaScript function and the data to napi_add_finalizer.
JavaScript Functions are described in Section Function objects of the ECMAScript\nLanguage Specification.
napi_status napi_get_cb_info(napi_env env,\n napi_callback_info cbinfo,\n size_t* argc,\n napi_value* argv,\n napi_value* thisArg,\n void** data)\n\n[in] env: The environment that the API is invoked under.[in] cbinfo: The callback info passed into the callback function.[in-out] argc: Specifies the length of the provided argv array and\nreceives the actual count of arguments. argc can\noptionally be ignored by passing NULL.[out] argv: C array of napi_values to which the arguments will be\ncopied. If there are more arguments than the provided count, only the\nrequested number of arguments are copied. If there are fewer arguments\nprovided than claimed, the rest of argv is filled with napi_value values\nthat represent undefined. argv can optionally be ignored by\npassing NULL.[out] thisArg: Receives the JavaScript this argument for the call.\nthisArg can optionally be ignored by passing NULL.[out] data: Receives the data pointer for the callback. data can\noptionally be ignored by passing NULL.Returns napi_ok if the API succeeded.
This method is used within a callback function to retrieve details about the\ncall like the arguments and the this pointer from a given callback info.
napi_status napi_get_new_target(napi_env env,\n napi_callback_info cbinfo,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] cbinfo: The callback info passed into the callback function.[out] result: The new.target of the constructor call.Returns napi_ok if the API succeeded.
This API returns the new.target of the constructor call. If the current\ncallback is not a constructor call, the result is NULL.
napi_status napi_new_instance(napi_env env,\n napi_value cons,\n size_t argc,\n napi_value* argv,\n napi_value* result)\n\n[in] env: The environment that the API is invoked under.[in] cons: napi_value representing the JavaScript function to be invoked\nas a constructor.[in] argc: The count of elements in the argv array.[in] argv: Array of JavaScript values as napi_value representing the\narguments to the constructor. If argc is zero this parameter may be\nomitted by passing in NULL.[out] result: napi_value representing the JavaScript object returned,\nwhich in this case is the constructed object.This method is used to instantiate a new JavaScript value using a given\nnapi_value that represents the constructor for the object. For example,\nconsider the following snippet:
function MyObject(param) {\n this.param = param;\n}\n\nconst arg = 'hello';\nconst value = new MyObject(arg);\n\nThe following can be approximated in Node-API using the following snippet:
\n// Get the constructor function MyObject\nnapi_value global, constructor, arg, value;\nnapi_status status = napi_get_global(env, &global);\nif (status != napi_ok) return;\n\nstatus = napi_get_named_property(env, global, \"MyObject\", &constructor);\nif (status != napi_ok) return;\n\n// const arg = \"hello\"\nstatus = napi_create_string_utf8(env, \"hello\", NAPI_AUTO_LENGTH, &arg);\nif (status != napi_ok) return;\n\nnapi_value* argv = &arg;\nsize_t argc = 1;\n\n// const value = new MyObject(arg)\nstatus = napi_new_instance(env, constructor, argc, argv, &value);\n\nReturns napi_ok if the API succeeded.
Node-API offers a way to \"wrap\" C++ classes and instances so that the class\nconstructor and methods can be called from JavaScript.
\nnapi_define_class API defines a JavaScript class with constructor,\nstatic properties and methods, and instance properties and methods that\ncorrespond to the C++ class.napi_wrap to wrap a new C++ instance in a JavaScript object,\nthen returns the wrapper object.napi_callback C++ function is invoked. For an instance\ncallback, napi_unwrap obtains the C++ instance that is the target of\nthe call.For wrapped objects it may be difficult to distinguish between a function\ncalled on a class prototype and a function called on an instance of a class.\nA common pattern used to address this problem is to save a persistent\nreference to the class constructor for later instanceof checks.
napi_value MyClass_constructor = NULL;\nstatus = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor);\nassert(napi_ok == status);\nbool is_instance = false;\nstatus = napi_instanceof(env, es_this, MyClass_constructor, &is_instance);\nassert(napi_ok == status);\nif (is_instance) {\n // napi_unwrap() ...\n} else {\n // otherwise...\n}\n\nThe reference must be freed once it is no longer needed.
\nThere are occasions where napi_instanceof() is insufficient for ensuring that\na JavaScript object is a wrapper for a certain native type. This is the case\nespecially when wrapped JavaScript objects are passed back into the addon via\nstatic methods rather than as the this value of prototype methods. In such\ncases there is a chance that they may be unwrapped incorrectly.
const myAddon = require('./build/Release/my_addon.node');\n\n// `openDatabase()` returns a JavaScript object that wraps a native database\n// handle.\nconst dbHandle = myAddon.openDatabase();\n\n// `query()` returns a JavaScript object that wraps a native query handle.\nconst queryHandle = myAddon.query(dbHandle, 'Gimme ALL the things!');\n\n// There is an accidental error in the line below. The first parameter to\n// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not\n// the query handle (`query`), so the correct condition for the while-loop\n// should be\n//\n// myAddon.queryHasRecords(dbHandle, queryHandle)\n//\nwhile (myAddon.queryHasRecords(queryHandle, dbHandle)) {\n // retrieve records\n}\n\nIn the above example myAddon.queryHasRecords() is a method that accepts two\narguments. The first is a database handle and the second is a query handle.\nInternally, it unwraps the first argument and casts the resulting pointer to a\nnative database handle. It then unwraps the second argument and casts the\nresulting pointer to a query handle. If the arguments are passed in the wrong\norder, the casts will work, however, there is a good chance that the underlying\ndatabase operation will fail, or will even cause an invalid memory access.
To ensure that the pointer retrieved from the first argument is indeed a pointer\nto a database handle and, similarly, that the pointer retrieved from the second\nargument is indeed a pointer to a query handle, the implementation of\nqueryHasRecords() has to perform a type validation. Retaining the JavaScript\nclass constructor from which the database handle was instantiated and the\nconstructor from which the query handle was instantiated in napi_refs can\nhelp, because napi_instanceof() can then be used to ensure that the instances\npassed into queryHashRecords() are indeed of the correct type.
Unfortunately, napi_instanceof() does not protect against prototype\nmanipulation. For example, the prototype of the database handle instance can be\nset to the prototype of the constructor for query handle instances. In this\ncase, the database handle instance can appear as a query handle instance, and it\nwill pass the napi_instanceof() test for a query handle instance, while still\ncontaining a pointer to a database handle.
To this end, Node-API provides type-tagging capabilities.
\nA type tag is a 128-bit integer unique to the addon. Node-API provides the\nnapi_type_tag structure for storing a type tag. When such a value is passed\nalong with a JavaScript object or external stored in a napi_value to\nnapi_type_tag_object(), the JavaScript object will be \"marked\" with the\ntype tag. The \"mark\" is invisible on the JavaScript side. When a JavaScript\nobject arrives into a native binding, napi_check_object_type_tag() can be used\nalong with the original type tag to determine whether the JavaScript object was\npreviously \"marked\" with the type tag. This creates a type-checking capability\nof a higher fidelity than napi_instanceof() can provide, because such type-\ntagging survives prototype manipulation and addon unloading/reloading.
Continuing the above example, the following skeleton addon implementation\nillustrates the use of napi_type_tag_object() and\nnapi_check_object_type_tag().
// This value is the type tag for a database handle. The command\n//\n// uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\\1, 0x\\2/'\n//\n// can be used to obtain the two values with which to initialize the structure.\nstatic const napi_type_tag DatabaseHandleTypeTag = {\n 0x1edf75a38336451d, 0xa5ed9ce2e4c00c38\n};\n\n// This value is the type tag for a query handle.\nstatic const napi_type_tag QueryHandleTypeTag = {\n 0x9c73317f9fad44a3, 0x93c3920bf3b0ad6a\n};\n\nstatic napi_value\nopenDatabase(napi_env env, napi_callback_info info) {\n napi_status status;\n napi_value result;\n\n // Perform the underlying action which results in a database handle.\n DatabaseHandle* dbHandle = open_database();\n\n // Create a new, empty JS object.\n status = napi_create_object(env, &result);\n if (status != napi_ok) return NULL;\n\n // Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.\n status = napi_type_tag_object(env, result, &DatabaseHandleTypeTag);\n if (status != napi_ok) return NULL;\n\n // Store the pointer to the `DatabaseHandle` structure inside the JS object.\n status = napi_wrap(env, result, dbHandle, NULL, NULL, NULL);\n if (status != napi_ok) return NULL;\n\n return result;\n}\n\n// Later when we receive a JavaScript object purporting to be a database handle\n// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a\n// handle.\n\nstatic napi_value\nquery(napi_env env, napi_callback_info info) {\n napi_status status;\n size_t argc = 2;\n napi_value argv[2];\n bool is_db_handle;\n\n status = napi_get_cb_info(env, info, &argc, argv, NULL, NULL);\n if (status != napi_ok) return NULL;\n\n // Check that the object passed as the first parameter has the previously\n // applied tag.\n status = napi_check_object_type_tag(env,\n argv[0],\n &DatabaseHandleTypeTag,\n &is_db_handle);\n if (status != napi_ok) return NULL;\n\n // Throw a `TypeError` if it doesn't.\n if (!is_db_handle) {\n // Throw a TypeError.\n return NULL;\n }\n}\n",
"modules": [
{
"textRaw": "`napi_define_class`",
"name": "`napi_define_class`",
"type": "module",
"meta": {
"added": [
"v8.0.0"
],
"changes": [],
"napiVersion": [
1
]
},
"desc": "napi_status napi_define_class(napi_env env,\n const char* utf8name,\n size_t length,\n napi_callback constructor,\n void* data,\n size_t property_count,\n const napi_property_descriptor* properties,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] utf8name: Name of the JavaScript constructor function. For clarity,\nit is recommended to use the C++ class name when wrapping a C++ class.[in] length: The length of the utf8name in bytes, or NAPI_AUTO_LENGTH\nif it is null-terminated.[in] constructor: Callback function that handles constructing instances\nof the class. When wrapping a C++ class, this method must be a static member\nwith the napi_callback signature. A C++ class constructor cannot be\nused. napi_callback provides more details.[in] data: Optional data to be passed to the constructor callback as\nthe data property of the callback info.[in] property_count: Number of items in the properties array argument.[in] properties: Array of property descriptors describing static and\ninstance data properties, accessors, and methods on the class\nSee napi_property_descriptor.[out] result: A napi_value representing the constructor function for\nthe class.Returns napi_ok if the API succeeded.
Defines a JavaScript class, including:
\nconstructor can be used to\ninstantiate a new C++ class instance, which can then be placed inside the\nJavaScript object instance being constructed using napi_wrap.napi_static attribute).prototype object. When wrapping a\nC++ class, non-static data properties, accessors, and methods of the C++\nclass can be called from the static functions given in the property\ndescriptors without the napi_static attribute after retrieving the C++ class\ninstance placed inside the JavaScript object instance by using\nnapi_unwrap.When wrapping a C++ class, the C++ constructor callback passed via constructor\nshould be a static method on the class that calls the actual class constructor,\nthen wraps the new C++ instance in a JavaScript object, and returns the wrapper\nobject. See napi_wrap for details.
The JavaScript constructor function returned from napi_define_class is\noften saved and used later to construct new instances of the class from native\ncode, and/or to check whether provided values are instances of the class. In\nthat case, to prevent the function value from being garbage-collected, a\nstrong persistent reference to it can be created using\nnapi_create_reference, ensuring that the reference count is kept >= 1.
Any non-NULL data which is passed to this API via the data parameter or via\nthe data field of the napi_property_descriptor array items can be associated\nwith the resulting JavaScript constructor (which is returned in the result\nparameter) and freed whenever the class is garbage-collected by passing both\nthe JavaScript function and the data to napi_add_finalizer.
napi_status napi_wrap(napi_env env,\n napi_value js_object,\n void* native_object,\n napi_finalize finalize_cb,\n void* finalize_hint,\n napi_ref* result);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object that will be the wrapper for the\nnative object.[in] native_object: The native instance that will be wrapped in the\nJavaScript object.[in] finalize_cb: Optional native callback that can be used to free the\nnative instance when the JavaScript object has been garbage-collected.\nnapi_finalize provides more details.[in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.[out] result: Optional reference to the wrapped object.Returns napi_ok if the API succeeded.
Wraps a native instance in a JavaScript object. The native instance can be\nretrieved later using napi_unwrap().
When JavaScript code invokes a constructor for a class that was defined using\nnapi_define_class(), the napi_callback for the constructor is invoked.\nAfter constructing an instance of the native class, the callback must then call\nnapi_wrap() to wrap the newly constructed instance in the already-created\nJavaScript object that is the this argument to the constructor callback.\n(That this object was created from the constructor function's prototype,\nso it already has definitions of all the instance properties and methods.)
Typically when wrapping a class instance, a finalize callback should be\nprovided that simply deletes the native instance that is received as the data\nargument to the finalize callback.
The optional returned reference is initially a weak reference, meaning it\nhas a reference count of 0. Typically this reference count would be incremented\ntemporarily during async operations that require the instance to remain valid.
\nCaution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.
Finalizer callbacks may be deferred, leaving a window where the object has\nbeen garbage collected (and the weak reference is invalid) but the finalizer\nhasn't been called yet. When using napi_get_reference_value() on weak\nreferences returned by napi_wrap(), you should still handle an empty result.
Calling napi_wrap() a second time on an object will return an error. To\nassociate another native instance with the object, use napi_remove_wrap()\nfirst.
napi_status napi_unwrap(napi_env env,\n napi_value js_object,\n void** result);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The object associated with the native instance.[out] result: Pointer to the wrapped native instance.Returns napi_ok if the API succeeded.
Retrieves a native instance that was previously wrapped in a JavaScript\nobject using napi_wrap().
When JavaScript code invokes a method or property accessor on the class, the\ncorresponding napi_callback is invoked. If the callback is for an instance\nmethod or accessor, then the this argument to the callback is the wrapper\nobject; the wrapped C++ instance that is the target of the call can be obtained\nthen by calling napi_unwrap() on the wrapper object.
napi_status napi_remove_wrap(napi_env env,\n napi_value js_object,\n void** result);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The object associated with the native instance.[out] result: Pointer to the wrapped native instance.Returns napi_ok if the API succeeded.
Retrieves a native instance that was previously wrapped in the JavaScript\nobject js_object using napi_wrap() and removes the wrapping. If a finalize\ncallback was associated with the wrapping, it will no longer be called when the\nJavaScript object becomes garbage-collected.
napi_status napi_type_tag_object(napi_env env,\n napi_value js_object,\n const napi_type_tag* type_tag);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object or external to be marked.[in] type_tag: The tag with which the object is to be marked.Returns napi_ok if the API succeeded.
Associates the value of the type_tag pointer with the JavaScript object or\nexternal. napi_check_object_type_tag() can then be used to compare the tag\nthat was attached to the object with one owned by the addon to ensure that the\nobject has the right type.
If the object already has an associated type tag, this API will return\nnapi_invalid_arg.
napi_status napi_check_object_type_tag(napi_env env,\n napi_value js_object,\n const napi_type_tag* type_tag,\n bool* result);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object or external whose type tag to\nexamine.[in] type_tag: The tag with which to compare any tag found on the object.[out] result: Whether the type tag given matched the type tag on the\nobject. false is also returned if no type tag was found on the object.Returns napi_ok if the API succeeded.
Compares the pointer given as type_tag with any that can be found on\njs_object. If no tag is found on js_object or, if a tag is found but it does\nnot match type_tag, then result is set to false. If a tag is found and it\nmatches type_tag, then result is set to true.
napi_status napi_add_finalizer(napi_env env,\n napi_value js_object,\n void* finalize_data,\n node_api_basic_finalize finalize_cb,\n void* finalize_hint,\n napi_ref* result);\n\n[in] env: The environment that the API is invoked under.[in] js_object: The JavaScript object to which the native data will be\nattached.[in] finalize_data: Optional data to be passed to finalize_cb.[in] finalize_cb: Native callback that will be used to free the\nnative data when the JavaScript object has been garbage-collected.\nnapi_finalize provides more details.[in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.[out] result: Optional reference to the JavaScript object.Returns napi_ok if the API succeeded.
Adds a napi_finalize callback which will be called when the JavaScript object\nin js_object has been garbage-collected.
This API can be called multiple times on a single JavaScript object.
\nCaution: The optional returned reference (if obtained) should be deleted via\nnapi_delete_reference ONLY in response to the finalize callback\ninvocation. If it is deleted before then, then the finalize callback may never\nbe invoked. Therefore, when obtaining a reference a finalize callback is also\nrequired in order to enable correct disposal of the reference.
napi_status node_api_post_finalizer(node_api_basic_env env,\n napi_finalize finalize_cb,\n void* finalize_data,\n void* finalize_hint);\n\n[in] env: The environment that the API is invoked under.[in] finalize_cb: Native callback that will be used to free the\nnative data when the JavaScript object has been garbage-collected.\nnapi_finalize provides more details.[in] finalize_data: Optional data to be passed to finalize_cb.[in] finalize_hint: Optional contextual hint that is passed to the\nfinalize callback.Returns napi_ok if the API succeeded.
Schedules a napi_finalize callback to be called asynchronously in the\nevent loop.
Normally, finalizers are called while the GC (garbage collector) collects\nobjects. At that point calling any Node-API that may cause changes in the GC\nstate will be disabled and will crash Node.js.
\nnode_api_post_finalizer helps to work around this limitation by allowing the\nadd-on to defer calls to such Node-APIs to a point in time outside of the GC\nfinalization.
Addon modules often need to leverage async helpers from libuv as part of their\nimplementation. This allows them to schedule work to be executed asynchronously\nso that their methods can return in advance of the work being completed. This\nallows them to avoid blocking overall execution of the Node.js application.
\nNode-API provides an ABI-stable interface for these\nsupporting functions which covers the most common asynchronous use cases.
\nNode-API defines the napi_async_work structure which is used to manage\nasynchronous workers. Instances are created/deleted with\nnapi_create_async_work and napi_delete_async_work.
The execute and complete callbacks are functions that will be\ninvoked when the executor is ready to execute and when it completes its\ntask respectively.
The execute function should avoid making any Node-API calls\nthat could result in the execution of JavaScript or interaction with\nJavaScript objects. Most often, any code that needs to make Node-API\ncalls should be made in complete callback instead.\nAvoid using the napi_env parameter in the execute callback as\nit will likely execute JavaScript.
These functions implement the following interfaces:
\ntypedef void (*napi_async_execute_callback)(napi_env env,\n void* data);\ntypedef void (*napi_async_complete_callback)(napi_env env,\n napi_status status,\n void* data);\n\nWhen these methods are invoked, the data parameter passed will be the\naddon-provided void* data that was passed into the\nnapi_create_async_work call.
Once created the async worker can be queued\nfor execution using the napi_queue_async_work function:
napi_status napi_queue_async_work(node_api_basic_env env,\n napi_async_work work);\n\nnapi_cancel_async_work can be used if the work needs\nto be cancelled before the work has started execution.
After calling napi_cancel_async_work, the complete callback\nwill be invoked with a status value of napi_cancelled.\nThe work should not be deleted before the complete\ncallback invocation, even when it was cancelled.
napi_status napi_create_async_work(napi_env env,\n napi_value async_resource,\n napi_value async_resource_name,\n napi_async_execute_callback execute,\n napi_async_complete_callback complete,\n void* data,\n napi_async_work* result);\n\n[in] env: The environment that the API is invoked under.[in] async_resource: An optional object associated with the async work\nthat will be passed to possible async_hooks init hooks.[in] async_resource_name: Identifier for the kind of resource that is being\nprovided for diagnostic information exposed by the async_hooks API.[in] execute: The native function which should be called to execute the\nlogic asynchronously. The given function is called from a worker pool thread\nand can execute in parallel with the main event loop thread.[in] complete: The native function which will be called when the\nasynchronous logic is completed or is cancelled. The given function is called\nfrom the main event loop thread. napi_async_complete_callback provides\nmore details.[in] data: User-provided data context. This will be passed back into the\nexecute and complete functions.[out] result: napi_async_work* which is the handle to the newly created\nasync work.Returns napi_ok if the API succeeded.
This API allocates a work object that is used to execute logic asynchronously.\nIt should be freed using napi_delete_async_work once the work is no longer\nrequired.
async_resource_name should be a null-terminated, UTF-8-encoded string.
The async_resource_name identifier is provided by the user and should be\nrepresentative of the type of async work being performed. It is also recommended\nto apply namespacing to the identifier, e.g. by including the module name. See\nthe async_hooks documentation for more information.
napi_status napi_delete_async_work(napi_env env,\n napi_async_work work);\n\n[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call to napi_create_async_work.Returns napi_ok if the API succeeded.
This API frees a previously allocated work object.
\nThis API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_delete_async_work`" }, { "textRaw": "`napi_queue_async_work`", "name": "`napi_queue_async_work`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_queue_async_work(node_api_basic_env env,\n napi_async_work work);\n\n[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call to napi_create_async_work.Returns napi_ok if the API succeeded.
This API requests that the previously allocated work be scheduled\nfor execution. Once it returns successfully, this API must not be called again\nwith the same napi_async_work item or the result will be undefined.
napi_status napi_cancel_async_work(node_api_basic_env env,\n napi_async_work work);\n\n[in] env: The environment that the API is invoked under.[in] work: The handle returned by the call to napi_create_async_work.Returns napi_ok if the API succeeded.
This API cancels queued work if it has not yet\nbeen started. If it has already started executing, it cannot be\ncancelled and napi_generic_failure will be returned. If successful,\nthe complete callback will be invoked with a status value of\nnapi_cancelled. The work should not be deleted before the complete\ncallback invocation, even if it has been successfully cancelled.
This API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_cancel_async_work`" } ], "displayName": "Simple asynchronous operations" }, { "textRaw": "Custom asynchronous operations", "name": "custom_asynchronous_operations", "type": "misc", "desc": "The simple asynchronous work APIs above may not be appropriate for every\nscenario. When using any other asynchronous mechanism, the following APIs\nare necessary to ensure an asynchronous operation is properly tracked by\nthe runtime.
", "modules": [ { "textRaw": "`napi_async_init`", "name": "`napi_async_init`", "type": "module", "meta": { "added": [ "v8.6.0" ], "changes": [ { "version": "v25.0.0", "pr-url": "https://github.com/nodejs/node/pull/59828", "description": "The `async_resource` object will now be held as a strong reference." } ], "napiVersion": [ 1 ] }, "desc": "napi_status napi_async_init(napi_env env,\n napi_value async_resource,\n napi_value async_resource_name,\n napi_async_context* result)\n\n[in] env: The environment that the API is invoked under.[in] async_resource: Object associated with the async work\nthat will be passed to possible async_hooks init hooks and can be\naccessed by async_hooks.executionAsyncResource().[in] async_resource_name: Identifier for the kind of resource that is being\nprovided for diagnostic information exposed by the async_hooks API.[out] result: The initialized async context.Returns napi_ok if the API succeeded.
In order to retain ABI compatibility with previous versions, passing NULL\nfor async_resource does not result in an error. However, this is not\nrecommended as this will result in undesirable behavior with async_hooks\ninit hooks and async_hooks.executionAsyncResource() as the resource is\nnow required by the underlying async_hooks implementation in order to provide\nthe linkage between async callbacks.
Previous versions of this API were not maintaining a strong reference to\nasync_resource while the napi_async_context object existed and instead\nexpected the caller to hold a strong reference. This has been changed, as a\ncorresponding call to napi_async_destroy for every call to\nnapi_async_init() is a requirement in any case to avoid memory leaks.
napi_status napi_async_destroy(napi_env env,\n napi_async_context async_context);\n\n[in] env: The environment that the API is invoked under.[in] async_context: The async context to be destroyed.Returns napi_ok if the API succeeded.
This API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_async_destroy`" }, { "textRaw": "`napi_make_callback`", "name": "`napi_make_callback`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v8.6.0", "pr-url": "https://github.com/nodejs/node/pull/15189", "description": "Added `async_context` parameter." } ], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_make_callback(napi_env env,\n napi_async_context async_context,\n napi_value recv,\n napi_value func,\n size_t argc,\n const napi_value* argv,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] async_context: Context for the async operation that is\ninvoking the callback. This should normally be a value previously\nobtained from napi_async_init.\nIn order to retain ABI compatibility with previous versions, passing NULL\nfor async_context does not result in an error. However, this results\nin incorrect operation of async hooks. Potential issues include loss of\nasync context when using the AsyncLocalStorage API.[in] recv: The this value passed to the called function.[in] func: napi_value representing the JavaScript function to be invoked.[in] argc: The count of elements in the argv array.[in] argv: Array of JavaScript values as napi_value representing the\narguments to the function. If argc is zero this parameter may be\nomitted by passing in NULL.[out] result: napi_value representing the JavaScript object returned.Returns napi_ok if the API succeeded.
This method allows a JavaScript function object to be called from a native\nadd-on. This API is similar to napi_call_function. However, it is used to call\nfrom native code back into JavaScript after returning from an async\noperation (when there is no other script on the stack). It is a fairly simple\nwrapper around node::MakeCallback.
Note it is not necessary to use napi_make_callback from within a\nnapi_async_complete_callback; in that situation the callback's async\ncontext has already been set up, so a direct call to napi_call_function\nis sufficient and appropriate. Use of the napi_make_callback function\nmay be required when implementing custom async behavior that does not use\nnapi_create_async_work.
Any process.nextTicks or Promises scheduled on the microtask queue by\nJavaScript during the callback are ran before returning back to C/C++.
NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,\n napi_value resource_object,\n napi_async_context context,\n napi_callback_scope* result)\n\n[in] env: The environment that the API is invoked under.[in] resource_object: An object associated with the async work\nthat will be passed to possible async_hooks init hooks. This\nparameter has been deprecated and is ignored at runtime. Use the\nasync_resource parameter in napi_async_init instead.[in] context: Context for the async operation that is invoking the callback.\nThis should be a value previously obtained from napi_async_init.[out] result: The newly created scope.There are cases (for example, resolving promises) where it is\nnecessary to have the equivalent of the scope associated with a callback\nin place when making certain Node-API calls. If there is no other script on\nthe stack the napi_open_callback_scope and\nnapi_close_callback_scope functions can be used to open/close\nthe required scope.
NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,\n napi_callback_scope scope)\n\n[in] env: The environment that the API is invoked under.[in] scope: The scope to be closed.This API can be called even if there is a pending JavaScript exception.
", "displayName": "`napi_close_callback_scope`" } ], "displayName": "Custom asynchronous operations" }, { "textRaw": "Version management", "name": "version_management", "type": "misc", "modules": [ { "textRaw": "`napi_get_node_version`", "name": "`napi_get_node_version`", "type": "module", "meta": { "added": [ "v8.4.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "typedef struct {\n uint32_t major;\n uint32_t minor;\n uint32_t patch;\n const char* release;\n} napi_node_version;\n\nnapi_status napi_get_node_version(node_api_basic_env env,\n const napi_node_version** version);\n\n[in] env: The environment that the API is invoked under.[out] version: A pointer to version information for Node.js itself.Returns napi_ok if the API succeeded.
This function fills the version struct with the major, minor, and patch\nversion of Node.js that is currently running, and the release field with the\nvalue of process.release.name.
The returned buffer is statically allocated and does not need to be freed.
", "displayName": "`napi_get_node_version`" }, { "textRaw": "`napi_get_version`", "name": "`napi_get_version`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_get_version(node_api_basic_env env,\n uint32_t* result);\n\n[in] env: The environment that the API is invoked under.[out] result: The highest version of Node-API supported.Returns napi_ok if the API succeeded.
This API returns the highest Node-API version supported by the\nNode.js runtime. Node-API is planned to be additive such that\nnewer releases of Node.js may support additional API functions.\nIn order to allow an addon to use a newer function when running with\nversions of Node.js that support it, while providing\nfallback behavior when running with Node.js versions that don't\nsupport it:
\nnapi_get_version() to determine if the API is available.uv_dlsym().NAPI_EXTERN napi_status napi_adjust_external_memory(node_api_basic_env env,\n int64_t change_in_bytes,\n int64_t* result);\n\n[in] env: The environment that the API is invoked under.[in] change_in_bytes: The change in externally allocated memory that is kept\nalive by JavaScript objects.[out] result: The adjusted value. This value should reflect the\ntotal amount of external memory with the given change_in_bytes included.\nThe absolute value of the returned value should not be depended on.\nFor example, implementations may use a single counter for all addons, or a\ncounter for each addon.Returns napi_ok if the API succeeded.
This function gives the runtime an indication of the amount of externally\nallocated memory that is kept alive by JavaScript objects\n(i.e. a JavaScript object that points to its own memory allocated by a\nnative addon). Registering externally allocated memory may, but is not\nguaranteed to, trigger global garbage collections more\noften than it would otherwise.
\nThis function is expected to be called in a manner such that an\naddon does not decrease the external memory more than it has\nincreased the external memory.
", "displayName": "`napi_adjust_external_memory`" } ], "displayName": "Memory management" }, { "textRaw": "Promises", "name": "promises", "type": "misc", "desc": "Node-API provides facilities for creating Promise objects as described in\nSection Promise objects of the ECMA specification. It implements promises as a pair of\nobjects. When a promise is created by napi_create_promise(), a \"deferred\"\nobject is created and returned alongside the Promise. The deferred object is\nbound to the created Promise and is the only means to resolve or reject the\nPromise using napi_resolve_deferred() or napi_reject_deferred(). The\ndeferred object that is created by napi_create_promise() is freed by\nnapi_resolve_deferred() or napi_reject_deferred(). The Promise object may\nbe returned to JavaScript where it can be used in the usual fashion.
For example, to create a promise and pass it to an asynchronous worker:
\nnapi_deferred deferred;\nnapi_value promise;\nnapi_status status;\n\n// Create the promise.\nstatus = napi_create_promise(env, &deferred, &promise);\nif (status != napi_ok) return NULL;\n\n// Pass the deferred to a function that performs an asynchronous action.\ndo_something_asynchronous(deferred);\n\n// Return the promise to JS\nreturn promise;\n\nThe above function do_something_asynchronous() would perform its asynchronous\naction and then it would resolve or reject the deferred, thereby concluding the\npromise and freeing the deferred:
napi_deferred deferred;\nnapi_value undefined;\nnapi_status status;\n\n// Create a value with which to conclude the deferred.\nstatus = napi_get_undefined(env, &undefined);\nif (status != napi_ok) return NULL;\n\n// Resolve or reject the promise associated with the deferred depending on\n// whether the asynchronous action succeeded.\nif (asynchronous_action_succeeded) {\n status = napi_resolve_deferred(env, deferred, undefined);\n} else {\n status = napi_reject_deferred(env, deferred, undefined);\n}\nif (status != napi_ok) return NULL;\n\n// At this point the deferred has been freed, so we should assign NULL to it.\ndeferred = NULL;\n",
"modules": [
{
"textRaw": "`napi_create_promise`",
"name": "`napi_create_promise`",
"type": "module",
"meta": {
"added": [
"v8.5.0"
],
"changes": [],
"napiVersion": [
1
]
},
"desc": "napi_status napi_create_promise(napi_env env,\n napi_deferred* deferred,\n napi_value* promise);\n\n[in] env: The environment that the API is invoked under.[out] deferred: A newly created deferred object which can later be passed to\nnapi_resolve_deferred() or napi_reject_deferred() to resolve resp. reject\nthe associated promise.[out] promise: The JavaScript promise associated with the deferred object.Returns napi_ok if the API succeeded.
This API creates a deferred object and a JavaScript promise.
", "displayName": "`napi_create_promise`" }, { "textRaw": "`napi_resolve_deferred`", "name": "`napi_resolve_deferred`", "type": "module", "meta": { "added": [ "v8.5.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_resolve_deferred(napi_env env,\n napi_deferred deferred,\n napi_value resolution);\n\n[in] env: The environment that the API is invoked under.[in] deferred: The deferred object whose associated promise to resolve.[in] resolution: The value with which to resolve the promise.This API resolves a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to resolve JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.
The deferred object is freed upon successful completion.
", "displayName": "`napi_resolve_deferred`" }, { "textRaw": "`napi_reject_deferred`", "name": "`napi_reject_deferred`", "type": "module", "meta": { "added": [ "v8.5.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_reject_deferred(napi_env env,\n napi_deferred deferred,\n napi_value rejection);\n\n[in] env: The environment that the API is invoked under.[in] deferred: The deferred object whose associated promise to resolve.[in] rejection: The value with which to reject the promise.This API rejects a JavaScript promise by way of the deferred object\nwith which it is associated. Thus, it can only be used to reject JavaScript\npromises for which the corresponding deferred object is available. This\neffectively means that the promise must have been created using\nnapi_create_promise() and the deferred object returned from that call must\nhave been retained in order to be passed to this API.
The deferred object is freed upon successful completion.
", "displayName": "`napi_reject_deferred`" }, { "textRaw": "`napi_is_promise`", "name": "`napi_is_promise`", "type": "module", "meta": { "added": [ "v8.5.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "napi_status napi_is_promise(napi_env env,\n napi_value value,\n bool* is_promise);\n\n[in] env: The environment that the API is invoked under.[in] value: The value to examine[out] is_promise: Flag indicating whether promise is a native promise\nobject (that is, a promise object created by the underlying engine).Node-API provides an API for executing a string containing JavaScript using the\nunderlying JavaScript engine.
", "modules": [ { "textRaw": "`napi_run_script`", "name": "`napi_run_script`", "type": "module", "meta": { "added": [ "v8.5.0" ], "changes": [], "napiVersion": [ 1 ] }, "desc": "NAPI_EXTERN napi_status napi_run_script(napi_env env,\n napi_value script,\n napi_value* result);\n\n[in] env: The environment that the API is invoked under.[in] script: A JavaScript string containing the script to execute.[out] result: The value resulting from having executed the script.This function executes a string of JavaScript code and returns its result with\nthe following caveats:
\neval, this function does not allow the script to access the current\nlexical scope, and therefore also does not allow to access the\nmodule scope, meaning that pseudo-globals such as require will not be\navailable.var declarations\nin the script will be added to the global object. Variable declarations\nmade using let and const will be visible globally, but will not be added\nto the global object.this is global within the script.Node-API provides a function for getting the current event loop associated with\na specific napi_env.
NAPI_EXTERN napi_status napi_get_uv_event_loop(node_api_basic_env env,\n struct uv_loop_s** loop);\n\n[in] env: The environment that the API is invoked under.[out] loop: The current libuv loop instance.Note: While libuv has been relatively stable over time, it does\nnot provide an ABI stability guarantee. Use of this function should be avoided.\nIts use may result in an addon that does not work across Node.js versions.\nasynchronous-thread-safe-function-calls\nare an alternative for many use cases.
", "displayName": "`napi_get_uv_event_loop`" } ], "displayName": "libuv event loop" }, { "textRaw": "Asynchronous thread-safe function calls", "name": "asynchronous_thread-safe_function_calls", "type": "misc", "desc": "JavaScript functions can normally only be called from a native addon's main\nthread. If an addon creates additional threads, then Node-API functions that\nrequire a napi_env, napi_value, or napi_ref must not be called from those\nthreads.
When an addon has additional threads and JavaScript functions need to be invoked\nbased on the processing completed by those threads, those threads must\ncommunicate with the addon's main thread so that the main thread can invoke the\nJavaScript function on their behalf. The thread-safe function APIs provide an\neasy way to do this.
\nThese APIs provide the type napi_threadsafe_function as well as APIs to\ncreate, destroy, and call objects of this type.\nnapi_create_threadsafe_function() creates a persistent reference to a\nnapi_value that holds a JavaScript function which can be called from multiple\nthreads. The calls happen asynchronously. This means that values with which the\nJavaScript callback is to be called will be placed in a queue, and, for each\nvalue in the queue, a call will eventually be made to the JavaScript function.
Upon creation of a napi_threadsafe_function a napi_finalize callback can be\nprovided. This callback will be invoked on the main thread when the thread-safe\nfunction is about to be destroyed. It receives the context and the finalize data\ngiven during construction, and provides an opportunity for cleaning up after the\nthreads e.g. by calling uv_thread_join(). Aside from the main loop thread,\nno threads should be using the thread-safe function after the finalize callback\ncompletes.
The context given during the call to napi_create_threadsafe_function() can\nbe retrieved from any thread with a call to\nnapi_get_threadsafe_function_context().
napi_call_threadsafe_function() can be used for initiating a call into\nJavaScript. napi_call_threadsafe_function() accepts a parameter which controls\nwhether the API behaves blockingly. If set to napi_tsfn_nonblocking, the API\nbehaves non-blockingly, returning napi_queue_full if the queue was full,\npreventing data from being successfully added to the queue. If set to\nnapi_tsfn_blocking, the API blocks until space becomes available in the queue.\nnapi_call_threadsafe_function() never blocks if the thread-safe function was\ncreated with a maximum queue size of 0.
napi_call_threadsafe_function() should not be called with napi_tsfn_blocking\nfrom a JavaScript thread, because, if the queue is full, it may cause the\nJavaScript thread to deadlock.
The actual call into JavaScript is controlled by the callback given via the\ncall_js_cb parameter. call_js_cb is invoked on the main thread once for each\nvalue that was placed into the queue by a successful call to\nnapi_call_threadsafe_function(). If such a callback is not given, a default\ncallback will be used, and the resulting JavaScript call will have no arguments.\nThe call_js_cb callback receives the JavaScript function to call as a\nnapi_value in its parameters, as well as the void* context pointer used when\ncreating the napi_threadsafe_function, and the next data pointer that was\ncreated by one of the secondary threads. The callback can then use an API such\nas napi_call_function() to call into JavaScript.
The callback may also be invoked with env and call_js_cb both set to NULL\nto indicate that calls into JavaScript are no longer possible, while items\nremain in the queue that may need to be freed. This normally occurs when the\nNode.js process exits while there is a thread-safe function still active.
It is not necessary to call into JavaScript via napi_make_callback() because\nNode-API runs call_js_cb in a context appropriate for callbacks.
Zero or more queued items may be invoked in each tick of the event loop.\nApplications should not depend on a specific behavior other than progress in\ninvoking callbacks will be made and events will be invoked\nas time moves forward.
", "displayName": "Calling a thread-safe function" }, { "textRaw": "Reference counting of thread-safe functions", "name": "reference_counting_of_thread-safe_functions", "type": "module", "desc": "Threads can be added to and removed from a napi_threadsafe_function object\nduring its existence. Thus, in addition to specifying an initial number of\nthreads upon creation, napi_acquire_threadsafe_function can be called to\nindicate that a new thread will start making use of the thread-safe function.\nSimilarly, napi_release_threadsafe_function can be called to indicate that an\nexisting thread will stop making use of the thread-safe function.
napi_threadsafe_function objects are destroyed when every thread which uses\nthe object has called napi_release_threadsafe_function() or has received a\nreturn status of napi_closing in response to a call to\nnapi_call_threadsafe_function. The queue is emptied before the\nnapi_threadsafe_function is destroyed. napi_release_threadsafe_function()\nshould be the last API call made in conjunction with a given\nnapi_threadsafe_function, because after the call completes, there is no\nguarantee that the napi_threadsafe_function is still allocated. For the same\nreason, do not use a thread-safe function\nafter receiving a return value of napi_closing in response to a call to\nnapi_call_threadsafe_function. Data associated with the\nnapi_threadsafe_function can be freed in its napi_finalize callback which\nwas passed to napi_create_threadsafe_function(). The parameter\ninitial_thread_count of napi_create_threadsafe_function marks the initial\nnumber of acquisitions of the thread-safe functions, instead of calling\nnapi_acquire_threadsafe_function multiple times at creation.
Once the number of threads making use of a napi_threadsafe_function reaches\nzero, no further threads can start making use of it by calling\nnapi_acquire_threadsafe_function(). In fact, all subsequent API calls\nassociated with it, except napi_release_threadsafe_function(), will return an\nerror value of napi_closing.
The thread-safe function can be \"aborted\" by giving a value of napi_tsfn_abort\nto napi_release_threadsafe_function(). This will cause all subsequent APIs\nassociated with the thread-safe function except\nnapi_release_threadsafe_function() to return napi_closing even before its\nreference count reaches zero. In particular, napi_call_threadsafe_function()\nwill return napi_closing, thus informing the threads that it is no longer\npossible to make asynchronous calls to the thread-safe function. This can be\nused as a criterion for terminating the thread. Upon receiving a return value\nof napi_closing from napi_call_threadsafe_function() a thread must not use\nthe thread-safe function anymore because it is no longer guaranteed to\nbe allocated.
Similarly to libuv handles, thread-safe functions can be \"referenced\" and\n\"unreferenced\". A \"referenced\" thread-safe function will cause the event loop on\nthe thread on which it is created to remain alive until the thread-safe function\nis destroyed. In contrast, an \"unreferenced\" thread-safe function will not\nprevent the event loop from exiting. The APIs napi_ref_threadsafe_function and\nnapi_unref_threadsafe_function exist for this purpose.
Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed.
NAPI_EXTERN napi_status\nnapi_create_threadsafe_function(napi_env env,\n napi_value func,\n napi_value async_resource,\n napi_value async_resource_name,\n size_t max_queue_size,\n size_t initial_thread_count,\n void* thread_finalize_data,\n napi_finalize thread_finalize_cb,\n void* context,\n napi_threadsafe_function_call_js call_js_cb,\n napi_threadsafe_function* result);\n\n[in] env: The environment that the API is invoked under.[in] func: An optional JavaScript function to call from another thread. It\nmust be provided if NULL is passed to call_js_cb.[in] async_resource: An optional object associated with the async work that\nwill be passed to possible async_hooks init hooks.[in] async_resource_name: A JavaScript string to provide an identifier for\nthe kind of resource that is being provided for diagnostic information exposed\nby the async_hooks API.[in] max_queue_size: Maximum size of the queue. 0 for no limit.[in] initial_thread_count: The initial number of acquisitions, i.e. the\ninitial number of threads, including the main thread, which will be making use\nof this function.[in] thread_finalize_data: Optional data to be passed to thread_finalize_cb.[in] thread_finalize_cb: Optional function to call when the\nnapi_threadsafe_function is being destroyed.[in] context: Optional data to attach to the resulting\nnapi_threadsafe_function.[in] call_js_cb: Optional callback which calls the JavaScript function in\nresponse to a call on a different thread. This callback will be called on the\nmain thread. If not given, the JavaScript function will be called with no\nparameters and with undefined as its this value.\nnapi_threadsafe_function_call_js provides more details.[out] result: The asynchronous thread-safe JavaScript function.Change History:
\nVersion 10 (NAPI_VERSION is defined as 10 or higher):
Uncaught exceptions thrown in call_js_cb are handled with the\n'uncaughtException' event, instead of being ignored.
NAPI_EXTERN napi_status\nnapi_get_threadsafe_function_context(napi_threadsafe_function func,\n void** result);\n\n[in] func: The thread-safe function for which to retrieve the context.[out] result: The location where to store the context.This API may be called from any thread which makes use of func.
NAPI_EXTERN napi_status\nnapi_call_threadsafe_function(napi_threadsafe_function func,\n void* data,\n napi_threadsafe_function_call_mode is_blocking);\n\n[in] func: The asynchronous thread-safe JavaScript function to invoke.[in] data: Data to send into JavaScript via the callback call_js_cb\nprovided during the creation of the thread-safe JavaScript function.[in] is_blocking: Flag whose value can be either napi_tsfn_blocking to\nindicate that the call should block if the queue is full or\nnapi_tsfn_nonblocking to indicate that the call should return immediately\nwith a status of napi_queue_full whenever the queue is full.This API should not be called with napi_tsfn_blocking from a JavaScript\nthread, because, if the queue is full, it may cause the JavaScript thread to\ndeadlock.
This API will return napi_closing if napi_release_threadsafe_function() was\ncalled with abort set to napi_tsfn_abort from any thread. The value is only\nadded to the queue if the API returns napi_ok.
This API may be called from any thread which makes use of func.
NAPI_EXTERN napi_status\nnapi_acquire_threadsafe_function(napi_threadsafe_function func);\n\n[in] func: The asynchronous thread-safe JavaScript function to start making\nuse of.A thread should call this API before passing func to any other thread-safe\nfunction APIs to indicate that it will be making use of func. This prevents\nfunc from being destroyed when all other threads have stopped making use of\nit.
This API may be called from any thread which will start making use of func.
NAPI_EXTERN napi_status\nnapi_release_threadsafe_function(napi_threadsafe_function func,\n napi_threadsafe_function_release_mode mode);\n\n[in] func: The asynchronous thread-safe JavaScript function whose reference\ncount to decrement.[in] mode: Flag whose value can be either napi_tsfn_release to indicate\nthat the current thread will make no further calls to the thread-safe\nfunction, or napi_tsfn_abort to indicate that in addition to the current\nthread, no other thread should make any further calls to the thread-safe\nfunction. If set to napi_tsfn_abort, further calls to\nnapi_call_threadsafe_function() will return napi_closing, and no further\nvalues will be placed in the queue.A thread should call this API when it stops making use of func. Passing func\nto any thread-safe APIs after having called this API has undefined results, as\nfunc may have been destroyed.
This API may be called from any thread which will stop making use of func.
NAPI_EXTERN napi_status\nnapi_ref_threadsafe_function(node_api_basic_env env, napi_threadsafe_function func);\n\n[in] env: The environment that the API is invoked under.[in] func: The thread-safe function to reference.This API is used to indicate that the event loop running on the main thread\nshould not exit until func has been destroyed. Similar to uv_ref it is\nalso idempotent.
Neither does napi_unref_threadsafe_function mark the thread-safe functions as\nable to be destroyed nor does napi_ref_threadsafe_function prevent it from\nbeing destroyed. napi_acquire_threadsafe_function and\nnapi_release_threadsafe_function are available for that purpose.
This API may only be called from the main thread.
", "displayName": "`napi_ref_threadsafe_function`" }, { "textRaw": "`napi_unref_threadsafe_function`", "name": "`napi_unref_threadsafe_function`", "type": "module", "meta": { "added": [ "v10.6.0" ], "changes": [], "napiVersion": [ 4 ] }, "desc": "NAPI_EXTERN napi_status\nnapi_unref_threadsafe_function(node_api_basic_env env, napi_threadsafe_function func);\n\n[in] env: The environment that the API is invoked under.[in] func: The thread-safe function to unreference.This API is used to indicate that the event loop running on the main thread\nmay exit before func is destroyed. Similar to uv_unref it is also\nidempotent.
This API may only be called from the main thread.
", "displayName": "`napi_unref_threadsafe_function`" } ], "displayName": "Asynchronous thread-safe function calls" }, { "textRaw": "Miscellaneous utilities", "name": "miscellaneous_utilities", "type": "misc", "modules": [ { "textRaw": "`node_api_get_module_file_name`", "name": "`node_api_get_module_file_name`", "type": "module", "meta": { "added": [ "v15.9.0", "v14.18.0", "v12.22.0" ], "changes": [], "napiVersion": [ 9 ] }, "desc": "NAPI_EXTERN napi_status\nnode_api_get_module_file_name(node_api_basic_env env, const char** result);\n\n\n[in] env: The environment that the API is invoked under.[out] result: A URL containing the absolute path of the\nlocation from which the add-on was loaded. For a file on the local\nfile system it will start with file://. The string is null-terminated and\nowned by env and must thus not be modified or freed.result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.
Node.js comes with a variety of CLI options. These options expose built-in\ndebugging, multiple ways to execute scripts, and other helpful runtime options.
\nTo view this documentation as a manual page in a terminal, run man node.
node [options] [V8 options] [<program-entry-point> | -e \"script\" | -] [--] [arguments]
node inspect [<program-entry-point> | -e \"script\" | <host>:<port>] …
node --v8-options
Execute without arguments to start the REPL.
\nFor more info about node inspect, see the debugger documentation.
The program entry point is a specifier-like string. If the string is not an\nabsolute path, it's resolved as a relative path from the current working\ndirectory. That entry point string is then resolved as if it's been requested\nby require() from the current working directory. If no corresponding file\nis found, an error is thrown.
By default, the resolved path is also loaded as if it's been requested by require(),\nunless one of the conditions below apply—then it's loaded as if it's been requested\nby import():
--import..mjs, .mts or .wasm extension..cjs extension, and the nearest parent\npackage.json file contains a top-level \"type\" field with a value of\n\"module\".See module resolution and loading for more details.
", "displayName": "Program entry point" }, { "textRaw": "Options", "name": "options", "type": "misc", "meta": { "changes": [ { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/23020", "description": "Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "All options, including V8 options, allow words to be separated by both\ndashes (-) or underscores (_). For example, --pending-deprecation is\nequivalent to --pending_deprecation.
If an option that takes a single value (such as --max-http-header-size) is\npassed more than once, then the last passed value is used. Options from the\ncommand line take precedence over options passed through the NODE_OPTIONS\nenvironment variable.
Alias for stdin. Analogous to the use of - in other command-line utilities,\nmeaning that the script is read from stdin, and the rest of the options\nare passed to that script.
Indicate the end of node options. Pass the rest of the arguments to the script.\nIf no script filename or eval/print script is supplied prior to this, then\nthe next argument is used as a script filename.
", "displayName": "`--`" }, { "textRaw": "`--abort-on-uncaught-exception`", "name": "`--abort-on-uncaught-exception`", "type": "module", "meta": { "added": [ "v0.10.8" ], "changes": [] }, "desc": "Aborting instead of exiting causes a core file to be generated for post-mortem\nanalysis using a debugger (such as lldb, gdb, and mdb).
If this flag is passed, the behavior can still be set to not abort through\nprocess.setUncaughtExceptionCaptureCallback() (and through usage of the\nnode:domain module that uses it).
When using the Permission Model, the process will not be able to use\nnative addons by default.\nAttempts to do so will throw an ERR_DLOPEN_DISABLED unless the\nuser explicitly passes the --allow-addons flag when starting Node.js.
Example:
\n// Attempt to require an native addon\nrequire('nodejs-addon-example');\n\n$ node --permission --allow-fs-read=* index.js\nnode:internal/modules/cjs/loader:1319\n return process.dlopen(module, path.toNamespacedPath(filename));\n ^\n\nError: Cannot load native addon because loading addons is disabled.\n at Module._extensions..node (node:internal/modules/cjs/loader:1319:18)\n at Module.load (node:internal/modules/cjs/loader:1091:32)\n at Module._load (node:internal/modules/cjs/loader:938:12)\n at Module.require (node:internal/modules/cjs/loader:1115:19)\n at require (node:internal/modules/helpers:130:18)\n at Object.<anonymous> (/home/index.js:1:15)\n at Module._compile (node:internal/modules/cjs/loader:1233:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1287:10)\n at Module.load (node:internal/modules/cjs/loader:1091:32)\n at Module._load (node:internal/modules/cjs/loader:938:12) {\n code: 'ERR_DLOPEN_DISABLED'\n}\n",
"displayName": "`--allow-addons`"
},
{
"textRaw": "`--allow-child-process`",
"name": "`--allow-child-process`",
"type": "module",
"meta": {
"added": [
"v20.0.0"
],
"changes": [
{
"version": [
"v24.4.0",
"v22.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/58853",
"description": "When spawning process with the permission model enabled. The flags are inherit to the child Node.js process through NODE_OPTIONS environment variable."
}
]
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "When using the Permission Model, the process will not be able to spawn any\nchild process by default.\nAttempts to do so will throw an ERR_ACCESS_DENIED unless the\nuser explicitly passes the --allow-child-process flag when starting Node.js.
Example:
\nconst childProcess = require('node:child_process');\n// Attempt to bypass the permission\nchildProcess.spawn('node', ['-e', 'require(\"fs\").writeFileSync(\"/new-file\", \"example\")']);\n\n$ node --permission --allow-fs-read=* index.js\nnode:internal/child_process:388\n const err = this._handle.spawn(options);\n ^\nError: Access to this API has been restricted\n at ChildProcess.spawn (node:internal/child_process:388:28)\n at node:internal/main/run_main_module:17:47 {\n code: 'ERR_ACCESS_DENIED',\n permission: 'ChildProcess'\n}\n\nThe child_process.fork() API inherits the execution arguments from the\nparent process. This means that if Node.js is started with the Permission\nModel enabled and the --allow-child-process flag is set, any child process\ncreated using child_process.fork() will automatically receive all relevant\nPermission Model flags.
This behavior also applies to child_process.spawn(), but in that case, the\nflags are propagated via the NODE_OPTIONS environment variable rather than\ndirectly through the process arguments.
This flag configures file system read permissions using\nthe Permission Model.
\nThe valid arguments for the --allow-fs-read flag are:
* - To allow all FileSystemRead operations.--allow-fs-read flags.\nExample --allow-fs-read=/folder1/ --allow-fs-read=/folder1/Examples can be found in the File System Permissions documentation.
\nThe initializer module and custom --require modules has a implicit\nread permission.
$ node --permission -r custom-require.js -r custom-require-2.js index.js\n\ncustom-require.js, custom-require-2.js, and index.js will be\nby default in the allowed read list.process.has('fs.read', 'index.js'); // true\nprocess.has('fs.read', 'custom-require.js'); // true\nprocess.has('fs.read', 'custom-require-2.js'); // true\n",
"displayName": "`--allow-fs-read`"
},
{
"textRaw": "`--allow-fs-write`",
"name": "`--allow-fs-write`",
"type": "module",
"meta": {
"added": [
"v20.0.0"
],
"changes": [
{
"version": [
"v23.5.0",
"v22.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/56201",
"description": "Permission Model and --allow-fs flags are stable."
},
{
"version": "v20.7.0",
"pr-url": "https://github.com/nodejs/node/pull/49047",
"description": "Paths delimited by comma (`,`) are no longer allowed."
}
]
},
"desc": "This flag configures file system write permissions using\nthe Permission Model.
\nThe valid arguments for the --allow-fs-write flag are:
* - To allow all FileSystemWrite operations.--allow-fs-write flags.\nExample --allow-fs-write=/folder1/ --allow-fs-write=/folder1/Paths delimited by comma (,) are no longer allowed.\nWhen passing a single flag with a comma a warning will be displayed.
Examples can be found in the File System Permissions documentation.
", "displayName": "`--allow-fs-write`" }, { "textRaw": "`--allow-inspector`", "name": "`--allow-inspector`", "type": "module", "meta": { "added": [ "v25.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Early development", "desc": "When using the Permission Model, the process will not be able to connect\nthrough inspector protocol.
\nAttempts to do so will throw an ERR_ACCESS_DENIED unless the\nuser explicitly passes the --allow-inspector flag when starting Node.js.
Example:
\nconst { Session } = require('node:inspector/promises');\n\nconst session = new Session();\nsession.connect();\n\n$ node --permission index.js\nError: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-inspector to manage permissions.\n code: 'ERR_ACCESS_DENIED',\n}\n",
"displayName": "`--allow-inspector`"
},
{
"textRaw": "`--allow-net`",
"name": "`--allow-net`",
"type": "module",
"meta": {
"added": [
"v25.0.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "When using the Permission Model, the process will not be able to access\nnetwork by default.\nAttempts to do so will throw an ERR_ACCESS_DENIED unless the\nuser explicitly passes the --allow-net flag when starting Node.js.
Example:
\nconst http = require('node:http');\n// Attempt to bypass the permission\nconst req = http.get('http://example.com', () => {});\n\nreq.on('error', (err) => {\n console.log('err', err);\n});\n\n$ node --permission index.js\nError: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-net to manage permissions.\n code: 'ERR_ACCESS_DENIED',\n}\n",
"displayName": "`--allow-net`"
},
{
"textRaw": "`--allow-wasi`",
"name": "`--allow-wasi`",
"type": "module",
"meta": {
"added": [
"v22.3.0",
"v20.16.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "When using the Permission Model, the process will not be capable of creating\nany WASI instances by default.\nFor security reasons, the call will throw an ERR_ACCESS_DENIED unless the\nuser explicitly passes the flag --allow-wasi in the main Node.js process.
Example:
\nconst { WASI } = require('node:wasi');\n// Attempt to bypass the permission\nnew WASI({\n version: 'preview1',\n // Attempt to mount the whole filesystem\n preopens: {\n '/': '/',\n },\n});\n\n$ node --permission --allow-fs-read=* index.js\n\nError: Access to this API has been restricted\n at node:internal/main/run_main_module:30:49 {\n code: 'ERR_ACCESS_DENIED',\n permission: 'WASI',\n}\n",
"displayName": "`--allow-wasi`"
},
{
"textRaw": "`--allow-worker`",
"name": "`--allow-worker`",
"type": "module",
"meta": {
"added": [
"v20.0.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "When using the Permission Model, the process will not be able to create any\nworker threads by default.\nFor security reasons, the call will throw an ERR_ACCESS_DENIED unless the\nuser explicitly pass the flag --allow-worker in the main Node.js process.
Example:
\nconst { Worker } = require('node:worker_threads');\n// Attempt to bypass the permission\nnew Worker(__filename);\n\n$ node --permission --allow-fs-read=* index.js\n\nError: Access to this API has been restricted\n at node:internal/main/run_main_module:17:47 {\n code: 'ERR_ACCESS_DENIED',\n permission: 'WorkerThreads'\n}\n",
"displayName": "`--allow-worker`"
},
{
"textRaw": "`--build-sea=config`",
"name": "`--build-sea=config`",
"type": "module",
"meta": {
"added": [
"v25.5.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "Generates a single executable application from a JSON\nconfiguration file. The argument must be a path to the configuration file. If\nthe path is not absolute, it is resolved relative to the current working\ndirectory.
\nFor configuration fields, cross-platform notes, and asset APIs, see\nthe single executable application documentation.
", "displayName": "`--build-sea=config`" }, { "textRaw": "`--build-snapshot`", "name": "`--build-snapshot`", "type": "module", "meta": { "added": [ "v18.8.0" ], "changes": [ { "version": [ "v25.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/60954", "description": "The snapshot building process is no longer experimental." } ] }, "desc": "Generates a snapshot blob when the process exits and writes it to\ndisk, which can be loaded later with --snapshot-blob.
When building the snapshot, if --snapshot-blob is not specified,\nthe generated blob will be written, by default, to snapshot.blob\nin the current working directory. Otherwise it will be written to\nthe path specified by --snapshot-blob.
$ echo \"globalThis.foo = 'I am from the snapshot'\" > snapshot.js\n\n# Run snapshot.js to initialize the application and snapshot the\n# state of it into snapshot.blob.\n$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js\n\n$ echo \"console.log(globalThis.foo)\" > index.js\n\n# Load the generated snapshot and start the application from index.js.\n$ node --snapshot-blob snapshot.blob index.js\nI am from the snapshot\n\nThe v8.startupSnapshot API can be used to specify an entry point at\nsnapshot building time, thus avoiding the need of an additional entry\nscript at deserialization time:
$ echo \"require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))\" > snapshot.js\n$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js\n$ node --snapshot-blob snapshot.blob\nI am from the snapshot\n\nFor more information, check out the v8.startupSnapshot API documentation.
The snapshot currently only supports loding a single entrypoint during the\nsnapshot building process, which can load built-in modules, but not additional user-land modules.\nUsers can bundle their applications into a single script with their bundler\nof choice before building a snapshot.
\nAs it's complicated to ensure the serializablility of all built-in modules,\nwhich are also growing over time, only a subset of the built-in modules are\nwell tested to be serializable during the snapshot building process.\nThe Node.js core test suite checks that a few fairly complex applications\ncan be snapshotted. The list of built-in modules being\ncaptured by the built-in snapshot of Node.js is considered supported.\nWhen the snapshot builder encounters a built-in module that cannot be\nserialized, it may crash the snapshot building process. In that case a typical\nworkaround would be to delay loading that module until\nruntime, using either v8.startupSnapshot.setDeserializeMainFunction() or\nv8.startupSnapshot.addDeserializeCallback(). If serialization for\nan additional module during the snapshot building process is needed,\nplease file a request in the Node.js issue tracker and link to it in the\ntracking issue for user-land snapshots.
Specifies the path to a JSON configuration file which configures snapshot\ncreation behavior.
\nThe following options are currently supported:
\nbuilder <string> Required. Provides the name to the script that is executed\nbefore building the snapshot, as if --build-snapshot had been passed\nwith builder as the main script name.withoutCodeCache <boolean> Optional. Including the code cache reduces the\ntime spent on compiling functions included in the snapshot at the expense\nof a bigger snapshot size and potentially breaking portability of the\nsnapshot.When using this flag, additional script files provided on the command line will\nnot be executed and instead be interpreted as regular command line arguments.
", "displayName": "`--build-snapshot-config`" }, { "textRaw": "`-c`, `--check`", "name": "`-c`,_`--check`", "type": "module", "meta": { "added": [ "v5.0.0", "v4.2.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19600", "description": "The `--require` option is now supported when checking a file." } ] }, "desc": "Syntax check the script without executing.
", "displayName": "`-c`, `--check`" }, { "textRaw": "`--completion-bash`", "name": "`--completion-bash`", "type": "module", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "desc": "Print source-able bash completion script for Node.js.
\nnode --completion-bash > node_bash_completion\nsource node_bash_completion\n",
"displayName": "`--completion-bash`"
},
{
"textRaw": "`-C condition`, `--conditions=condition`",
"name": "`-c_condition`,_`--conditions=condition`",
"type": "module",
"meta": {
"added": [
"v14.9.0",
"v12.19.0"
],
"changes": [
{
"version": [
"v22.9.0",
"v20.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/54209",
"description": "The flag is no longer experimental."
}
]
},
"desc": "Provide custom conditional exports resolution conditions.
\nAny number of custom string condition names are permitted.
\nThe default Node.js conditions of \"node\", \"default\", \"import\", and\n\"require\" will always apply as defined.
For example, to run a module with \"development\" resolutions:
\nnode -C development app.js\n",
"displayName": "`-C condition`, `--conditions=condition`"
},
{
"textRaw": "`--cpu-prof`",
"name": "`--cpu-prof`",
"type": "module",
"meta": {
"added": [
"v12.0.0"
],
"changes": [
{
"version": [
"v22.4.0",
"v20.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/53343",
"description": "The `--cpu-prof` flags are now stable."
}
]
},
"desc": "Starts the V8 CPU profiler on start up, and writes the CPU profile to disk\nbefore exit.
\nIf --cpu-prof-dir is not specified, the generated profile is placed\nin the current working directory.
If --cpu-prof-name is not specified, the generated profile is\nnamed CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.
$ node --cpu-prof index.js\n$ ls *.cpuprofile\nCPU.20190409.202950.15293.0.0.cpuprofile\n\nIf --cpu-prof-name is specified, the provided value is used as a template\nfor the file name. The following placeholder is supported and will be\nsubstituted at runtime:
${pid} — the current process ID$ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js\n$ ls *.cpuprofile\nCPU.15293.cpuprofile\n",
"displayName": "`--cpu-prof`"
},
{
"textRaw": "`--cpu-prof-dir`",
"name": "`--cpu-prof-dir`",
"type": "module",
"meta": {
"added": [
"v12.0.0"
],
"changes": [
{
"version": [
"v22.4.0",
"v20.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/53343",
"description": "The `--cpu-prof` flags are now stable."
}
]
},
"desc": "Specify the directory where the CPU profiles generated by --cpu-prof will\nbe placed.
The default value is controlled by the\n--diagnostic-dir command-line option.
Specify the sampling interval in microseconds for the CPU profiles generated\nby --cpu-prof. The default is 1000 microseconds.
Specify the file name of the CPU profile generated by --cpu-prof.
Set the directory to which all diagnostic output files are written.\nDefaults to current working directory.
\nAffects the default output directory of:
\n", "displayName": "`--diagnostic-dir=directory`" }, { "textRaw": "`--disable-proto=mode`", "name": "`--disable-proto=mode`", "type": "module", "meta": { "added": [ "v13.12.0", "v12.17.0" ], "changes": [] }, "desc": "Disable the Object.prototype.__proto__ property. If mode is delete, the\nproperty is removed entirely. If mode is throw, accesses to the\nproperty throw an exception with the code ERR_PROTO_ACCESS.
Disable the ability of starting a debugging session by sending a\nSIGUSR1 signal to the process.
Disable specific process warnings by code or type.
Warnings emitted from process.emitWarning() may contain a\ncode and a type. This option will not-emit warnings that have a matching\ncode or type.
List of deprecation warnings.
\nThe Node.js core warning types are: DeprecationWarning and\nExperimentalWarning
For example, the following script will not emit\nDEP0025 require('node:sys') when executed with\nnode --disable-warning=DEP0025:
import sys from 'node:sys';\n\nconst sys = require('node:sys');\n\nFor example, the following script will emit the\nDEP0025 require('node:sys'), but not any Experimental\nWarnings (such as\nExperimentalWarning: vm.measureMemory is an experimental feature\nin <=v21) when executed with node --disable-warning=ExperimentalWarning:
import sys from 'node:sys';\nimport vm from 'node:vm';\n\nvm.measureMemory();\n\nconst sys = require('node:sys');\nconst vm = require('node:vm');\n\nvm.measureMemory();\n",
"displayName": "`--disable-warning=code-or-type`"
},
{
"textRaw": "`--disable-wasm-trap-handler`",
"name": "`--disable-wasm-trap-handler`",
"type": "module",
"meta": {
"added": [
"v22.2.0",
"v20.15.0"
],
"changes": []
},
"desc": "By default, Node.js enables trap-handler-based WebAssembly bound\nchecks. As a result, V8 does not need to insert inline bound checks\nin the code compiled from WebAssembly which may speed up WebAssembly\nexecution significantly, but this optimization requires allocating\na big virtual memory cage (currently 10GB). If the Node.js process\ndoes not have access to a large enough virtual memory address space\ndue to system configurations or hardware limitations, users won't\nbe able to run any WebAssembly that involves allocation in this\nvirtual memory cage and will see an out-of-memory error.
\n$ ulimit -v 5000000\n$ node -p \"new WebAssembly.Memory({ initial: 10, maximum: 100 });\"\n[eval]:1\nnew WebAssembly.Memory({ initial: 10, maximum: 100 });\n^\n\nRangeError: WebAssembly.Memory(): could not allocate memory\n at [eval]:1:1\n at runScriptInThisContext (node:internal/vm:209:10)\n at node:internal/process/execution:118:14\n at [eval]-wrapper:6:24\n at runScript (node:internal/process/execution:101:62)\n at evalScript (node:internal/process/execution:136:3)\n at node:internal/main/eval_string:49:3\n\n\n--disable-wasm-trap-handler disables this optimization so that\nusers can at least run WebAssembly (with less optimal performance)\nwhen the virtual memory address space available to their Node.js\nprocess is lower than what the V8 WebAssembly memory cage needs.
Make built-in language features like eval and new Function that generate\ncode from strings throw an exception instead. This does not affect the Node.js\nnode:vm module.
Set the default value of order in dns.lookup() and\ndnsPromises.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 dns.setDefaultResultOrder() have higher\npriority than --dns-result-order.
Enable FIPS-compliant crypto at startup. (Requires Node.js to be built\nagainst FIPS-compatible OpenSSL.)
", "displayName": "`--enable-fips`" }, { "textRaw": "`--enable-source-maps`", "name": "`--enable-source-maps`", "type": "module", "meta": { "added": [ "v12.12.0" ], "changes": [ { "version": [ "v15.11.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/37362", "description": "This API is no longer experimental." } ] }, "desc": "Enable Source Map support for stack traces.
\nWhen using a transpiler, such as TypeScript, stack traces thrown by an\napplication reference the transpiled code, not the original source position.\n--enable-source-maps enables caching of Source Maps and makes a best\neffort to report stack traces relative to the original source file.
Overriding Error.prepareStackTrace may prevent --enable-source-maps from\nmodifying the stack trace. Call and return the results of the original\nError.prepareStackTrace in the overriding function to modify the stack trace\nwith source maps.
const originalPrepareStackTrace = Error.prepareStackTrace;\nError.prepareStackTrace = (error, trace) => {\n // Modify error and trace and format stack trace with\n // original Error.prepareStackTrace.\n return originalPrepareStackTrace(error, trace);\n};\n\nNote, enabling source maps can introduce latency to your application\nwhen Error.stack is accessed. If you access Error.stack frequently\nin your application, take into account the performance implications\nof --enable-source-maps.
When present, Node.js will interpret the entry point as a URL, rather than a\npath.
\nFollows ECMAScript module resolution rules.
\nAny query parameter or hash in the URL will be accessible via import.meta.url.
node --entry-url 'file:///path/to/file.js?queryparams=work#and-hashes-too'\nnode --entry-url 'file.ts?query#hash'\nnode --entry-url 'data:text/javascript,console.log(\"Hello\")'\n",
"displayName": "`--entry-url`"
},
{
"textRaw": "`--env-file-if-exists=file`",
"name": "`--env-file-if-exists=file`",
"type": "module",
"meta": {
"added": [
"v22.9.0"
],
"changes": [
{
"version": "v24.10.0",
"pr-url": "https://github.com/nodejs/node/pull/59925",
"description": "The `--env-file-if-exists` flag is no longer experimental."
}
]
},
"desc": "Behavior is the same as --env-file, but an error is not thrown if the file\ndoes not exist.
Loads environment variables from a file relative to the current directory,\nmaking them available to applications on process.env. The environment\nvariables which configure Node.js, such as NODE_OPTIONS,\nare parsed and applied. If the same variable is defined in the environment and\nin the file, the value from the environment takes precedence.
You can pass multiple --env-file arguments. Subsequent files override\npre-existing variables defined in previous files.
An error is thrown if the file does not exist.
\nnode --env-file=.env --env-file=.development.env index.js\n\nThe format of the file should be one line per key-value pair of environment\nvariable name and value separated by =:
PORT=3000\n\nAny text after a # is treated as a comment:
# This is a comment\nPORT=3000 # This is also a comment\n\nValues can start and end with the following quotes: `, \" or '.\nThey are omitted from the values.
USERNAME=\"nodejs\" # will result in `nodejs` as the value.\n\nMulti-line values are supported:
\nMULTI_LINE=\"THIS IS\nA MULTILINE\"\n# will result in `THIS IS\\nA MULTILINE` as the value.\n\nExport keyword before a key is ignored:
\nexport USERNAME=\"nodejs\" # will result in `nodejs` as the value.\n\nIf you want to load environment variables from a file that may not exist, you\ncan use the --env-file-if-exists flag instead.
Evaluate the following argument as JavaScript. The modules which are\npredefined in the REPL can also be used in script.
On Windows, using cmd.exe a single quote will not work correctly because it\nonly recognizes double \" for quoting. In Powershell or Git bash, both '\nand \" are usable.
It is possible to run code containing inline types unless the\n--no-strip-types flag is provided.
Enable experimental import support for .node addons.
If present, Node.js will look for a configuration file at the specified path.\nNode.js will read the configuration file and apply the settings. The\nconfiguration file should be a JSON file with the following structure. vX.Y.Z\nin the $schema must be replaced with the version of Node.js you are using.
{\n \"$schema\": \"https://nodejs.org/dist/vX.Y.Z/docs/node-config-schema.json\",\n \"nodeOptions\": {\n \"import\": [\n \"amaro/strip\"\n ],\n \"watch-path\": \"src\",\n \"watch-preserve-output\": true\n },\n \"test\": {\n \"test-isolation\": \"process\"\n },\n \"watch\": {\n \"watch-preserve-output\": true\n }\n}\n\nThe configuration file supports namespace-specific options:
\nThe nodeOptions field contains CLI flags that are allowed in NODE_OPTIONS.
Namespace fields like test, watch, and permission contain configuration specific to that subsystem.
When a namespace is present in the\nconfiguration file, Node.js automatically enables the corresponding flag\n(e.g., --test, --watch, --permission). This allows you to configure\nsubsystem-specific options without explicitly passing the flag on the command line.
For example:
\n{\n \"test\": {\n \"test-isolation\": \"process\"\n }\n}\n\nis equivalent to:
\nnode --test --test-isolation=process\n\nTo disable the automatic flag while still using namespace options, you can\nexplicitly set the flag to false within the namespace:
{\n \"test\": {\n \"test\": false,\n \"test-isolation\": \"process\"\n }\n}\n\nNo-op flags are not supported.\nNot all V8 flags are currently supported.
\nIt is possible to use the official JSON schema\nto validate the configuration file, which may vary depending on the Node.js version.\nEach key in the configuration file corresponds to a flag that can be passed\nas a command-line argument. The value of the key is the value that would be\npassed to the flag.
\nFor example, the configuration file above is equivalent to\nthe following command-line arguments:
\nnode --import amaro/strip --watch-path=src --watch-preserve-output --test-isolation=process\n\nThe priority in configuration is as follows:
\nValues in the configuration file will not override the values in the environment\nvariables and command-line options, but will override the values in the NODE_OPTIONS\nenv file parsed by the --env-file flag.
Keys cannot be duplicated within the same or different namespaces.
\nThe configuration parser will throw an error if the configuration file contains\nunknown keys or keys that cannot be used in a namespace.
\nNode.js will not sanitize or perform validation on the user-provided configuration,\nso NEVER use untrusted configuration files.
", "displayName": "`--experimental-config-file=config`" }, { "textRaw": "`--experimental-default-config-file`", "name": "`--experimental-default-config-file`", "type": "module", "meta": { "added": [ "v23.10.0", "v22.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "Early development", "desc": "If the --experimental-default-config-file flag is present, Node.js will look for a\nnode.config.json file in the current working directory and load it as a\nas configuration file.
Enable exposition of EventSource Web API on the global scope.
", "displayName": "`--experimental-eventsource`" }, { "textRaw": "`--experimental-import-meta-resolve`", "name": "`--experimental-import-meta-resolve`", "type": "module", "meta": { "added": [ "v13.9.0", "v12.16.2" ], "changes": [ { "version": [ "v20.6.0", "v18.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/49028", "description": "synchronous import.meta.resolve made available by default, with the flag retained for enabling the experimental second argument as previously supported." } ] }, "desc": "Enable experimental import.meta.resolve() parent URL support, which allows\npassing a second parentURL argument for contextual resolution.
Previously gated the entire import.meta.resolve feature.
Enable experimental support for inspector network resources.
", "displayName": "`--experimental-inspector-network-resource`" }, { "textRaw": "`--experimental-loader=module`", "name": "`--experimental-loader=module`", "type": "module", "meta": { "added": [ "v8.8.0" ], "changes": [ { "version": [ "v23.6.1", "v22.13.1", "v20.18.2" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/629", "description": "Using this feature with the permission model enabled requires passing `--allow-worker`." }, { "version": "v12.11.1", "pr-url": "https://github.com/nodejs/node/pull/29752", "description": "This flag was renamed from `--loader` to `--experimental-loader`." } ] }, "desc": "\n\nThis flag is discouraged and may be removed in a future version of Node.js.\nPlease use\n
\n--importwithregister()instead.
Specify the module containing exported asynchronous module customization hooks.\nmodule may be any string accepted as an import specifier.
This feature requires --allow-worker if used with the Permission Model.
Enable experimental support for the network inspection with Chrome DevTools.
", "displayName": "`--experimental-network-inspection`" }, { "textRaw": "`--experimental-print-required-tla`", "name": "`--experimental-print-required-tla`", "type": "module", "meta": { "added": [ "v22.0.0", "v20.17.0" ], "changes": [] }, "desc": "If the ES module being require()'d contains top-level await, this flag\nallows Node.js to evaluate the module, try to locate the\ntop-level awaits, and print their location to help users find them.
Enable experimental support for the QUIC protocol.
", "displayName": "`--experimental-quic`" }, { "textRaw": "`--experimental-sea-config`", "name": "`--experimental-sea-config`", "type": "module", "meta": { "added": [ "v20.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Use this flag to generate a blob that can be injected into the Node.js\nbinary to produce a single executable application. See the documentation\nabout this configuration for details.
", "displayName": "`--experimental-sea-config`" }, { "textRaw": "`--experimental-shadow-realm`", "name": "`--experimental-shadow-realm`", "type": "module", "meta": { "added": [ "v19.0.0", "v18.13.0" ], "changes": [] }, "desc": "Use this flag to enable ShadowRealm support.
", "displayName": "`--experimental-shadow-realm`" }, { "textRaw": "`--experimental-storage-inspection`", "name": "`--experimental-storage-inspection`", "type": "module", "meta": { "added": [ "v25.5.0" ], "changes": [] }, "stability": 1.1, "stabilityText": "Active Development", "desc": "Enable experimental support for storage inspection
", "displayName": "`--experimental-storage-inspection`" }, { "textRaw": "`--experimental-test-coverage`", "name": "`--experimental-test-coverage`", "type": "module", "meta": { "added": [ "v19.7.0", "v18.15.0" ], "changes": [ { "version": [ "v20.1.0", "v18.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/47686", "description": "This option can be used with `--test`." } ] }, "desc": "When used in conjunction with the node:test module, a code coverage report is\ngenerated as part of the test runner output. If no tests are run, a coverage\nreport is not generated. See the documentation on\ncollecting code coverage from tests for more details.
Enable module mocking in the test runner.
\nThis feature requires --allow-worker if used with the Permission Model.
Enables the transformation of TypeScript-only syntax into JavaScript code.\nImplies --enable-source-maps.
Enable experimental ES Module support in the node:vm module.
Enable experimental WebAssembly System Interface (WASI) support.
", "displayName": "`--experimental-wasi-unstable-preview1`" }, { "textRaw": "`--experimental-worker-inspection`", "name": "`--experimental-worker-inspection`", "type": "module", "meta": { "added": [ "v24.1.0", "v22.17.0" ], "changes": [] }, "stability": 1.1, "stabilityText": "Active Development", "desc": "Enable experimental support for the worker inspection with Chrome DevTools.
", "displayName": "`--experimental-worker-inspection`" }, { "textRaw": "`--expose-gc`", "name": "`--expose-gc`", "type": "module", "meta": { "added": [ "v22.3.0", "v20.18.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental. This flag is inherited from V8 and is subject to change upstream.", "desc": "This flag will expose the gc extension from V8.
\nif (globalThis.gc) {\n globalThis.gc();\n}\n",
"displayName": "`--expose-gc`"
},
{
"textRaw": "`--force-context-aware`",
"name": "`--force-context-aware`",
"type": "module",
"meta": {
"added": [
"v12.12.0"
],
"changes": []
},
"desc": "Disable loading native addons that are not context-aware.
", "displayName": "`--force-context-aware`" }, { "textRaw": "`--force-fips`", "name": "`--force-fips`", "type": "module", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)\n(Same requirements as --enable-fips.)
Enforces uncaughtException event on Node-API asynchronous callbacks.
To prevent from an existing add-on from crashing the process, this flag is not\nenabled by default. In the future, this flag will be enabled by default to\nenforce the correct behavior.
", "displayName": "`--force-node-api-uncaught-exceptions-policy`" }, { "textRaw": "`--frozen-intrinsics`", "name": "`--frozen-intrinsics`", "type": "module", "meta": { "added": [ "v11.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Enable experimental frozen intrinsics like Array and Object.
Only the root context is supported. There is no guarantee that\nglobalThis.Array is indeed the default intrinsic reference. Code may break\nunder this flag.
To allow polyfills to be added,\n--require and --import both run before freezing intrinsics.
Starts the V8 heap profiler on start up, and writes the heap profile to disk\nbefore exit.
\nIf --heap-prof-dir is not specified, the generated profile is placed\nin the current working directory.
If --heap-prof-name is not specified, the generated profile is\nnamed Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.
$ node --heap-prof index.js\n$ ls *.heapprofile\nHeap.20190409.202950.15293.0.001.heapprofile\n",
"displayName": "`--heap-prof`"
},
{
"textRaw": "`--heap-prof-dir`",
"name": "`--heap-prof-dir`",
"type": "module",
"meta": {
"added": [
"v12.4.0"
],
"changes": [
{
"version": [
"v22.4.0",
"v20.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/53343",
"description": "The `--heap-prof` flags are now stable."
}
]
},
"desc": "Specify the directory where the heap profiles generated by --heap-prof will\nbe placed.
The default value is controlled by the\n--diagnostic-dir command-line option.
Specify the average sampling interval in bytes for the heap profiles generated\nby --heap-prof. The default is 512 * 1024 bytes.
Specify the file name of the heap profile generated by --heap-prof.
Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the\nheap limit. count should be a non-negative integer (in which case\nNode.js will write no more than max_count snapshots to disk).
When generating snapshots, garbage collection may be triggered and bring\nthe heap usage down. Therefore multiple snapshots may be written to disk\nbefore the Node.js instance finally runs out of memory. These heap snapshots\ncan be compared to determine what objects are being allocated during the\ntime consecutive snapshots are taken. It's not guaranteed that Node.js will\nwrite exactly max_count snapshots to disk, but it will try\nits best to generate at least one and up to max_count snapshots before the\nNode.js instance runs out of memory when max_count is greater than 0.
Generating V8 snapshots takes time and memory (both memory managed by the\nV8 heap and native memory outside the V8 heap). The bigger the heap is,\nthe more resources it needs. Node.js will adjust the V8 heap to accommodate\nthe additional V8 heap memory overhead, and try its best to avoid using up\nall the memory available to the process. When the process uses\nmore memory than the system deems appropriate, the process may be terminated\nabruptly by the system, depending on the system configuration.
\n$ node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js\nWrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot\nWrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot\nWrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot\n\n<--- Last few GCs --->\n\n[49580:0x110000000] 4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed\n[49580:0x110000000] 4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed\n\n\n<--- JS stacktrace --->\n\nFATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory\n....\n",
"displayName": "`--heapsnapshot-near-heap-limit=max_count`"
},
{
"textRaw": "`--heapsnapshot-signal=signal`",
"name": "`--heapsnapshot-signal=signal`",
"type": "module",
"meta": {
"added": [
"v12.0.0"
],
"changes": []
},
"desc": "Enables a signal handler that causes the Node.js process to write a heap dump\nwhen the specified signal is received. signal must be a valid signal name.\nDisabled by default.
$ node --heapsnapshot-signal=SIGUSR2 index.js &\n$ ps aux\nUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND\nnode 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js\n$ kill -USR2 1\n$ ls\nHeap.20190718.133405.15554.0.001.heapsnapshot\n",
"displayName": "`--heapsnapshot-signal=signal`"
},
{
"textRaw": "`-h`, `--help`",
"name": "`-h`,_`--help`",
"type": "module",
"meta": {
"added": [
"v0.1.3"
],
"changes": []
},
"desc": "Print node command-line options.\nThe output of this option is less detailed than this document.
", "displayName": "`-h`, `--help`" }, { "textRaw": "`--icu-data-dir=file`", "name": "`--icu-data-dir=file`", "type": "module", "meta": { "added": [ "v0.11.15" ], "changes": [] }, "desc": "Specify ICU data load path. (Overrides NODE_ICU_DATA.)
Preload the specified module at startup. If the flag is provided several times,\neach module will be executed sequentially in the order they appear, starting\nwith the ones provided in NODE_OPTIONS.
Follows ECMAScript module resolution rules.\nUse --require to load a CommonJS module.\nModules preloaded with --require will run before modules preloaded with --import.
Modules are preloaded into the main thread as well as any worker threads,\nforked processes, or clustered processes.
", "displayName": "`--import=module`" }, { "textRaw": "`--input-type=type`", "name": "`--input-type=type`", "type": "module", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": [ "v23.6.0", "v22.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/56350", "description": "Add support for `-typescript` values." }, { "version": [ "v22.7.0", "v20.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/53619", "description": "ESM syntax detection is enabled by default." } ] }, "desc": "This configures Node.js to interpret --eval or STDIN input as CommonJS or\nas an ES module. Valid values are \"commonjs\", \"module\", \"module-typescript\" and \"commonjs-typescript\".\nThe \"-typescript\" values are not available with the flag --no-strip-types.\nThe default is no value, or \"commonjs\" if --no-experimental-detect-module is passed.
If --input-type is not provided,\nNode.js will try to detect the syntax with the following steps:
ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX\nor ERR_INVALID_TYPESCRIPT_SYNTAX,\nthrow the error from step 2, including the TypeScript error in the message,\nelse run as CommonJS.To avoid the delay of multiple syntax detection passes, the --input-type=type flag can be used to specify\nhow the --eval input should be interpreted.
The REPL does not support this option. Usage of --input-type=module with\n--print will throw an error, as --print does not support ES module\nsyntax.
Enable leniency flags on the HTTP parser. This may allow\ninteroperability with non-conformant HTTP implementations.
\nWhen enabled, the parser will accept the following:
\nTransfer-Encoding\nand Content-Length headers.Connection: close is present.chunked has been provided.\\n to be used as token separator instead of \\r\\n.\\r\\n not to be provided after a chunk.\\r\\n.All the above will expose your application to request smuggling\nor poisoning attack. Avoid using this option.
", "displayName": "`--insecure-http-parser`" }, { "textRaw": "`--inspect-brk[=[host:]port]`", "name": "`--inspect-brk[=[host:]port]`", "type": "module", "meta": { "added": [ "v7.6.0" ], "changes": [] }, "desc": "Activate inspector on host:port and break at start of user script.\nDefault host:port is 127.0.0.1:9229. If port 0 is specified,\na random available port will be used.
See V8 Inspector integration for Node.js for further explanation on Node.js debugger.
\nSee the security warning below regarding the host\nparameter usage.
Set the host:port to be used when the inspector is activated.\nUseful when activating the inspector by sending the SIGUSR1 signal.\nExcept when --disable-sigusr1 is passed.
Default host is 127.0.0.1. If port 0 is specified,\na random available port will be used.
See the security warning below regarding the host\nparameter usage.
Specify ways of the inspector web socket url exposure.
\nBy default inspector websocket url is available in stderr and under /json/list\nendpoint on http://host:port/json/list.
Activate inspector on host:port and wait for debugger to be attached.\nDefault host:port is 127.0.0.1:9229. If port 0 is specified,\na random available port will be used.
See V8 Inspector integration for Node.js for further explanation on Node.js debugger.
\nSee the security warning below regarding the host\nparameter usage.
Activate inspector on host:port. Default is 127.0.0.1:9229. If port 0 is\nspecified, a random available port will be used.
V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug\nand profile Node.js instances. The tools attach to Node.js instances via a\ntcp port and communicate using the Chrome DevTools Protocol.\nSee V8 Inspector integration for Node.js for further explanation on Node.js debugger.
\n", "modules": [ { "textRaw": "Warning: binding inspector to a public IP:port combination is insecure", "name": "warning:_binding_inspector_to_a_public_ip:port_combination_is_insecure", "type": "module", "desc": "Binding the inspector to a public IP (including 0.0.0.0) with an open port is\ninsecure, as it allows external hosts to connect to the inspector and perform\na remote code execution attack.
If specifying a host, make sure that either:
\nMore specifically, --inspect=0.0.0.0 is insecure if the port (9229 by\ndefault) is not firewall-protected.
See the debugging security implications section for more information.
", "displayName": "Warning: binding inspector to a public IP:port combination is insecure" } ], "displayName": "`--inspect[=[host:]port]`" }, { "textRaw": "`-i`, `--interactive`", "name": "`-i`,_`--interactive`", "type": "module", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "Opens the REPL even if stdin does not appear to be a terminal.
", "displayName": "`-i`, `--interactive`" }, { "textRaw": "`--jitless`", "name": "`--jitless`", "type": "module", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental. This flag is inherited from V8 and is subject to change upstream.", "desc": "Disable runtime allocation of executable memory. This may be\nrequired on some platforms for security reasons. It can also reduce attack\nsurface on other platforms, but the performance impact may be severe.
", "displayName": "`--jitless`" }, { "textRaw": "`--localstorage-file=file`", "name": "`--localstorage-file=file`", "type": "module", "meta": { "added": [ "v22.4.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate.", "desc": "The file used to store localStorage data. If the file does not exist, it is\ncreated the first time localStorage is accessed. The same file may be shared\nbetween multiple Node.js processes concurrently.
Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB.
", "displayName": "`--max-http-header-size=size`" }, { "textRaw": "`--max-old-space-size-percentage=percentage`", "name": "`--max-old-space-size-percentage=percentage`", "type": "module", "desc": "Sets the maximum memory size of V8's old memory section as a percentage of available system memory.\nThis flag takes precedence over --max-old-space-size when both are specified.
The percentage parameter must be a number greater than 0 and up to 100, representing the percentage\nof available system memory to allocate to the V8 heap.
Note: This flag utilizes --max-old-space-size, which may be unreliable on 32-bit platforms due to\ninteger overflow issues.
# Using 50% of available system memory\nnode --max-old-space-size-percentage=50 index.js\n\n# Using 75% of available system memory\nnode --max-old-space-size-percentage=75 index.js\n",
"displayName": "`--max-old-space-size-percentage=percentage`"
},
{
"textRaw": "`--napi-modules`",
"name": "`--napi-modules`",
"type": "module",
"meta": {
"added": [
"v7.10.0"
],
"changes": []
},
"desc": "This option is a no-op. It is kept for compatibility.
", "displayName": "`--napi-modules`" }, { "textRaw": "`--network-family-autoselection-attempt-timeout`", "name": "`--network-family-autoselection-attempt-timeout`", "type": "module", "meta": { "added": [ "v22.1.0", "v20.13.0" ], "changes": [] }, "desc": "Sets the default value for the network family autoselection attempt timeout.\nFor more information, see net.getDefaultAutoSelectFamilyAttemptTimeout().
Disable the node-addons exports condition as well as disable loading\nnative addons. When --no-addons is specified, calling process.dlopen or\nrequiring a native C++ addon will fail and throw an exception.
Disables the use of AsyncLocalStorage backed by AsyncContextFrame and\nuses the prior implementation which relied on async_hooks. The previous model\nis retained for compatibility with Electron and for cases where the context\nflow may differ. However, if a difference in flow is found please report it.
Silence deprecation warnings.
", "displayName": "`--no-deprecation`" }, { "textRaw": "`--no-experimental-detect-module`", "name": "`--no-experimental-detect-module`", "type": "module", "meta": { "added": [ "v21.1.0", "v20.10.0" ], "changes": [ { "version": [ "v22.7.0", "v20.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/53619", "description": "Syntax detection is enabled by default." } ] }, "desc": "Disable using syntax detection to determine module type.
", "displayName": "`--no-experimental-detect-module`" }, { "textRaw": "`--no-experimental-global-navigator`", "name": "`--no-experimental-global-navigator`", "type": "module", "meta": { "added": [ "v21.2.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Disable exposition of Navigator API on the global scope.
", "displayName": "`--no-experimental-global-navigator`" }, { "textRaw": "`--no-experimental-repl-await`", "name": "`--no-experimental-repl-await`", "type": "module", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "Use this flag to disable top-level await in REPL.
", "displayName": "`--no-experimental-repl-await`" }, { "textRaw": "`--no-experimental-require-module`", "name": "`--no-experimental-require-module`", "type": "module", "meta": { "added": [ "v22.0.0", "v20.17.0" ], "changes": [ { "version": [ "v25.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/60959", "description": "The flag was renamed from `--no-experimental-require-module` to `--no-require-module`, with the former marked as legacy." }, { "version": [ "v23.0.0", "v22.12.0", "v20.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/55085", "description": "This is now false by default." } ] }, "stability": 3, "stabilityText": "Legacy: Use `--no-require-module` instead.", "desc": "Legacy alias for --no-require-module.
Disable the experimental node:sqlite module.
Disable exposition of <WebSocket> on the global scope.
Disable Web Storage support.
Hide extra information on fatal exception that causes exit.
", "displayName": "`--no-extra-info-on-fatal-exception`" }, { "textRaw": "`--no-force-async-hooks-checks`", "name": "`--no-force-async-hooks-checks`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "desc": "Disables runtime checks for async_hooks. These will still be enabled\ndynamically when async_hooks is enabled.
Do not search modules from global paths like $HOME/.node_modules and\n$NODE_PATH.
Disables the family autoselection algorithm unless connection options explicitly\nenables it.
\n", "displayName": "`--no-network-family-autoselection`" }, { "textRaw": "`--no-require-module`", "name": "`--no-require-module`", "type": "module", "meta": { "added": [ "v22.0.0", "v20.17.0" ], "changes": [ { "version": [ "v25.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/60959", "description": "This flag is no longer experimental." }, { "version": [ "v25.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/60959", "description": "This flag was renamed from `--no-experimental-require-module` to `--no-require-module`." }, { "version": [ "v23.0.0", "v22.12.0", "v20.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/55085", "description": "This is now false by default." } ] }, "desc": "Disable support for loading a synchronous ES module graph in require().
See Loading ECMAScript modules using require().
Disable type-stripping for TypeScript files.\nFor more information, see the TypeScript type-stripping documentation.
", "displayName": "`--no-strip-types`" }, { "textRaw": "`--no-warnings`", "name": "`--no-warnings`", "type": "module", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "Silence all process warnings (including deprecations).
", "displayName": "`--no-warnings`" }, { "textRaw": "`--node-memory-debug`", "name": "`--node-memory-debug`", "type": "module", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "desc": "Enable extra debug checks for memory leaks in Node.js internals. This is\nusually only useful for developers debugging Node.js itself.
", "displayName": "`--node-memory-debug`" }, { "textRaw": "`--openssl-config=file`", "name": "`--openssl-config=file`", "type": "module", "meta": { "added": [ "v6.9.0" ], "changes": [] }, "desc": "Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built\nagainst FIPS-enabled OpenSSL.
", "displayName": "`--openssl-config=file`" }, { "textRaw": "`--openssl-legacy-provider`", "name": "`--openssl-legacy-provider`", "type": "module", "meta": { "added": [ "v17.0.0", "v16.17.0" ], "changes": [] }, "desc": "Enable OpenSSL 3.0 legacy provider. For more information please see\nOSSL_PROVIDER-legacy.
", "displayName": "`--openssl-legacy-provider`" }, { "textRaw": "`--openssl-shared-config`", "name": "`--openssl-shared-config`", "type": "module", "meta": { "added": [ "v18.5.0", "v16.17.0", "v14.21.0" ], "changes": [] }, "desc": "Enable OpenSSL default configuration section, openssl_conf to be read from\nthe OpenSSL configuration file. The default configuration file is named\nopenssl.cnf but this can be changed using the environment variable\nOPENSSL_CONF, or by using the command line option --openssl-config.\nThe location of the default OpenSSL configuration file depends on how OpenSSL\nis being linked to Node.js. Sharing the OpenSSL configuration may have unwanted\nimplications and it is recommended to use a configuration section specific to\nNode.js which is nodejs_conf and is default when this option is not used.
Emit pending deprecation warnings.
\nPending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command-line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.
Enable the Permission Model for current process. When enabled, the\nfollowing permissions are restricted:
\n--allow-fs-read, --allow-fs-write flags--allow-net flag--allow-child-process flag--allow-worker flag--allow-wasi flag--allow-addons flagEnable audit only for the permission model. When enabled, permission checks\nare performed but access is not denied. Instead, a warning is emitted for\neach permission violation via diagnostics channel.
", "displayName": "`--permission-audit`" }, { "textRaw": "`--preserve-symlinks`", "name": "`--preserve-symlinks`", "type": "module", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "Instructs the module loader to preserve symbolic links when resolving and\ncaching modules.
\nBy default, when Node.js loads a module from a path that is symbolically linked\nto a different on-disk location, Node.js will dereference the link and use the\nactual on-disk \"real path\" of the module as both an identifier and as a root\npath to locate other dependency modules. In most cases, this default behavior\nis acceptable. However, when using symbolically linked peer dependencies, as\nillustrated in the example below, the default behavior causes an exception to\nbe thrown if moduleA attempts to require moduleB as a peer dependency:
{appDir}\n ├── app\n │ ├── index.js\n │ └── node_modules\n │ ├── moduleA -> {appDir}/moduleA\n │ └── moduleB\n │ ├── index.js\n │ └── package.json\n └── moduleA\n ├── index.js\n └── package.json\n\nThe --preserve-symlinks command-line flag instructs Node.js to use the\nsymlink path for modules as opposed to the real path, allowing symbolically\nlinked peer dependencies to be found.
Note, however, that using --preserve-symlinks can have other side effects.\nSpecifically, symbolically linked native modules can fail to load if those\nare linked from more than one location in the dependency tree (Node.js would\nsee those as two separate modules and would attempt to load the module multiple\ntimes, causing an exception to be thrown).
The --preserve-symlinks flag does not apply to the main module, which allows\nnode --preserve-symlinks node_module/.bin/<foo> to work. To apply the same\nbehavior for the main module, also use --preserve-symlinks-main.
Instructs the module loader to preserve symbolic links when resolving and\ncaching the main module (require.main).
This flag exists so that the main module can be opted-in to the same behavior\nthat --preserve-symlinks gives to all other imports; they are separate flags,\nhowever, for backward compatibility with older Node.js versions.
--preserve-symlinks-main does not imply --preserve-symlinks; use\n--preserve-symlinks-main in addition to\n--preserve-symlinks when it is not desirable to follow symlinks before\nresolving relative paths.
See --preserve-symlinks for more information.
Identical to -e but prints the result.
Generate V8 profiler output.
", "displayName": "`--prof`" }, { "textRaw": "`--prof-process`", "name": "`--prof-process`", "type": "module", "meta": { "added": [ "v5.2.0" ], "changes": [] }, "desc": "Process V8 profiler output generated using the V8 option --prof.
Write process warnings to the given file instead of printing to stderr. The\nfile will be created if it does not exist, and will be appended to if it does.\nIf an error occurs while attempting to write the warning to the file, the\nwarning will be written to stderr instead.
\nThe file name may be an absolute path. If it is not, the default directory it\nwill be written to is controlled by the\n--diagnostic-dir command-line option.
Write reports in a compact format, single-line JSON, more easily consumable\nby log processing systems than the default multi-line format designed for\nhuman consumption.
", "displayName": "`--report-compact`" }, { "textRaw": "`--report-dir=directory`, `--report-directory=directory`", "name": "`--report-dir=directory`,_`--report-directory=directory`", "type": "module", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This option is no longer experimental." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27312", "description": "Changed from `--diagnostic-report-directory` to `--report-directory`." } ] }, "desc": "Location at which the report will be generated.
", "displayName": "`--report-dir=directory`, `--report-directory=directory`" }, { "textRaw": "`--report-exclude-env`", "name": "`--report-exclude-env`", "type": "module", "meta": { "added": [ "v23.3.0", "v22.13.0" ], "changes": [] }, "desc": "When --report-exclude-env is passed the diagnostic report generated will not\ncontain the environmentVariables data.
Exclude header.networkInterfaces from the diagnostic report. By default\nthis is not set and the network interfaces are included.
Name of the file to which the report will be written.
\nIf the filename is set to 'stdout' or 'stderr', the report is written to\nthe stdout or stderr of the process respectively.
Enables the report to be triggered on fatal errors (internal errors within\nthe Node.js runtime such as out of memory) that lead to termination of the\napplication. Useful to inspect various diagnostic data elements such as heap,\nstack, event loop state, resource consumption etc. to reason about the fatal\nerror.
", "displayName": "`--report-on-fatalerror`" }, { "textRaw": "`--report-on-signal`", "name": "`--report-on-signal`", "type": "module", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This option is no longer experimental." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27312", "description": "changed from `--diagnostic-report-on-signal` to `--report-on-signal`." } ] }, "desc": "Enables report to be generated upon receiving the specified (or predefined)\nsignal to the running Node.js process. The signal to trigger the report is\nspecified through --report-signal.
Sets or resets the signal for report generation (not supported on Windows).\nDefault signal is SIGUSR2.
Enables report to be generated when the process exits due to an uncaught\nexception. Useful when inspecting the JavaScript stack in conjunction with\nnative stack and other runtime environment data.
", "displayName": "`--report-uncaught-exception`" }, { "textRaw": "`-r`, `--require module`", "name": "`-r`,_`--require_module`", "type": "module", "meta": { "added": [ "v1.6.0" ], "changes": [ { "version": [ "v23.0.0", "v22.12.0", "v20.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/51977", "description": "This option also supports ECMAScript module." } ] }, "desc": "Preload the specified module at startup.
\nFollows require()'s module resolution\nrules. module may be either a path to a file, or a node module name.
Modules preloaded with --require will run before modules preloaded with --import.
Modules are preloaded into the main thread as well as any worker threads,\nforked processes, or clustered processes.
", "displayName": "`-r`, `--require module`" }, { "textRaw": "`--run`", "name": "`--run`", "type": "module", "meta": { "added": [ "v22.0.0" ], "changes": [ { "version": "v22.3.0", "pr-url": "https://github.com/nodejs/node/pull/53032", "description": "NODE_RUN_SCRIPT_NAME environment variable is added." }, { "version": "v22.3.0", "pr-url": "https://github.com/nodejs/node/pull/53058", "description": "NODE_RUN_PACKAGE_JSON_PATH environment variable is added." }, { "version": "v22.3.0", "pr-url": "https://github.com/nodejs/node/pull/53154", "description": "Traverses up to the root directory and finds a `package.json` file to run the command from, and updates `PATH` environment variable accordingly." } ] }, "desc": "This runs a specified command from a package.json's \"scripts\" object.\nIf a missing \"command\" is provided, it will list the available scripts.
--run will traverse up to the root directory and finds a package.json\nfile to run the command from.
--run prepends ./node_modules/.bin for each ancestor of\nthe current directory, to the PATH in order to execute the binaries from\ndifferent folders where multiple node_modules directories are present, if\nancestor-folder/node_modules/.bin is a directory.
--run executes the command in the directory containing the related package.json.
For example, the following command will run the test script of\nthe package.json in the current folder:
$ node --run test\n\nYou can also pass arguments to the command. Any argument after -- will\nbe appended to the script:
$ node --run test -- --verbose\n",
"modules": [
{
"textRaw": "Intentional limitations",
"name": "intentional_limitations",
"type": "module",
"desc": "node --run is not meant to match the behaviors of npm run or of the run\ncommands of other package managers. The Node.js implementation is intentionally\nmore limited, in order to focus on top performance for the most common use\ncases.\nSome features of other run implementations that are intentionally excluded\nare:
pre or post scripts in addition to the specified script.The following environment variables are set when running a script with --run:
NODE_RUN_SCRIPT_NAME: The name of the script being run. For example, if\n--run is used to run test, the value of this variable will be test.NODE_RUN_PACKAGE_JSON_PATH: The path to the package.json that is being\nprocessed.When using --secure-heap, the --secure-heap-min flag specifies the\nminimum allocation from the secure heap. The minimum value is 2.\nThe maximum value is the lesser of --secure-heap or 2147483647.\nThe value given must be a power of two.
Initializes an OpenSSL secure heap of n bytes. When initialized, the\nsecure heap is used for selected types of allocations within OpenSSL\nduring key generation and other operations. This is useful, for instance,\nto prevent sensitive information from leaking due to pointer overruns\nor underruns.
The secure heap is a fixed size and cannot be resized at runtime so,\nif used, it is important to select a large enough heap to cover all\napplication uses.
\nThe heap size given must be a power of two. Any value less than 2\nwill disable the secure heap.
\nThe secure heap is disabled by default.
\nThe secure heap is not available on Windows.
\nSee CRYPTO_secure_malloc_init for more details.
When used with --build-snapshot, --snapshot-blob specifies the path\nwhere the generated snapshot blob is written to. If not specified, the\ngenerated blob is written to snapshot.blob in the current working directory.
When used without --build-snapshot, --snapshot-blob specifies the\npath to the blob that is used to restore the application state.
When loading a snapshot, Node.js checks that:
\nIf they don't match, Node.js refuses to load the snapshot and exits with\nstatus code 1.
", "displayName": "`--snapshot-blob=path`" }, { "textRaw": "`--test`", "name": "`--test`", "type": "module", "meta": { "added": [ "v18.1.0", "v16.17.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46983", "description": "The test runner is now stable." }, { "version": [ "v19.2.0", "v18.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/45214", "description": "Test runner now supports running in watch mode." } ] }, "desc": "Starts the Node.js command line test runner. This flag cannot be combined with\n--watch-path, --check, --eval, --interactive, or the inspector.\nSee the documentation on running tests from the command line\nfor more details.
The maximum number of test files that the test runner CLI will execute\nconcurrently. If --test-isolation is set to 'none', this flag is ignored and\nconcurrency is one. Otherwise, concurrency defaults to\nos.availableParallelism() - 1.
Require a minimum percent of covered branches. If code coverage does not reach\nthe threshold specified, the process will exit with code 1.
Excludes specific files from code coverage using a glob pattern, which can match\nboth absolute and relative file paths.
\nThis option may be specified multiple times to exclude multiple glob patterns.
\nIf both --test-coverage-exclude and --test-coverage-include are provided,\nfiles must meet both criteria to be included in the coverage report.
By default all the matching test files are excluded from the coverage report.\nSpecifying this option will override the default behavior.
", "displayName": "`--test-coverage-exclude`" }, { "textRaw": "`--test-coverage-functions=threshold`", "name": "`--test-coverage-functions=threshold`", "type": "module", "meta": { "added": [ "v22.8.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Require a minimum percent of covered functions. If code coverage does not reach\nthe threshold specified, the process will exit with code 1.
Includes specific files in code coverage using a glob pattern, which can match\nboth absolute and relative file paths.
\nThis option may be specified multiple times to include multiple glob patterns.
\nIf both --test-coverage-exclude and --test-coverage-include are provided,\nfiles must meet both criteria to be included in the coverage report.
Require a minimum percent of covered lines. If code coverage does not reach\nthe threshold specified, the process will exit with code 1.
Configures the test runner to exit the process once all known tests have\nfinished executing even if the event loop would otherwise remain active.
", "displayName": "`--test-force-exit`" }, { "textRaw": "`--test-global-setup=module`", "name": "`--test-global-setup=module`", "type": "module", "meta": { "added": [ "v24.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Early development", "desc": "Specify a module that will be evaluated before all tests are executed and\ncan be used to setup global state or fixtures for tests.
\nSee the documentation on global setup and teardown for more details.
", "displayName": "`--test-global-setup=module`" }, { "textRaw": "`--test-isolation=mode`", "name": "`--test-isolation=mode`", "type": "module", "meta": { "added": [ "v22.8.0" ], "changes": [ { "version": "v23.6.0", "pr-url": "https://github.com/nodejs/node/pull/56298", "description": "This flag was renamed from `--experimental-test-isolation` to `--test-isolation`." } ] }, "desc": "Configures the type of test isolation used in the test runner. When mode is\n'process', each test file is run in a separate child process. When mode is\n'none', all test files run in the same process as the test runner. The default\nisolation mode is 'process'. This flag is ignored if the --test flag is not\npresent. See the test runner execution model section for more information.
A regular expression that configures the test runner to only execute tests\nwhose name matches the provided pattern. See the documentation on\nfiltering tests by name for more details.
\nIf both --test-name-pattern and --test-skip-pattern are supplied,\ntests must satisfy both requirements in order to be executed.
Configures the test runner to only execute top level tests that have the only\noption set. This flag is not necessary when test isolation is disabled.
A test reporter to use when running tests. See the documentation on\ntest reporters for more details.
", "displayName": "`--test-reporter`" }, { "textRaw": "`--test-reporter-destination`", "name": "`--test-reporter-destination`", "type": "module", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46983", "description": "The test runner is now stable." } ] }, "desc": "The destination for the corresponding test reporter. See the documentation on\ntest reporters for more details.
", "displayName": "`--test-reporter-destination`" }, { "textRaw": "`--test-rerun-failures`", "name": "`--test-rerun-failures`", "type": "module", "meta": { "added": [ "v24.7.0" ], "changes": [] }, "desc": "A path to a file allowing the test runner to persist the state of the test\nsuite between runs. The test runner will use this file to determine which tests\nhave already succeeded or failed, allowing for re-running of failed tests\nwithout having to re-run the entire test suite. The test runner will create this\nfile if it does not exist.\nSee the documentation on test reruns for more details.
", "displayName": "`--test-rerun-failures`" }, { "textRaw": "`--test-shard`", "name": "`--test-shard`", "type": "module", "meta": { "added": [ "v20.5.0", "v18.19.0" ], "changes": [] }, "desc": "Test suite shard to execute in a format of <index>/<total>, where
index is a positive integer, index of divided parts.total is a positive integer, total of divided part.This command will divide all tests files into total equal parts,\nand will run only those that happen to be in an index part.
For example, to split your tests suite into three parts, use this:
\nnode --test --test-shard=1/3\nnode --test --test-shard=2/3\nnode --test --test-shard=3/3\n",
"displayName": "`--test-shard`"
},
{
"textRaw": "`--test-skip-pattern`",
"name": "`--test-skip-pattern`",
"type": "module",
"meta": {
"added": [
"v22.1.0"
],
"changes": []
},
"desc": "A regular expression that configures the test runner to skip tests\nwhose name matches the provided pattern. See the documentation on\nfiltering tests by name for more details.
\nIf both --test-name-pattern and --test-skip-pattern are supplied,\ntests must satisfy both requirements in order to be executed.
A number of milliseconds the test execution will fail after. If unspecified,\nsubtests inherit this value from their parent. The default value is Infinity.
Regenerates the snapshot files used by the test runner for snapshot testing.
", "displayName": "`--test-update-snapshots`" }, { "textRaw": "`--throw-deprecation`", "name": "`--throw-deprecation`", "type": "module", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "Throw errors for deprecations.
", "displayName": "`--throw-deprecation`" }, { "textRaw": "`--title=title`", "name": "`--title=title`", "type": "module", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "desc": "Set process.title on startup.
Specify an alternative default TLS cipher list. Requires Node.js to be built\nwith crypto support (default).
", "displayName": "`--tls-cipher-list=list`" }, { "textRaw": "`--tls-keylog=file`", "name": "`--tls-keylog=file`", "type": "module", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "desc": "Log TLS key material to a file. The key material is in NSS SSLKEYLOGFILE\nformat and can be used by software (such as Wireshark) to decrypt the TLS\ntraffic.
Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for\nTLSv1.3.
Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support\nfor TLSv1.3.
Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with\nold TLS clients or servers.
Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility\nwith old TLS clients or servers.
Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.2'. This is the default for\n12.x and later, but the option is supported for compatibility with older Node.js\nversions.
Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support\nfor TLSv1.2, which is not as secure as TLSv1.3.
Print stack traces for deprecations.
", "displayName": "`--trace-deprecation`" }, { "textRaw": "`--trace-env`", "name": "`--trace-env`", "type": "module", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "desc": "Print information about any access to environment variables done in the current Node.js\ninstance to stderr, including:
\nprocess.env.KEY = \"SOME VALUE\".process.env.KEY.Object.defineProperty(process.env, 'KEY', {...}).Object.hasOwn(process.env, 'KEY'),\nprocess.env.hasOwnProperty('KEY') or 'KEY' in process.env.delete process.env.KEY....process.env or Object.keys(process.env).Only the names of the environment variables being accessed are printed. The values are not printed.
\nTo print the stack trace of the access, use --trace-env-js-stack and/or\n--trace-env-native-stack.
In addition to what --trace-env does, this prints the JavaScript stack trace of the access.
In addition to what --trace-env does, this prints the native stack trace of the access.
A comma separated list of categories that should be traced when trace event\ntracing is enabled using --trace-events-enabled.
Template string specifying the filepath for the trace event data, it\nsupports ${rotation} and ${pid}.
Enables the collection of trace event tracing information.
", "displayName": "`--trace-events-enabled`" }, { "textRaw": "`--trace-exit`", "name": "`--trace-exit`", "type": "module", "meta": { "added": [ "v13.5.0", "v12.16.0" ], "changes": [] }, "desc": "Prints a stack trace whenever an environment is exited proactively,\ni.e. invoking process.exit().
Prints information about usage of Loading ECMAScript modules using require().
When mode is all, all usage is printed. When mode is no-node-modules, usage\nfrom the node_modules folder is excluded.
Prints a stack trace on SIGINT.
", "displayName": "`--trace-sigint`" }, { "textRaw": "`--trace-sync-io`", "name": "`--trace-sync-io`", "type": "module", "meta": { "added": [ "v2.1.0" ], "changes": [] }, "desc": "Prints a stack trace whenever synchronous I/O is detected after the first turn\nof the event loop.
", "displayName": "`--trace-sync-io`" }, { "textRaw": "`--trace-tls`", "name": "`--trace-tls`", "type": "module", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "desc": "Prints TLS packet trace information to stderr. This can be used to debug TLS\nconnection problems.
Print stack traces for uncaught exceptions; usually, the stack trace associated\nwith the creation of an Error is printed, whereas this makes Node.js also\nprint the stack trace associated with throwing the value (which does not need\nto be an Error instance).
Enabling this option may affect garbage collection behavior negatively.
", "displayName": "`--trace-uncaught`" }, { "textRaw": "`--trace-warnings`", "name": "`--trace-warnings`", "type": "module", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "Print stack traces for process warnings (including deprecations).
", "displayName": "`--trace-warnings`" }, { "textRaw": "`--track-heap-objects`", "name": "`--track-heap-objects`", "type": "module", "meta": { "added": [ "v2.4.0" ], "changes": [] }, "desc": "Track heap object allocations for heap snapshots.
", "displayName": "`--track-heap-objects`" }, { "textRaw": "`--unhandled-rejections=mode`", "name": "`--unhandled-rejections=mode`", "type": "module", "meta": { "added": [ "v12.0.0", "v10.17.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33021", "description": "Changed default mode to `throw`. Previously, a warning was emitted." } ] }, "desc": "Using this flag allows to change what should happen when an unhandled rejection\noccurs. One of the following modes can be chosen:
\nthrow: Emit unhandledRejection. If this hook is not set, raise the\nunhandled rejection as an uncaught exception. This is the default.strict: Raise the unhandled rejection as an uncaught exception. If the\nexception is handled, unhandledRejection is emitted.warn: Always trigger a warning, no matter if the unhandledRejection\nhook is set or not but do not print the deprecation warning.warn-with-error-code: Emit unhandledRejection. If this hook is not\nset, trigger a warning, and set the process exit code to 1.none: Silence all warnings.If a rejection happens during the command line entry point's ES module static\nloading phase, it will always raise it as an uncaught exception.
", "displayName": "`--unhandled-rejections=mode`" }, { "textRaw": "`--use-bundled-ca`, `--use-openssl-ca`", "name": "`--use-bundled-ca`,_`--use-openssl-ca`", "type": "module", "meta": { "added": [ "v6.11.0" ], "changes": [] }, "desc": "Use bundled Mozilla CA store as supplied by current Node.js version\nor use OpenSSL's default CA store. The default store is selectable\nat build-time.
\nThe bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.
\nUsing OpenSSL store allows for external modifications of the store. For most\nLinux and BSD distributions, this store is maintained by the distribution\nmaintainers and system administrators. OpenSSL CA store location is dependent on\nconfiguration of the OpenSSL library but this can be altered at runtime using\nenvironment variables.
\nSee SSL_CERT_DIR and SSL_CERT_FILE.
When enabled, Node.js parses the HTTP_PROXY, HTTPS_PROXY and NO_PROXY\nenvironment variables during startup, and tunnels requests over the\nspecified proxy.
This is equivalent to setting the NODE_USE_ENV_PROXY=1 environment variable.\nWhen both are set, --use-env-proxy takes precedence.
Re-map the Node.js static code to large memory pages at startup. If supported on\nthe target system, this will cause the Node.js static code to be moved onto 2\nMiB pages instead of 4 KiB pages.
\nThe following values are valid for mode:
off: No mapping will be attempted. This is the default.on: If supported by the OS, mapping will be attempted. Failure to map will\nbe ignored and a message will be printed to standard error.silent: If supported by the OS, mapping will be attempted. Failure to map\nwill be ignored and will not be reported.Node.js uses the trusted CA certificates present in the system store along with\nthe --use-bundled-ca option and the NODE_EXTRA_CA_CERTS environment variable.\nOn platforms other than Windows and macOS, this loads certificates from the directory\nand file trusted by OpenSSL, similar to --use-openssl-ca, with the difference being\nthat it caches the certificates after first load.
On Windows and macOS, the certificate trust policy is similar to\nChromium's policy for locally trusted certificates, but with some differences:
\nOn macOS, the following settings are respected:
\nOn Windows, the following settings are respected:
\ncertlm.msc)\ncertmgr.msc)\nOn Windows and macOS, Node.js would check that the user settings for the trusted\ncertificates do not forbid them for TLS server authentication before using them.
\nNode.js currently does not support distrust/revocation of certificates\nfrom another source based on system settings.
\nOn other systems, Node.js loads certificates from the default certificate file\n(typically /etc/ssl/cert.pem) and default certificate directory (typically\n/etc/ssl/certs) that the version of OpenSSL that Node.js links to respects.\nThis typically works with the convention on major Linux distributions and other\nUnix-like systems. If the overriding OpenSSL environment variables\n(typically SSL_CERT_FILE and SSL_CERT_DIR, depending on the configuration\nof the OpenSSL that Node.js links to) are set, the specified paths will be used to load\ncertificates instead. These environment variables can be used as workarounds\nif the conventional paths used by the version of OpenSSL Node.js links to are\nnot consistent with the system configuration that the users have for some reason.
Print V8 command-line options.
", "displayName": "`--v8-options`" }, { "textRaw": "`--v8-pool-size=num`", "name": "`--v8-pool-size=num`", "type": "module", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "desc": "Set V8's thread pool size which will be used to allocate background jobs.
\nIf set to 0 then Node.js will choose an appropriate size of the thread pool\nbased on an estimate of the amount of parallelism.
The amount of parallelism refers to the number of computations that can be\ncarried out simultaneously in a given machine. In general, it's the same as the\namount of CPUs, but it may diverge in environments such as VMs or containers.
", "displayName": "`--v8-pool-size=num`" }, { "textRaw": "`-v`, `--version`", "name": "`-v`,_`--version`", "type": "module", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "Print node's version.
", "displayName": "`-v`, `--version`" }, { "textRaw": "`--watch`", "name": "`--watch`", "type": "module", "meta": { "added": [ "v18.11.0", "v16.19.0" ], "changes": [ { "version": [ "v22.0.0", "v20.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/52074", "description": "Watch mode is now stable." }, { "version": [ "v19.2.0", "v18.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/45214", "description": "Test runner now supports running in watch mode." } ] }, "desc": "Starts Node.js in watch mode.\nWhen in watch mode, changes in the watched files cause the Node.js process to\nrestart.\nBy default, watch mode will watch the entry point\nand any required or imported module.\nUse --watch-path to specify what paths to watch.
This flag cannot be combined with\n--check, --eval, --interactive, or the REPL.
Note: The --watch flag requires a file path as an argument and is incompatible\nwith --run or inline script input, as --run takes precedence and ignores watch\nmode. If no file is provided, Node.js will exit with status code 9.
node --watch index.js\n",
"displayName": "`--watch`"
},
{
"textRaw": "`--watch-kill-signal`",
"name": "`--watch-kill-signal`",
"type": "module",
"meta": {
"added": [
"v24.4.0",
"v22.18.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active Development",
"desc": "Customizes the signal sent to the process on watch mode restarts.
\nnode --watch --watch-kill-signal SIGINT test.js\n",
"displayName": "`--watch-kill-signal`"
},
{
"textRaw": "`--watch-path`",
"name": "`--watch-path`",
"type": "module",
"meta": {
"added": [
"v18.11.0",
"v16.19.0"
],
"changes": [
{
"version": [
"v22.0.0",
"v20.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/52074",
"description": "Watch mode is now stable."
}
]
},
"desc": "Starts Node.js in watch mode and specifies what paths to watch.\nWhen in watch mode, changes in the watched paths cause the Node.js process to\nrestart.\nThis will turn off watching of required or imported modules, even when used in\ncombination with --watch.
This flag cannot be combined with\n--check, --eval, --interactive, --test, or the REPL.
Note: Using --watch-path implicitly enables --watch, which requires a file path\nand is incompatible with --run, as --run takes precedence and ignores watch mode.
node --watch-path=./src --watch-path=./tests index.js\n\nThis option is only supported on macOS and Windows.\nAn ERR_FEATURE_UNAVAILABLE_ON_PLATFORM exception will be thrown\nwhen the option is used on a platform that does not support it.
Disable the clearing of the console when watch mode restarts the process.
\nnode --watch --watch-preserve-output test.js\n",
"displayName": "`--watch-preserve-output`"
},
{
"textRaw": "`--zero-fill-buffers`",
"name": "`--zero-fill-buffers`",
"type": "module",
"meta": {
"added": [
"v6.0.0"
],
"changes": []
},
"desc": "Automatically zero-fills all newly allocated Buffer instances.
The FORCE_COLOR environment variable is used to\nenable ANSI colorized output. The value may be:
1, true, or the empty string '' indicate 16-color support,2 to indicate 256-color support, or3 to indicate 16 million-color support.When FORCE_COLOR is used and set to a supported value, both the NO_COLOR,\nand NODE_DISABLE_COLORS environment variables are ignored.
Any other value will result in colorized output being disabled.
", "displayName": "`FORCE_COLOR=[1, 2, 3]`" }, { "textRaw": "`NODE_COMPILE_CACHE=dir`", "name": "`node_compile_cache=dir`", "type": "module", "meta": { "added": [ "v22.1.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60971", "description": "This feature is no longer experimental." } ] }, "desc": "Enable the module compile cache for the Node.js instance. See the documentation of\nmodule compile cache for details.
", "displayName": "`NODE_COMPILE_CACHE=dir`" }, { "textRaw": "`NODE_COMPILE_CACHE_PORTABLE=1`", "name": "`node_compile_cache_portable=1`", "type": "module", "desc": "When set to 1, the module compile cache can be reused across different directory\nlocations as long as the module layout relative to the cache directory remains the same.
", "displayName": "`NODE_COMPILE_CACHE_PORTABLE=1`" }, { "textRaw": "`NODE_DEBUG=module[,…]`", "name": "`node_debug=module[,…]`", "type": "module", "meta": { "added": [ "v0.1.32" ], "changes": [] }, "desc": "','-separated list of core modules that should print debug information.
','-separated list of core C++ modules that should print debug information.
When set, colors will not be used in the REPL.
", "displayName": "`NODE_DISABLE_COLORS=1`" }, { "textRaw": "`NODE_DISABLE_COMPILE_CACHE=1`", "name": "`node_disable_compile_cache=1`", "type": "module", "meta": { "added": [ "v22.8.0" ], "changes": [] }, "stability": 1.1, "stabilityText": "Active Development", "desc": "Disable the module compile cache for the Node.js instance. See the documentation of\nmodule compile cache for details.
", "displayName": "`NODE_DISABLE_COMPILE_CACHE=1`" }, { "textRaw": "`NODE_EXTRA_CA_CERTS=file`", "name": "`node_extra_ca_certs=file`", "type": "module", "meta": { "added": [ "v7.3.0" ], "changes": [] }, "desc": "When set, the well known \"root\" CAs (like VeriSign) will be extended with the\nextra certificates in file. The file should consist of one or more trusted\ncertificates in PEM format. A message will be emitted (once) with\nprocess.emitWarning() if the file is missing or\nmalformed, but any errors are otherwise ignored.
Neither the well known nor extra certificates are used when the ca\noptions property is explicitly specified for a TLS or HTTPS client or server.
This environment variable is ignored when node runs as setuid root or\nhas Linux file capabilities set.
The NODE_EXTRA_CA_CERTS environment variable is only read when the Node.js\nprocess is first launched. Changing the value at runtime using\nprocess.env.NODE_EXTRA_CA_CERTS has no effect on the current process.
Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.
When set to 1, process warnings are silenced.
A space-separated list of command-line options. options... are interpreted\nbefore command-line options, so command-line options will override or\ncompound after anything in options.... Node.js will exit with an error if\nan option that is not allowed in the environment is used, such as -p or a\nscript file.
If an option value contains a space, it can be escaped using double quotes:
\nNODE_OPTIONS='--require \"./my path/file.js\"'\n\nA singleton flag passed as a command-line option will override the same flag\npassed into NODE_OPTIONS:
# The inspector will be available on port 5555\nNODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555\n\nA flag that can be passed multiple times will be treated as if its\nNODE_OPTIONS instances were passed first, and then its command-line\ninstances afterwards:
NODE_OPTIONS='--require \"./a.js\"' node --require \"./b.js\"\n# is equivalent to:\nnode --require \"./a.js\" --require \"./b.js\"\n\nNode.js options that are allowed are in the following list. If an option\nsupports both --XX and --no-XX variants, they are both supported but only\none is included in the list below.
\n--allow-addons--allow-child-process--allow-fs-read--allow-fs-write--allow-inspector--allow-net--allow-wasi--allow-worker--conditions, -C--cpu-prof-dir--cpu-prof-interval--cpu-prof-name--cpu-prof--diagnostic-dir--disable-proto--disable-sigusr1--disable-warning--disable-wasm-trap-handler--dns-result-order--enable-fips--enable-network-family-autoselection--enable-source-maps--entry-url--experimental-abortcontroller--experimental-addon-modules--experimental-detect-module--experimental-eventsource--experimental-import-meta-resolve--experimental-json-modules--experimental-loader--experimental-modules--experimental-print-required-tla--experimental-quic--experimental-require-module--experimental-shadow-realm--experimental-specifier-resolution--experimental-test-isolation--experimental-top-level-await--experimental-transform-types--experimental-vm-modules--experimental-wasi-unstable-preview1--force-context-aware--force-fips--force-node-api-uncaught-exceptions-policy--frozen-intrinsics--heap-prof-dir--heap-prof-interval--heap-prof-name--heap-prof--heapsnapshot-near-heap-limit--heapsnapshot-signal--http-parser--icu-data-dir--import--input-type--insecure-http-parser--inspect-brk--inspect-port, --debug-port--inspect-publish-uid--inspect-wait--inspect--localstorage-file--max-http-header-size--max-old-space-size-percentage--napi-modules--network-family-autoselection-attempt-timeout--no-addons--no-async-context-frame--no-deprecation--no-experimental-global-navigator--no-experimental-repl-await--no-experimental-sqlite--no-experimental-strip-types--no-experimental-websocket--no-experimental-webstorage--no-extra-info-on-fatal-exception--no-force-async-hooks-checks--no-global-search-paths--no-network-family-autoselection--no-strip-types--no-warnings--no-webstorage--node-memory-debug--openssl-config--openssl-legacy-provider--openssl-shared-config--pending-deprecation--permission-audit--permission--preserve-symlinks-main--preserve-symlinks--prof-process--redirect-warnings--report-compact--report-dir, --report-directory--report-exclude-env--report-exclude-network--report-filename--report-on-fatalerror--report-on-signal--report-signal--report-uncaught-exception--require-module--require, -r--secure-heap-min--secure-heap--snapshot-blob--test-coverage-branches--test-coverage-exclude--test-coverage-functions--test-coverage-include--test-coverage-lines--test-global-setup--test-isolation--test-name-pattern--test-only--test-reporter-destination--test-reporter--test-rerun-failures--test-shard--test-skip-pattern--throw-deprecation--title--tls-cipher-list--tls-keylog--tls-max-v1.2--tls-max-v1.3--tls-min-v1.0--tls-min-v1.1--tls-min-v1.2--tls-min-v1.3--trace-deprecation--trace-env-js-stack--trace-env-native-stack--trace-env--trace-event-categories--trace-event-file-pattern--trace-events-enabled--trace-exit--trace-require-module--trace-sigint--trace-sync-io--trace-tls--trace-uncaught--trace-warnings--track-heap-objects--unhandled-rejections--use-bundled-ca--use-env-proxy--use-largepages--use-openssl-ca--use-system-ca--v8-pool-size--watch-kill-signal--watch-path--watch-preserve-output--watch--zero-fill-buffersV8 options that are allowed are:
\n--abort-on-uncaught-exception--disallow-code-generation-from-strings--enable-etw-stack-walking--expose-gc--interpreted-frames-native-stack--jitless--max-old-space-size--max-semi-space-size--perf-basic-prof-only-functions--perf-basic-prof--perf-prof-unwinding-info--perf-prof--stack-trace-limit--perf-basic-prof-only-functions, --perf-basic-prof,\n--perf-prof-unwinding-info, and --perf-prof are only available on Linux.
--enable-etw-stack-walking is only available on Windows.
':'-separated list of directories prefixed to the module search path.
On Windows, this is a ';'-separated list instead.
When set to 1, emit pending deprecation warnings.
Pending deprecations are generally identical to a runtime deprecation with the\nnotable exception that they are turned off by default and will not be emitted\nunless either the --pending-deprecation command-line flag, or the\nNODE_PENDING_DEPRECATION=1 environment variable, is set. Pending deprecations\nare used to provide a kind of selective \"early warning\" mechanism that\ndevelopers may leverage to detect deprecated API usage.
Set the number of pending pipe instance handles when the pipe server is waiting\nfor connections. This setting applies to Windows only.
", "displayName": "`NODE_PENDING_PIPE_INSTANCES=instances`" }, { "textRaw": "`NODE_PRESERVE_SYMLINKS=1`", "name": "`node_preserve_symlinks=1`", "type": "module", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "desc": "When set to 1, instructs the module loader to preserve symbolic links when\nresolving and caching modules.
When set, process warnings will be emitted to the given file instead of\nprinting to stderr. The file will be created if it does not exist, and will be\nappended to if it does. If an error occurs while attempting to write the\nwarning to the file, the warning will be written to stderr instead. This is\nequivalent to using the --redirect-warnings=file command-line flag.
Path to a Node.js module which will be loaded in place of the built-in REPL.\nOverriding this value to an empty string ('') will use the built-in REPL.
Path to the file used to store the persistent REPL history. The default path is\n~/.node_repl_history, which is overridden by this variable. Setting the value\nto an empty string ('' or ' ') disables persistent REPL history.
If value equals '1', the check for a supported platform is skipped during\nNode.js startup. Node.js might not execute correctly. Any issues encountered\non unsupported platforms will not be fixed.
If value equals 'child', test reporter options will be overridden and test\noutput will be sent to stdout in the TAP format. If any other value is provided,\nNode.js makes no guarantees about the reporter format used or its stability.
If value equals '0', certificate validation is disabled for TLS connections.\nThis makes TLS, and HTTPS by extension, insecure. The use of this environment\nvariable is strongly discouraged.
When enabled, Node.js parses the HTTP_PROXY, HTTPS_PROXY and NO_PROXY\nenvironment variables during startup, and tunnels requests over the\nspecified proxy.
This can also be enabled using the --use-env-proxy command-line flag.\nWhen both are set, --use-env-proxy takes precedence.
Node.js uses the trusted CA certificates present in the system store along with\nthe --use-bundled-ca option and the NODE_EXTRA_CA_CERTS environment variable.
This can also be enabled using the --use-system-ca command-line flag.\nWhen both are set, --use-system-ca takes precedence.
When set, Node.js will begin outputting V8 JavaScript code coverage and\nSource Map data to the directory provided as an argument (coverage\ninformation is written as JSON to files with a coverage prefix).
NODE_V8_COVERAGE will automatically propagate to subprocesses, making it\neasier to instrument applications that call the child_process.spawn() family\nof functions. NODE_V8_COVERAGE can be set to an empty string, to prevent\npropagation.
Coverage is output as an array of ScriptCoverage objects on the top-level\nkey result:
{\n \"result\": [\n {\n \"scriptId\": \"67\",\n \"url\": \"internal/tty.js\",\n \"functions\": []\n }\n ]\n}\n",
"displayName": "Coverage output"
},
{
"textRaw": "Source map cache",
"name": "source_map_cache",
"type": "module",
"stability": 1,
"stabilityText": "Experimental",
"desc": "If found, source map data is appended to the top-level key source-map-cache\non the JSON coverage object.
source-map-cache is an object with keys representing the files source maps\nwere extracted from, and values which include the raw source-map URL\n(in the key url), the parsed Source Map v3 information (in the key data),\nand the line lengths of the source file (in the key lineLengths).
{\n \"result\": [\n {\n \"scriptId\": \"68\",\n \"url\": \"file:///absolute/path/to/source.js\",\n \"functions\": []\n }\n ],\n \"source-map-cache\": {\n \"file:///absolute/path/to/source.js\": {\n \"url\": \"./path-to-map.json\",\n \"data\": {\n \"version\": 3,\n \"sources\": [\n \"file:///absolute/path/to/original.js\"\n ],\n \"names\": [\n \"Foo\",\n \"console\",\n \"info\"\n ],\n \"mappings\": \"MAAMA,IACJC,YAAaC\",\n \"sourceRoot\": \"./\"\n },\n \"lineLengths\": [\n 13,\n 62,\n 38,\n 27\n ]\n }\n }\n}\n",
"displayName": "Source map cache"
}
],
"displayName": "`NODE_V8_COVERAGE=dir`"
},
{
"textRaw": "`NO_COLOR=NO_COLOR is an alias for NODE_DISABLE_COLORS. The value of the\nenvironment variable is arbitrary.
Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with\n./configure --openssl-fips.
If the --openssl-config command-line option is used, the environment\nvariable is ignored.
If --use-openssl-ca is enabled, or if --use-system-ca is enabled on\nplatforms other than macOS and Windows, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.
Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.
", "displayName": "`SSL_CERT_DIR=dir`" }, { "textRaw": "`SSL_CERT_FILE=file`", "name": "`ssl_cert_file=file`", "type": "module", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "desc": "If --use-openssl-ca is enabled, or if --use-system-ca is enabled on\nplatforms other than macOS and Windows, this overrides and sets OpenSSL's file\ncontaining trusted certificates.
Be aware that unless the child environment is explicitly set, this environment\nvariable will be inherited by any child processes, and if they use OpenSSL, it\nmay cause them to trust the same CAs as node.
", "displayName": "`SSL_CERT_FILE=file`" }, { "textRaw": "`TZ`", "name": "`tz`", "type": "module", "meta": { "added": [ "v0.0.1" ], "changes": [ { "version": [ "v16.2.0" ], "pr-url": "https://github.com/nodejs/node/pull/38642", "description": "Changing the TZ variable using process.env.TZ = changes the timezone on Windows as well." }, { "version": [ "v13.0.0" ], "pr-url": "https://github.com/nodejs/node/pull/20026", "description": "Changing the TZ variable using process.env.TZ = changes the timezone on POSIX systems." } ] }, "desc": "The TZ environment variable is used to specify the timezone configuration.
While Node.js does not support all of the various ways that TZ is handled in\nother environments, it does support basic timezone IDs (such as\n'Etc/UTC', 'Europe/Paris', or 'America/New_York').\nIt may support a few other abbreviations or aliases, but these are strongly\ndiscouraged and not guaranteed.
$ TZ=Europe/Dublin node -pe \"new Date().toString()\"\nWed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time)\n",
"displayName": "`TZ`"
},
{
"textRaw": "`UV_THREADPOOL_SIZE=size`",
"name": "`uv_threadpool_size=size`",
"type": "module",
"desc": "Set the number of threads used in libuv's threadpool to size threads.
Asynchronous system APIs are used by Node.js whenever possible, but where they\ndo not exist, libuv's threadpool is used to create asynchronous node APIs based\non synchronous system APIs. Node.js APIs that use the threadpool are:
\nfs APIs, other than the file watcher APIs and those that are explicitly\nsynchronouscrypto.pbkdf2(), crypto.scrypt(),\ncrypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()dns.lookup()zlib APIs, other than those that are explicitly synchronousBecause libuv's threadpool has a fixed size, it means that if for whatever\nreason any of these APIs takes a long time, other (seemingly unrelated) APIs\nthat run in libuv's threadpool will experience degraded performance. In order to\nmitigate this issue, one potential solution is to increase the size of libuv's\nthreadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value\ngreater than 4 (its current default value). However, setting this from inside\nthe process using process.env.UV_THREADPOOL_SIZE=size is not guranteed to work\nas the threadpool would have been created as part of the runtime initialisation\nmuch before user code is run. For more information, see the libuv threadpool documentation.
V8 has its own set of CLI options. Any V8 CLI option that is provided to node\nwill be passed on to V8 to handle. V8's options have no stability guarantee.\nThe V8 team themselves don't consider them to be part of their formal API,\nand reserve the right to change them at any time. Likewise, they are not\ncovered by the Node.js stability guarantees. Many of the V8\noptions are of interest only to V8 developers. Despite this, there is a small\nset of V8 options that are widely applicable to Node.js, and they are\ndocumented here:
Sets the max memory size of V8's old memory section. As memory\nconsumption approaches the limit, V8 will spend more time on\ngarbage collection in an effort to free unused memory.
\nOn a machine with 2 GiB of memory, consider setting this to\n1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.
\nnode --max-old-space-size=1536 index.js\n\n",
"displayName": "`--max-old-space-size=SIZE` (in MiB)"
},
{
"textRaw": "`--max-semi-space-size=SIZE` (in MiB)",
"name": "`--max-semi-space-size=size`_(in_mib)",
"type": "module",
"desc": "Sets the maximum semi-space size for V8's scavenge garbage collector in\nMiB (mebibytes).\nIncreasing the max size of a semi-space may improve throughput for Node.js at\nthe cost of more memory consumption.
\nSince the young generation size of the V8 heap is three times (see\nYoungGenerationSizeFromSemiSpaceSize in V8) the size of the semi-space,\nan increase of 1 MiB to semi-space applies to each of the three individual\nsemi-spaces and causes the heap size to increase by 3 MiB. The throughput\nimprovement depends on your workload (see #42511).
The default value depends on the memory limit. For example, on 64-bit systems\nwith a memory limit of 512 MiB, the max size of a semi-space defaults to 1 MiB.\nFor memory limits up to and including 2GiB, the default max size of a\nsemi-space will be less than 16 MiB on 64-bit systems.
\nTo get the best configuration for your application, you should try different\nmax-semi-space-size values when running benchmarks for your application.
\nFor example, benchmark on a 64-bit systems:
\nfor MiB in 16 32 64 128; do\n node --max-semi-space-size=$MiB index.js\ndone\n",
"displayName": "`--max-semi-space-size=SIZE` (in MiB)"
},
{
"textRaw": "`--perf-basic-prof`",
"name": "`--perf-basic-prof`",
"type": "module",
"displayName": "`--perf-basic-prof`"
},
{
"textRaw": "`--perf-basic-prof-only-functions`",
"name": "`--perf-basic-prof-only-functions`",
"type": "module",
"displayName": "`--perf-basic-prof-only-functions`"
},
{
"textRaw": "`--perf-prof`",
"name": "`--perf-prof`",
"type": "module",
"displayName": "`--perf-prof`"
},
{
"textRaw": "`--perf-prof-unwinding-info`",
"name": "`--perf-prof-unwinding-info`",
"type": "module",
"displayName": "`--perf-prof-unwinding-info`"
},
{
"textRaw": "`--prof`",
"name": "`--prof`",
"type": "module",
"displayName": "`--prof`"
},
{
"textRaw": "`--security-revert`",
"name": "`--security-revert`",
"type": "module",
"displayName": "`--security-revert`"
},
{
"textRaw": "`--stack-trace-limit=limit`",
"name": "`--stack-trace-limit=limit`",
"type": "module",
"desc": "The maximum number of stack frames to collect in an error's stack trace.\nSetting it to 0 disables stack trace collection. The default value is 10.
\nnode --stack-trace-limit=12 -p -e \"Error.stackTraceLimit\" # prints 12\n",
"displayName": "`--stack-trace-limit=limit`"
}
],
"displayName": "Useful V8 options"
}
],
"source": "doc/api/cli.md"
},
{
"textRaw": "Debugger",
"name": "Debugger",
"introduced_in": "v0.9.12",
"type": "misc",
"stability": 2,
"stabilityText": "Stable",
"desc": "Node.js includes a command-line debugging utility. The Node.js debugger client\nis not a full-featured debugger, but simple stepping and inspection are\npossible.
\nTo use it, start Node.js with the inspect argument followed by the path to the\nscript to debug.
$ node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8\n< For help, see: https://nodejs.org/en/docs/inspector\n<\nconnecting to 127.0.0.1:9229 ... ok\n< Debugger attached.\n<\n ok\nBreak on start in myscript.js:2\n 1 // myscript.js\n> 2 global.x = 5;\n 3 setTimeout(() => {\n 4 debugger;\ndebug>\n\nThe debugger automatically breaks on the first executable line. To instead\nrun until the first breakpoint (specified by a debugger statement), set\nthe NODE_INSPECT_RESUME_ON_START environment variable to 1.
$ cat myscript.js\n// myscript.js\nglobal.x = 5;\nsetTimeout(() => {\n debugger;\n console.log('world');\n}, 1000);\nconsole.log('hello');\n$ NODE_INSPECT_RESUME_ON_START=1 node inspect myscript.js\n< Debugger listening on ws://127.0.0.1:9229/f1ed133e-7876-495b-83ae-c32c6fc319c2\n< For help, see: https://nodejs.org/en/docs/inspector\n<\nconnecting to 127.0.0.1:9229 ... ok\n< Debugger attached.\n<\n< hello\n<\nbreak in myscript.js:4\n 2 global.x = 5;\n 3 setTimeout(() => {\n> 4 debugger;\n 5 console.log('world');\n 6 }, 1000);\ndebug> next\nbreak in myscript.js:5\n 3 setTimeout(() => {\n 4 debugger;\n> 5 console.log('world');\n 6 }, 1000);\n 7 console.log('hello');\ndebug> repl\nPress Ctrl+C to leave debug repl\n> x\n5\n> 2 + 2\n4\ndebug> next\n< world\n<\nbreak in myscript.js:6\n 4 debugger;\n 5 console.log('world');\n> 6 }, 1000);\n 7 console.log('hello');\n 8\ndebug> .exit\n$\n\nThe repl command allows code to be evaluated remotely. The next command\nsteps to the next line. Type help to see what other commands are available.
Pressing enter without typing a command will repeat the previous debugger\ncommand.
It is possible to watch expression and variable values while debugging. On\nevery breakpoint, each expression from the watchers list will be evaluated\nin the current context and displayed immediately before the breakpoint's\nsource code listing.
\nTo begin watching an expression, type watch('my_expression'). The command\nwatchers will print the active watchers. To remove a watcher, type\nunwatch('my_expression').
cont, c: Continue executionnext, n: Step nextstep, s: Step inout, o: Step outpause: Pause running code (like pause button in Developer Tools)setBreakpoint(), sb(): Set breakpoint on current linesetBreakpoint(line), sb(line): Set breakpoint on specific linesetBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in\nfunction's bodysetBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of\nscript.jssetBreakpoint('script.js', 1, 'num < 4'), sb(...): Set conditional\nbreakpoint on first line of script.js that only breaks when num < 4\nevaluates to trueclearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js\non line 1It is also possible to set a breakpoint in a file (module) that\nis not loaded yet:
\n$ node inspect main.js\n< Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9\n< For help, see: https://nodejs.org/en/docs/inspector\n<\nconnecting to 127.0.0.1:9229 ... ok\n< Debugger attached.\n<\nBreak on start in main.js:1\n> 1 const mod = require('./mod.js');\n 2 mod.hello();\n 3 mod.hello();\ndebug> setBreakpoint('mod.js', 22)\nWarning: script 'mod.js' was not loaded yet.\ndebug> c\nbreak in mod.js:22\n 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.\n 21\n>22 exports.hello = function() {\n 23 return 'hello from module';\n 24 };\ndebug>\n\nIt is also possible to set a conditional breakpoint that only breaks when a\ngiven expression evaluates to true:
$ node inspect main.js\n< Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35\n< For help, see: https://nodejs.org/en/docs/inspector\n<\nconnecting to 127.0.0.1:9229 ... ok\n< Debugger attached.\nBreak on start in main.js:7\n 5 }\n 6\n> 7 addOne(10);\n 8 addOne(-1);\n 9\ndebug> setBreakpoint('main.js', 4, 'num < 0')\n 1 'use strict';\n 2\n 3 function addOne(num) {\n> 4 return num + 1;\n 5 }\n 6\n 7 addOne(10);\n 8 addOne(-1);\n 9\ndebug> cont\nbreak in main.js:4\n 2\n 3 function addOne(num) {\n> 4 return num + 1;\n 5 }\n 6\ndebug> exec('num')\n-1\ndebug>\n",
"displayName": "Breakpoints"
},
{
"textRaw": "Information",
"name": "information",
"type": "module",
"desc": "backtrace, bt: Print backtrace of current execution framelist(5): List scripts source code with 5 line context (5 lines before and\nafter)watch(expr): Add expression to watch listunwatch(expr): Remove expression from watch listunwatch(index): Remove expression at specific index from watch listwatchers: List all watchers and their values (automatically listed on each\nbreakpoint)repl: Open debugger's repl for evaluation in debugging script's contextexec expr, p expr: Execute an expression in debugging script's context and\nprint its valueprofile: Start CPU profiling sessionprofileEnd: Stop current CPU profiling sessionprofiles: List all completed CPU profiling sessionsprofiles[n].save(filepath = 'node.cpuprofile'): Save CPU profiling session\nto disk as JSONtakeHeapSnapshot(filepath = 'node.heapsnapshot'): Take a heap snapshot\nand save to disk as JSONrun: Run script (automatically runs on debugger's start)restart: Restart scriptkill: Kill scriptscripts: List all loaded scriptsversion: Display V8's versionV8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling. It uses the\nChrome DevTools Protocol.
\nV8 Inspector can be enabled by passing the --inspect flag when starting a\nNode.js application. It is also possible to supply a custom port with that flag,\ne.g. --inspect=9222 will accept DevTools connections on port 9222.
Using the --inspect flag will execute the code immediately before debugger is connected.\nThis means that the code will start running before you can start debugging, which might\nnot be ideal if you want to debug from the very beginning.
In such cases, you have two alternatives:
\n--inspect-wait flag: This flag will wait for debugger to be attached before executing the code.\nThis allows you to start debugging right from the beginning of the execution.--inspect-brk flag: Unlike --inspect, this flag will break on the first line of the code\nas soon as debugger is attached. This is useful when you want to debug the code step by step\nfrom the very beginning, without any code execution prior to debugging.So, when deciding between --inspect, --inspect-wait, and --inspect-brk, consider whether you want\nthe code to start executing immediately, wait for debugger to be attached before execution,\nor break on the first line for step-by-step debugging.
$ node --inspect index.js\nDebugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nFor help, see: https://nodejs.org/en/docs/inspector\n\n(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29\nat the end of the URL is generated on the fly, it varies in different\ndebugging sessions.)
\nIf the Chrome browser is older than 66.0.3345.0,\nuse inspector.html instead of js_app.html in the above URL.
Chrome DevTools doesn't support debugging worker threads yet.\nndb can be used to debug them.
", "displayName": "V8 inspector integration for Node.js" } ], "displayName": "Advanced usage" } ], "source": "doc/api/debugger.md" }, { "textRaw": "Deprecated APIs", "name": "Deprecated APIs", "introduced_in": "v7.7.0", "type": "misc", "desc": "Node.js APIs might be deprecated for any of the following reasons:
\nNode.js uses four kinds of deprecations:
\nnode_modules code only)A Documentation-only deprecation is one that is expressed only within the\nNode.js API docs. These generate no side-effects while running Node.js.\nSome Documentation-only deprecations trigger a runtime warning when launched\nwith --pending-deprecation flag (or its alternative,\nNODE_PENDING_DEPRECATION=1 environment variable), similarly to Runtime\ndeprecations below. Documentation-only deprecations that support that flag\nare explicitly labeled as such in the\nlist of Deprecated APIs.
An Application deprecation for only non-node_modules code will, by default,\ngenerate a process warning that will be printed to stderr the first time\nthe deprecated API is used in code that's not loaded from node_modules.\nWhen the --throw-deprecation command-line flag is used, a Runtime\ndeprecation will cause an error to be thrown. When\n--pending-deprecation is used, warnings will also be emitted for\ncode loaded from node_modules.
A runtime deprecation for all code is similar to the runtime deprecation\nfor non-node_modules code, except that it also emits a warning for\ncode loaded from node_modules.
An End-of-Life deprecation is used when functionality is or will soon be removed\nfrom Node.js.
", "miscs": [ { "textRaw": "Revoking deprecations", "name": "revoking_deprecations", "type": "misc", "desc": "Occasionally, the deprecation of an API might be reversed. In such situations,\nthis document will be updated with information relevant to the decision.\nHowever, the deprecation identifier will not be modified.
", "displayName": "Revoking deprecations" }, { "textRaw": "List of deprecated APIs", "name": "list_of_deprecated_apis", "type": "misc", "modules": [ { "textRaw": "DEP0001: `http.OutgoingMessage.prototype.flush`", "name": "dep0001:_`http.outgoingmessage.prototype.flush`", "type": "module", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31164", "description": "End-of-Life." }, { "version": [ "v6.12.0", "v4.8.6" ], "pr-url": "https://github.com/nodejs/node/pull/10116", "description": "A deprecation code has been assigned." }, { "version": "v1.6.0", "pr-url": "https://github.com/nodejs/node/pull/1156", "description": "Runtime deprecation." } ] }, "desc": "Type: End-of-Life
\nOutgoingMessage.prototype.flush() has been removed. Use\nOutgoingMessage.prototype.flushHeaders() instead.
Type: End-of-Life
\nThe _linklist module is deprecated. Please use a userland alternative.
Type: End-of-Life
\nThe _writableState.buffer has been removed. Use _writableState.getBuffer()\ninstead.
Type: End-of-Life
\nThe CryptoStream.prototype.readyState property was removed.
Type: Application (non-node_modules code only)
The Buffer() function and new Buffer() constructor are deprecated due to\nAPI usability issues that can lead to accidental security issues.
As an alternative, use one of the following methods of constructing Buffer\nobjects:
Buffer.alloc(size[, fill[, encoding]]): Create a Buffer with\ninitialized memory.Buffer.allocUnsafe(size): Create a Buffer with\nuninitialized memory.Buffer.allocUnsafeSlow(size): Create a Buffer with uninitialized\nmemory.Buffer.from(array): Create a Buffer with a copy of arrayBuffer.from(arrayBuffer[, byteOffset[, length]]) -\nCreate a Buffer that wraps the given arrayBuffer.Buffer.from(buffer): Create a Buffer that copies buffer.Buffer.from(string[, encoding]): Create a Buffer\nthat copies string.Without --pending-deprecation, runtime warnings occur only for code not in\nnode_modules. This means there will not be deprecation warnings for\nBuffer() usage in dependencies. With --pending-deprecation, a runtime\nwarning results no matter where the Buffer() usage occurs.
Type: End-of-Life
\nWithin the child_process module's spawn(), fork(), and exec()\nmethods, the options.customFds option is deprecated. The options.stdio\noption should be used instead.
Type: End-of-Life
\nIn an earlier version of the Node.js cluster, a boolean property with the name\nsuicide was added to the Worker object. The intent of this property was to\nprovide an indication of how and why the Worker instance exited. In Node.js\n6.0.0, the old property was deprecated and replaced with a new\nworker.exitedAfterDisconnect property. The old property name did not\nprecisely describe the actual semantics and was unnecessarily emotion-laden.
Type: Documentation-only
\nThe node:constants module is deprecated. When requiring access to constants\nrelevant to specific Node.js builtin modules, developers should instead refer\nto the constants property exposed by the relevant module. For instance,\nrequire('node:fs').constants and require('node:os').constants.
Type: End-of-Life
\nUse of the crypto.pbkdf2() API without specifying a digest was deprecated\nin Node.js 6.0 because the method defaulted to using the non-recommended\n'SHA1' digest. Previously, a deprecation warning was printed. Starting in\nNode.js 8.0.0, calling crypto.pbkdf2() or crypto.pbkdf2Sync() with\ndigest set to undefined will throw a TypeError.
Beginning in Node.js 11.0.0, calling these functions with digest set to\nnull would print a deprecation warning to align with the behavior when digest\nis undefined.
Now, however, passing either undefined or null will throw a TypeError.
Type: End-of-Life
\nThe crypto.createCredentials() API was removed. Please use\ntls.createSecureContext() instead.
Type: End-of-Life
\nThe crypto.Credentials class was removed. Please use tls.SecureContext\ninstead.
Type: End-of-Life
\nDomain.dispose() has been removed. Recover from failed I/O actions\nexplicitly via error event handlers set on the domain instead.
Type: End-of-Life
\nCalling an asynchronous function without a callback throws a TypeError\nin Node.js 10.0.0 onwards. See https://github.com/nodejs/node/pull/12562.
Type: End-of-Life
\nThe fs.read() legacy String interface is deprecated. Use the Buffer\nAPI as mentioned in the documentation instead.
Type: End-of-Life
\nThe fs.readSync() legacy String interface is deprecated. Use the\nBuffer API as mentioned in the documentation instead.
Type: End-of-Life
\nThe GLOBAL and root aliases for the global property were deprecated\nin Node.js 6.0.0 and have since been removed.
Type: End-of-Life
\nIntl.v8BreakIterator was a non-standard extension and has been removed.\nSee Intl.Segmenter.
Type: End-of-Life
\nUnhandled promise rejections are deprecated. By default, promise rejections\nthat are not handled terminate the Node.js process with a non-zero exit\ncode. To change the way Node.js treats unhandled rejections, use the\n--unhandled-rejections command-line option.
Type: End-of-Life
\nIn certain cases, require('.') could resolve outside the package directory.\nThis behavior has been removed.
Type: End-of-Life
\nThe Server.connections property was deprecated in Node.js 0.9.7 and has\nbeen removed. Please use the Server.getConnections() method instead.
Type: End-of-Life
\nThe Server.listenFD() method was deprecated and removed. Please use\nServer.listen({fd: <number>}) instead.
Type: End-of-Life
\nThe os.tmpDir() API was deprecated in Node.js 7.0.0 and has since been\nremoved. Please use os.tmpdir() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/tmpDir-to-tmpdir\n",
"displayName": "DEP0022: `os.tmpDir()`"
},
{
"textRaw": "DEP0023: `os.getNetworkInterfaces()`",
"name": "dep0023:_`os.getnetworkinterfaces()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/25280",
"description": "End-of-Life."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v0.6.0",
"commit": "37bb37d151fb6ee4696730e63ff28bb7a4924f97",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe os.getNetworkInterfaces() method is deprecated. Please use the\nos.networkInterfaces() method instead.
Type: End-of-Life
\nThe REPLServer.prototype.convertToContext() API has been removed.
Type: Runtime
\nThe node:sys module is deprecated. Please use the util module instead.
Type: End-of-Life
\nutil.print() has been removed. Please use console.log() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-print-to-console-log\n",
"displayName": "DEP0026: `util.print()`"
},
{
"textRaw": "DEP0027: `util.puts()`",
"name": "dep0027:_`util.puts()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/25377",
"description": "End-of-Life."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v0.11.3",
"commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nutil.puts() has been removed. Please use console.log() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-print-to-console-log\n",
"displayName": "DEP0027: `util.puts()`"
},
{
"textRaw": "DEP0028: `util.debug()`",
"name": "dep0028:_`util.debug()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/25377",
"description": "End-of-Life."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v0.11.3",
"commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nutil.debug() has been removed. Please use console.error() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-print-to-console-log\n",
"displayName": "DEP0028: `util.debug()`"
},
{
"textRaw": "DEP0029: `util.error()`",
"name": "dep0029:_`util.error()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/25377",
"description": "End-of-Life."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v0.11.3",
"commit": "896b2aa7074fc886efd7dd0a397d694763cac7ce",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nutil.error() has been removed. Please use console.error() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-print-to-console-log\n",
"displayName": "DEP0029: `util.error()`"
},
{
"textRaw": "DEP0030: `SlowBuffer`",
"name": "dep0030:_`slowbuffer`",
"type": "module",
"meta": {
"changes": [
{
"version": "v25.0.0",
"pr-url": "https://github.com/nodejs/node/pull/58220",
"description": "End-of-Life."
},
{
"version": "v24.0.0",
"pr-url": "https://github.com/nodejs/node/pull/55175",
"description": "Runtime deprecation."
},
{
"version": "v6.12.0",
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/5833",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe SlowBuffer class has been removed. Please use\nBuffer.allocUnsafeSlow(size) instead.
An automated migration is available (source).
\nnpx codemod@latest @nodejs/slow-buffer-to-buffer-alloc-unsafe-slow\n",
"displayName": "DEP0030: `SlowBuffer`"
},
{
"textRaw": "DEP0031: `ecdh.setPublicKey()`",
"name": "dep0031:_`ecdh.setpublickey()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v25.0.0",
"pr-url": "https://github.com/nodejs/node/pull/58620",
"description": "Runtime deprecation."
},
{
"version": "v6.12.0",
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v5.2.0",
"pr-url": "https://github.com/nodejs/node/pull/3511",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Runtime
\nThe ecdh.setPublicKey() method is now deprecated as its inclusion in\nthe API is not useful.
Type: Documentation-only
\nThe domain module is deprecated and should not be used.
Type: Revoked
\nThe events.listenerCount(emitter, eventName) API was deprecated, as it\nprovided identical fuctionality to emitter.listenerCount(eventName). The\ndeprecation was revoked because this function has been repurposed to also\naccept <EventTarget> arguments.
Type: Documentation-only
\nThe fs.exists(path, callback) API is deprecated. Please use\nfs.stat() or fs.access() instead.
Type: Documentation-only
\nThe fs.lchmod(path, mode, callback) API is deprecated.
Type: Documentation-only
\nThe fs.lchmodSync(path, mode) API is deprecated.
Type: Deprecation revoked
\nThe fs.lchown(path, uid, gid, callback) API was deprecated. The\ndeprecation was revoked because the requisite supporting APIs were added in\nlibuv.
Type: Deprecation revoked
\nThe fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was\nrevoked because the requisite supporting APIs were added in libuv.
Type: Documentation-only
\nThe require.extensions property is deprecated.
Type: Application (non-node_modules code only)
The punycode module is deprecated. Please use a userland alternative\ninstead.
Type: End-of-Life
\nThe NODE_REPL_HISTORY_FILE environment variable was removed. Please use\nNODE_REPL_HISTORY instead.
Type: End-of-Life
\nThe tls.CryptoStream class was removed. Please use\ntls.TLSSocket instead.
Type: End-of-Life
\nThe tls.SecurePair class is deprecated. Please use\ntls.TLSSocket instead.
Type: Runtime
\nThe util.isArray() API is deprecated. Please use Array.isArray()\ninstead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0044: `util.isArray()`"
},
{
"textRaw": "DEP0045: `util.isBoolean()`",
"name": "dep0045:_`util.isboolean()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isBoolean() API has been removed. Please use\ntypeof arg === 'boolean' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0045: `util.isBoolean()`"
},
{
"textRaw": "DEP0046: `util.isBuffer()`",
"name": "dep0046:_`util.isbuffer()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isBuffer() API has been removed. Please use\nBuffer.isBuffer() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0046: `util.isBuffer()`"
},
{
"textRaw": "DEP0047: `util.isDate()`",
"name": "dep0047:_`util.isdate()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isDate() API has been removed. Please use\narg instanceof Date instead.
Also for stronger approaches, consider using:\nDate.prototype.toString.call(arg) === '[object Date]' && !isNaN(arg).\nThis can also be used in a try/catch block to handle invalid date objects.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0047: `util.isDate()`"
},
{
"textRaw": "DEP0048: `util.isError()`",
"name": "dep0048:_`util.iserror()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isError() API has been removed. Please use Error.isError(arg).
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0048: `util.isError()`"
},
{
"textRaw": "DEP0049: `util.isFunction()`",
"name": "dep0049:_`util.isfunction()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isFunction() API has been removed. Please use\ntypeof arg === 'function' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0049: `util.isFunction()`"
},
{
"textRaw": "DEP0050: `util.isNull()`",
"name": "dep0050:_`util.isnull()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isNull() API has been removed. Please use\narg === null instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0050: `util.isNull()`"
},
{
"textRaw": "DEP0051: `util.isNullOrUndefined()`",
"name": "dep0051:_`util.isnullorundefined()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isNullOrUndefined() API has been removed. Please use\narg === null || arg === undefined instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0051: `util.isNullOrUndefined()`"
},
{
"textRaw": "DEP0052: `util.isNumber()`",
"name": "dep0052:_`util.isnumber()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isNumber() API has been removed. Please use\ntypeof arg === 'number' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0052: `util.isNumber()`"
},
{
"textRaw": "DEP0053: `util.isObject()`",
"name": "dep0053:_`util.isobject()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isObject() API has been removed. Please use\narg && typeof arg === 'object' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0053: `util.isObject()`"
},
{
"textRaw": "DEP0054: `util.isPrimitive()`",
"name": "dep0054:_`util.isprimitive()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isPrimitive() API has been removed. Please use Object(arg) !== arg instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0054: `util.isPrimitive()`"
},
{
"textRaw": "DEP0055: `util.isRegExp()`",
"name": "dep0055:_`util.isregexp()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isRegExp() API has been removed. Please use\narg instanceof RegExp instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0055: `util.isRegExp()`"
},
{
"textRaw": "DEP0056: `util.isString()`",
"name": "dep0056:_`util.isstring()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isString() API has been removed. Please use\ntypeof arg === 'string' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0056: `util.isString()`"
},
{
"textRaw": "DEP0057: `util.isSymbol()`",
"name": "dep0057:_`util.issymbol()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isSymbol() API has been removed. Please use\ntypeof arg === 'symbol' instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0057: `util.isSymbol()`"
},
{
"textRaw": "DEP0058: `util.isUndefined()`",
"name": "dep0058:_`util.isundefined()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": [
"v6.12.0",
"v4.8.6"
],
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": [
"v4.0.0",
"v3.3.1"
],
"pr-url": "https://github.com/nodejs/node/pull/2447",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.isUndefined() API has been removed. Please use\narg === undefined instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-is\n",
"displayName": "DEP0058: `util.isUndefined()`"
},
{
"textRaw": "DEP0059: `util.log()`",
"name": "dep0059:_`util.log()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v23.0.0",
"pr-url": "https://github.com/nodejs/node/pull/52744",
"description": "End-of-Life deprecation."
},
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": "v6.12.0",
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/6161",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.log() API has been removed because it's an unmaintained\nlegacy API that was exposed to user land by accident. Instead,\nconsider the following alternatives based on your specific needs:
Third-Party Logging Libraries
\nUse console.log(new Date().toLocaleString(), message)
By adopting one of these alternatives, you can transition away from util.log()\nand choose a logging strategy that aligns with the specific\nrequirements and complexity of your application.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-log-to-console-log\n",
"displayName": "DEP0059: `util.log()`"
},
{
"textRaw": "DEP0060: `util._extend()`",
"name": "dep0060:_`util._extend()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/50488",
"description": "Runtime deprecation."
},
{
"version": "v6.12.0",
"pr-url": "https://github.com/nodejs/node/pull/10116",
"description": "A deprecation code has been assigned."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/4903",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Runtime
\nThe util._extend() API is deprecated because it's an unmaintained\nlegacy API that was exposed to user land by accident.\nPlease use target = Object.assign(target, source) instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/util-extend-to-object-assign\n",
"displayName": "DEP0060: `util._extend()`"
},
{
"textRaw": "DEP0061: `fs.SyncWriteStream`",
"name": "dep0061:_`fs.syncwritestream`",
"type": "module",
"meta": {
"changes": [
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/20735",
"description": "End-of-Life."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10467",
"description": "Runtime deprecation."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/6749",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe fs.SyncWriteStream class was never intended to be a publicly accessible\nAPI and has been removed. No alternative API is available. Please use a userland\nalternative.
Type: End-of-Life
\n--debug activates the legacy V8 debugger interface, which was removed as\nof V8 5.8. It is replaced by Inspector which is activated with --inspect\ninstead.
Type: Runtime
\nThe node:http module ServerResponse.prototype.writeHeader() API is\ndeprecated. Please use ServerResponse.prototype.writeHead() instead.
The ServerResponse.prototype.writeHeader() method was never documented as an\nofficially supported API.
Type: End-of-Life
\nThe tls.createSecurePair() API was deprecated in documentation in Node.js\n0.11.3. Users should use tls.Socket instead.
Type: End-of-Life
\nThe node:repl module's REPL_MODE_MAGIC constant, used for replMode option,\nhas been removed. Its behavior has been functionally identical to that of\nREPL_MODE_SLOPPY since Node.js 6.0.0, when V8 5.0 was imported. Please use\nREPL_MODE_SLOPPY instead.
The NODE_REPL_MODE environment variable is used to set the underlying\nreplMode of an interactive node session. Its value, magic, is also\nremoved. Please use sloppy instead.
Type: End-of-Life
\nThe node:http module OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties are deprecated. Use one of\nthe public methods (e.g. OutgoingMessage.prototype.getHeader(),\nOutgoingMessage.prototype.getHeaders(),\nOutgoingMessage.prototype.getHeaderNames(),\nOutgoingMessage.prototype.getRawHeaderNames(),\nOutgoingMessage.prototype.hasHeader(),\nOutgoingMessage.prototype.removeHeader(),\nOutgoingMessage.prototype.setHeader()) for working with outgoing headers.
The OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties were never documented as\nofficially supported properties.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/http-outgoingmessage-headers\n",
"displayName": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`"
},
{
"textRaw": "DEP0067: `OutgoingMessage.prototype._renderHeaders`",
"name": "dep0067:_`outgoingmessage.prototype._renderheaders`",
"type": "module",
"meta": {
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10941",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nThe node:http module OutgoingMessage.prototype._renderHeaders() API is\ndeprecated.
The OutgoingMessage.prototype._renderHeaders property was never documented as\nan officially supported API.
Type: End-of-Life
\nnode debug corresponds to the legacy CLI debugger which has been replaced with\na V8-inspector based CLI debugger available through node inspect.
Type: End-of-Life
\nDebugContext has been removed in V8 and is not available in Node.js 10+.
\nDebugContext was an experimental API.
", "displayName": "DEP0069: `vm.runInDebugContext(string)`" }, { "textRaw": "DEP0070: `async_hooks.currentId()`", "name": "dep0070:_`async_hooks.currentid()`", "type": "module", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/14414", "description": "End-of-Life." }, { "version": "v8.2.0", "pr-url": "https://github.com/nodejs/node/pull/13490", "description": "Runtime deprecation." } ] }, "desc": "Type: End-of-Life
\nasync_hooks.currentId() was renamed to async_hooks.executionAsyncId() for\nclarity.
This change was made while async_hooks was an experimental API.
Type: End-of-Life
\nasync_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for\nclarity.
This change was made while async_hooks was an experimental API.
Type: End-of-Life
\nasync_hooks.AsyncResource.triggerId() was renamed to\nasync_hooks.AsyncResource.triggerAsyncId() for clarity.
This change was made while async_hooks was an experimental API.
Type: End-of-Life
\nAccessing several internal, undocumented properties of net.Server instances\nwith inappropriate names is deprecated.
As the original API was undocumented and not generally useful for non-internal\ncode, no replacement API is provided.
", "displayName": "DEP0073: Several internal properties of `net.Server`" }, { "textRaw": "DEP0074: `REPLServer.bufferedCommand`", "name": "dep0074:_`replserver.bufferedcommand`", "type": "module", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33286", "description": "End-of-Life." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/13687", "description": "Runtime deprecation." } ] }, "desc": "Type: End-of-Life
\nThe REPLServer.bufferedCommand property was deprecated in favor of\nREPLServer.clearBufferedCommand().
Type: End-of-Life
\nREPLServer.parseREPLKeyword() was removed from userland visibility.
Type: End-of-Life
\ntls.parseCertString() was a trivial parsing helper that was made public by\nmistake. While it was supposed to parse certificate subject and issuer strings,\nit never handled multi-value Relative Distinguished Names correctly.
Earlier versions of this document suggested using querystring.parse() as an\nalternative to tls.parseCertString(). However, querystring.parse() also does\nnot handle all certificate subjects correctly and should not be used.
Type: End-of-Life
\nModule._debug() has been removed.
The Module._debug() function was never documented as an officially\nsupported API.
Type: End-of-Life
\nREPLServer.turnOffEditorMode() was removed from userland visibility.
Type: End-of-Life
\nUsing a property named inspect on an object to specify a custom inspection\nfunction for util.inspect() is deprecated. Use util.inspect.custom\ninstead. For backward compatibility with Node.js prior to version 6.4.0, both\ncan be specified.
Type: Documentation-only
\nThe internal path._makeLong() was not intended for public use. However,\nuserland modules have found it useful. The internal API is deprecated\nand replaced with an identical, public path.toNamespacedPath() method.
Type: End-of-Life
\nfs.truncate() fs.truncateSync() usage with a file descriptor is\ndeprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with\nfile descriptors.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/fs-truncate-fd-deprecation\n",
"displayName": "DEP0081: `fs.truncate()` using a file descriptor"
},
{
"textRaw": "DEP0082: `REPLServer.prototype.memory()`",
"name": "dep0082:_`replserver.prototype.memory()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/33286",
"description": "End-of-Life."
},
{
"version": "v9.0.0",
"pr-url": "https://github.com/nodejs/node/pull/16242",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nREPLServer.prototype.memory() is only necessary for the internal mechanics of\nthe REPLServer itself. Do not use this function.
Type: End-of-Life
\nThe ecdhCurve option to tls.createSecureContext() and tls.TLSSocket could\nbe set to false to disable ECDH entirely on the server only. This mode was\ndeprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with\nthe client and is now unsupported. Use the ciphers parameter instead.
Type: End-of-Life
\nSince Node.js versions 4.4.0 and 5.2.0, several modules only intended for\ninternal usage were mistakenly exposed to user code through require(). These\nmodules were:
v8/tools/codemapv8/tools/consarrayv8/tools/csvparserv8/tools/logreaderv8/tools/profile_viewv8/tools/profilev8/tools/SourceMapv8/tools/splaytreev8/tools/tickprocessor-driverv8/tools/tickprocessornode-inspect/lib/_inspect (from 7.6.0)node-inspect/lib/internal/inspect_client (from 7.6.0)node-inspect/lib/internal/inspect_repl (from 7.6.0)The v8/* modules do not have any exports, and if not imported in a specific\norder would in fact throw errors. As such there are virtually no legitimate use\ncases for importing them through require().
On the other hand, node-inspect can be installed locally through a package\nmanager, as it is published on the npm registry under the same name. No source\ncode modification is necessary if that is done.
Type: End-of-Life
\nThe AsyncHooks sensitive API was never documented and had various minor issues.\nUse the AsyncResource API instead. See\nhttps://github.com/nodejs/node/issues/15572.
Type: End-of-Life
\nrunInAsyncIdScope doesn't emit the 'before' or 'after' event and can thus\ncause a lot of issues. See https://github.com/nodejs/node/issues/14328.
Type: Deprecation revoked
\nImporting assert directly was not recommended as the exposed functions use\nloose equality checks. The deprecation was revoked because use of the\nnode:assert module is not discouraged, and the deprecation caused developer\nconfusion.
Type: End-of-Life
\nNode.js used to support all GCM authentication tag lengths which are accepted by\nOpenSSL when calling decipher.setAuthTag(). Beginning with Node.js\nv11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32\nbits are allowed. Authentication tags of other lengths are invalid per\nNIST SP 800-38D.
Type: End-of-Life
\nThe crypto.DEFAULT_ENCODING property only existed for compatibility with\nNode.js releases prior to versions 0.9.3 and has been removed.
Type: Documentation-only
\nAssigning properties to the top-level this as an alternative\nto module.exports is deprecated. Developers should use exports\nor module.exports instead.
Type: Runtime
\nThe crypto.fips property is deprecated. Please use crypto.setFips()\nand crypto.getFips() instead.
An automated migration is available (source).
\nnpx codemod@latest @nodejs/crypto-fips-to-getFips\n",
"displayName": "DEP0093: `crypto.fips` is deprecated and replaced"
},
{
"textRaw": "DEP0094: Using `assert.fail()` with more than one argument",
"name": "dep0094:_using_`assert.fail()`_with_more_than_one_argument",
"type": "module",
"meta": {
"changes": [
{
"version": "v25.0.0",
"pr-url": "https://github.com/nodejs/node/pull/58532",
"description": "End-of-Life."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18418",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nUsing assert.fail() with more than one argument is deprecated. Use\nassert.fail() with only one argument or use a different node:assert module\nmethod.
Type: End-of-Life
\ntimers.enroll() has been removed. Please use the publicly documented\nsetTimeout() or setInterval() instead.
Type: End-of-Life
\ntimers.unenroll() has been removed. Please use the publicly documented\nclearTimeout() or clearInterval() instead.
Type: Runtime
\nUsers of MakeCallback that add the domain property to carry context,\nshould start using the async_context variant of MakeCallback or\nCallbackScope, or the high-level AsyncResource class.
Type: End-of-Life
\nThe embedded API provided by AsyncHooks exposes .emitBefore() and\n.emitAfter() methods which are very easy to use incorrectly which can lead\nto unrecoverable errors.
Use asyncResource.runInAsyncScope() API instead which provides a much\nsafer, and more convenient, alternative. See\nhttps://github.com/nodejs/node/pull/18513.
Type: Compile-time
\nCertain versions of node::MakeCallback APIs available to native addons are\ndeprecated. Please use the versions of the API that accept an async_context\nparameter.
Type: End-of-Life
\nprocess.assert() is deprecated. Please use the assert module instead.
This was never a documented feature.
\nAn automated migration is available (source).
\nnpx codemod@latest @nodejs/process-assert-to-node-assert\n",
"displayName": "DEP0100: `process.assert()`"
},
{
"textRaw": "DEP0101: `--with-lttng`",
"name": "dep0101:_`--with-lttng`",
"type": "module",
"meta": {
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18982",
"description": "End-of-Life."
}
]
},
"desc": "Type: End-of-Life
\nThe --with-lttng compile-time option has been removed.
Type: End-of-Life
\nUsing the noAssert argument has no functionality anymore. All input is\nverified regardless of the value of noAssert. Skipping the verification\ncould lead to hard-to-find errors and crashes.
Type: Documentation-only (supports --pending-deprecation)
Using process.binding() in general should be avoided. The type checking\nmethods in particular can be replaced by using util.types.
This deprecation has been superseded by the deprecation of the\nprocess.binding() API (DEP0111).
Type: Documentation-only (supports --pending-deprecation)
When assigning a non-string property to process.env, the assigned value is\nimplicitly converted to a string. This behavior is deprecated if the assigned\nvalue is not a string, boolean, or number. In the future, such assignment might\nresult in a thrown error. Please convert the property to a string before\nassigning it to process.env.
Type: End-of-Life
\ndecipher.finaltol() has never been documented and was an alias for\ndecipher.final(). This API has been removed, and it is recommended to use\ndecipher.final() instead.
Type: End-of-Life
\ncrypto.createCipher() and crypto.createDecipher() have been removed\nas they use a weak key derivation function (MD5 with no salt) and static\ninitialization vectors.\nIt is recommended to derive a key using\ncrypto.pbkdf2() or crypto.scrypt() with random salts and to use\ncrypto.createCipheriv() and crypto.createDecipheriv() to obtain the\nCipheriv and Decipheriv objects respectively.
Type: End-of-Life
\nThis was an undocumented helper function not intended for use outside Node.js\ncore and obsoleted by the removal of NPN (Next Protocol Negotiation) support.
", "displayName": "DEP0107: `tls.convertNPNProtocols()`" }, { "textRaw": "DEP0108: `zlib.bytesRead`", "name": "dep0108:_`zlib.bytesread`", "type": "module", "meta": { "changes": [ { "version": "v23.0.0", "pr-url": "https://github.com/nodejs/node/pull/55020", "description": "End-of-Life." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/23308", "description": "Runtime deprecation." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19414", "description": "Documentation-only deprecation." } ] }, "desc": "Type: End-of-Life
\nDeprecated alias for zlib.bytesWritten. This original name was chosen\nbecause it also made sense to interpret the value as the number of bytes\nread by the engine, but is inconsistent with other streams in Node.js that\nexpose values under these names.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/zlib-bytesread-to-byteswritten\n",
"displayName": "DEP0108: `zlib.bytesRead`"
},
{
"textRaw": "DEP0109: `http`, `https`, and `tls` support for invalid URLs",
"name": "dep0109:_`http`,_`https`,_and_`tls`_support_for_invalid_urls",
"type": "module",
"meta": {
"changes": [
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/36853",
"description": "End-of-Life."
},
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/20270",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nSome previously supported (but strictly invalid) URLs were accepted through the\nhttp.request(), http.get(), https.request(),\nhttps.get(), and tls.checkServerIdentity() APIs because those were\naccepted by the legacy url.parse() API. The mentioned APIs now use the WHATWG\nURL parser that requires strictly valid URLs. Passing an invalid URL is\ndeprecated and support will be removed in the future.
Type: Documentation-only
\nThe produceCachedData option is deprecated. Use\nscript.createCachedData() instead.
Type: Documentation-only (supports --pending-deprecation)
process.binding() is for use by Node.js internal code only.
While process.binding() has not reached End-of-Life status in general, it is\nunavailable when the permission model is enabled.
Type: End-of-Life
\nThe node:dgram module previously contained several APIs that were never meant\nto accessed outside of Node.js core: Socket.prototype._handle,\nSocket.prototype._receiving, Socket.prototype._bindState,\nSocket.prototype._queue, Socket.prototype._reuseAddr,\nSocket.prototype._healthCheck(), Socket.prototype._stopReceiving(), and\ndgram._createSocketHandle(). These have been removed.
Type: End-of-Life
\nCipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They\nwere never documented and would throw when called.
Type: End-of-Life
\nThe crypto._toBuf() function was not designed to be used by modules outside\nof Node.js core and was removed.
Type: Documentation-only (supports --pending-deprecation)
In recent versions of Node.js, there is no difference between\ncrypto.randomBytes() and crypto.pseudoRandomBytes(). The latter is\ndeprecated along with the undocumented aliases crypto.prng() and\ncrypto.rng() in favor of crypto.randomBytes() and might be removed in a\nfuture release.
Type: Deprecation revoked
\nThe legacy URL API is deprecated. This includes url.format(),\nurl.parse(), url.resolve(), and the legacy urlObject. Please\nuse the WHATWG URL API instead.
An automated migration is available (source).
\nnpx codemod@latest @nodejs/node-url-to-whatwg-url\n",
"displayName": "DEP0116: Legacy URL API"
},
{
"textRaw": "DEP0117: Native crypto handles",
"name": "dep0117:_native_crypto_handles",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/27011",
"description": "End-of-Life."
},
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/22747",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nPrevious versions of Node.js exposed handles to internal native objects through\nthe _handle property of the Cipher, Decipher, DiffieHellman,\nDiffieHellmanGroup, ECDH, Hash, Hmac, Sign, and Verify classes.\nThe _handle property has been removed because improper use of the native\nobject can lead to crashing the application.
Type: End-of-Life
\nPrevious versions of Node.js supported dns.lookup() with a falsy host name\nlike dns.lookup(false) due to backward compatibility. This has been removed.
Type: Documentation-only (supports --pending-deprecation)
process.binding('uv').errname() is deprecated. Please use\nutil.getSystemErrorName() instead.
Type: End-of-Life
\nWindows Performance Counter support has been removed from Node.js. The\nundocumented COUNTER_NET_SERVER_CONNECTION(),\nCOUNTER_NET_SERVER_CONNECTION_CLOSE(), COUNTER_HTTP_SERVER_REQUEST(),\nCOUNTER_HTTP_SERVER_RESPONSE(), COUNTER_HTTP_CLIENT_REQUEST(), and\nCOUNTER_HTTP_CLIENT_RESPONSE() functions have been deprecated.
Type: End-of-Life
\nThe undocumented net._setSimultaneousAccepts() function was originally\nintended for debugging and performance tuning when using the\nnode:child_process and node:cluster modules on Windows. The function is not\ngenerally useful and is being removed. See discussion here:\nhttps://github.com/nodejs/node/issues/18391
Type: End-of-Life
\nPlease use Server.prototype.setSecureContext() instead.
Type: End-of-Life
\nSetting the TLS ServerName to an IP address is not permitted by\nRFC 6066.
", "displayName": "DEP0123: setting the TLS ServerName to an IP address" }, { "textRaw": "DEP0124: using `REPLServer.rli`", "name": "dep0124:_using_`replserver.rli`", "type": "module", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33286", "description": "End-of-Life." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26260", "description": "Runtime deprecation." } ] }, "desc": "Type: End-of-Life
\nThis property is a reference to the instance itself.
", "displayName": "DEP0124: using `REPLServer.rli`" }, { "textRaw": "DEP0125: `require('node:_stream_wrap')`", "name": "dep0125:_`require('node:_stream_wrap')`", "type": "module", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26245", "description": "Runtime deprecation." } ] }, "desc": "Type: Runtime
\nThe node:_stream_wrap module is deprecated.
Type: End-of-Life
\nThe previously undocumented timers.active() has been removed.\nPlease use the publicly documented timeout.refresh() instead.\nIf re-referencing the timeout is necessary, timeout.ref() can be used\nwith no performance impact since Node.js 10.
Type: End-of-Life
\nThe previously undocumented and \"private\" timers._unrefActive() has been removed.\nPlease use the publicly documented timeout.refresh() instead.\nIf unreferencing the timeout is necessary, timeout.unref() can be used\nwith no performance impact since Node.js 10.
Type: Runtime
\nModules that have an invalid main entry (e.g., ./does-not-exist.js) and\nalso have an index.js file in the top level directory will resolve the\nindex.js file. That is deprecated and is going to throw an error in future\nNode.js versions.
Type: End-of-Life
\nThe _channel property of child process objects returned by spawn() and\nsimilar functions is not intended for public use. Use ChildProcess.channel\ninstead.
Type: End-of-Life
\nUse module.createRequire() instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/create-require-from-path\n",
"displayName": "DEP0130: `Module.createRequireFromPath()`"
},
{
"textRaw": "DEP0131: Legacy HTTP parser",
"name": "dep0131:_legacy_http_parser",
"type": "module",
"meta": {
"changes": [
{
"version": "v13.0.0",
"pr-url": "https://github.com/nodejs/node/pull/29589",
"description": "This feature has been removed."
},
{
"version": "v12.22.0",
"pr-url": "https://github.com/nodejs/node/pull/37603",
"description": "Runtime deprecation."
},
{
"version": "v12.3.0",
"pr-url": "https://github.com/nodejs/node/pull/27498",
"description": "Documentation-only."
}
]
},
"desc": "Type: End-of-Life
\nThe legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,\nis deprecated and has been removed in v13.0.0. Prior to v13.0.0, the\n--http-parser=legacy command-line flag could be used to revert to using the\nlegacy parser.
Type: End-of-Life
\nPassing a callback to worker.terminate() is deprecated. Use the returned\nPromise instead, or a listener to the worker's 'exit' event.
Type: Documentation-only
\nPrefer response.socket over response.connection and\nrequest.socket over request.connection.
Type: Documentation-only (supports --pending-deprecation)
The process._tickCallback property was never documented as\nan officially supported API.
Type: End-of-Life
\nWriteStream.open() and ReadStream.open() are undocumented internal\nAPIs that do not make sense to use in userland. File streams should always be\nopened through their corresponding factory methods fs.createWriteStream()\nand fs.createReadStream()) or by passing a file descriptor in options.
Type: Documentation-only
\nresponse.finished indicates whether response.end() has been\ncalled, not whether 'finish' has been emitted and the underlying data\nis flushed.
Use response.writableFinished or response.writableEnded\naccordingly instead to avoid the ambiguity.
To maintain existing behavior response.finished should be replaced with\nresponse.writableEnded.
Type: End-of-Life
\nAllowing a fs.FileHandle object to be closed on garbage collection used\nto be allowed, but now throws an error.
Please ensure that all fs.FileHandle objects are explicitly closed using\nFileHandle.prototype.close() when the fs.FileHandle is no longer needed:
const fsPromises = require('node:fs').promises;\nasync function openAndClose() {\n let filehandle;\n try {\n filehandle = await fsPromises.open('thefile.txt', 'r');\n } finally {\n if (filehandle !== undefined)\n await filehandle.close();\n }\n}\n",
"displayName": "DEP0137: Closing fs.FileHandle on garbage collection"
},
{
"textRaw": "DEP0138: `process.mainModule`",
"name": "dep0138:_`process.mainmodule`",
"type": "module",
"meta": {
"changes": [
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/32232",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nprocess.mainModule is a CommonJS-only feature while process global\nobject is shared with non-CommonJS environment. Its use within ECMAScript\nmodules is unsupported.
It is deprecated in favor of require.main, because it serves the same\npurpose and is only available on CommonJS environment.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/process-main-module\n",
"displayName": "DEP0138: `process.mainModule`"
},
{
"textRaw": "DEP0139: `process.umask()` with no arguments",
"name": "dep0139:_`process.umask()`_with_no_arguments",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v14.0.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/32499",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nCalling process.umask() with no argument causes the process-wide umask to be\nwritten twice. This introduces a race condition between threads, and is a\npotential security vulnerability. There is no safe, cross-platform alternative\nAPI.
Type: Documentation-only
\nUse request.destroy() instead of request.abort().
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exported the input and output stream twice. Use .input\ninstead of .inputStream and .output instead of .outputStream.
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exports a _builtinLibs property that contains an array\nof built-in modules. It was incomplete so far and instead it's better to rely\nupon require('node:module').builtinModules.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/repl-builtin-modules\n",
"displayName": "DEP0142: `repl._builtinLibs`"
},
{
"textRaw": "DEP0143: `Transform._transformState`",
"name": "dep0143:_`transform._transformstate`",
"type": "module",
"meta": {
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/33105",
"description": "End-of-Life."
},
{
"version": "v14.5.0",
"pr-url": "https://github.com/nodejs/node/pull/33126",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: End-of-Life
\nTransform._transformState will be removed in future versions where it is\nno longer required due to simplification of the implementation.
Type: Documentation-only (supports --pending-deprecation)
A CommonJS module can access the first module that required it using\nmodule.parent. This feature is deprecated because it does not work\nconsistently in the presence of ECMAScript modules and because it gives an\ninaccurate representation of the CommonJS module graph.
Some modules use it to check if they are the entry point of the current process.\nInstead, it is recommended to compare require.main and module:
if (require.main === module) {\n // Code section that will run only if current file is the entry point.\n}\n\nWhen looking for the CommonJS modules that have required the current one,\nrequire.cache and module.children can be used:
const moduleParents = Object.values(require.cache)\n .filter((m) => m.children.includes(module));\n",
"displayName": "DEP0144: `module.parent`"
},
{
"textRaw": "DEP0145: `socket.bufferSize`",
"name": "dep0145:_`socket.buffersize`",
"type": "module",
"meta": {
"changes": [
{
"version": "v14.6.0",
"pr-url": "https://github.com/nodejs/node/pull/34088",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nsocket.bufferSize is just an alias for writable.writableLength.
Type: Documentation-only
\nThe crypto.Certificate() constructor is deprecated. Use\nstatic methods of crypto.Certificate() instead.
Type: End-of-Life
\nThe fs.rmdir, fs.rmdirSync, and fs.promises.rmdir methods used\nto support a recursive option. That option has been removed.
Use fs.rm(path, { recursive: true, force: true }),\nfs.rmSync(path, { recursive: true, force: true }) or\nfs.promises.rm(path, { recursive: true, force: true }) instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/rmdir\n",
"displayName": "DEP0147: `fs.rmdir(path, { recursive: true })`"
},
{
"textRaw": "DEP0148: Folder mappings in `\"exports\"` (trailing `\"/\"`)",
"name": "dep0148:_folder_mappings_in_`\"exports\"`_(trailing_`\"/\"`)",
"type": "module",
"meta": {
"changes": [
{
"version": "v17.0.0",
"pr-url": "https://github.com/nodejs/node/pull/40121",
"description": "End-of-Life."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37215",
"description": "Runtime deprecation."
},
{
"version": "v15.1.0",
"pr-url": "https://github.com/nodejs/node/pull/35747",
"description": "Runtime deprecation for self-referencing imports."
},
{
"version": "v14.13.0",
"pr-url": "https://github.com/nodejs/node/pull/34718",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nUsing a trailing \"/\" to define subpath folder mappings in the\nsubpath exports or subpath imports fields is no longer supported.\nUse subpath patterns instead.
Type: Documentation-only
\nPrefer message.socket over message.connection.
Type: End-of-Life
\nThe process.config property provides access to Node.js compile-time settings.\nHowever, the property is mutable and therefore subject to tampering. The ability\nto change the value will be removed in a future version of Node.js.
Type: Runtime
\nPreviously, index.js and extension searching lookups would apply to\nimport 'pkg' main entry point resolution, even when resolving ES modules.
With this deprecation, all ES module main entry point resolutions require\nan explicit \"exports\" or \"main\" entry with the exact file extension.
Type: End-of-Life
\nThe 'gc', 'http2', and 'http' <PerformanceEntry> object types used to have\nadditional properties assigned to them that provide additional information.\nThese properties are now available within the standard detail property\nof the PerformanceEntry object. The deprecated accessors have been\nremoved.
Type: End-of-Life
\nUsing a non-nullish non-integer value for family option, a non-nullish\nnon-number value for hints option, a non-nullish non-boolean value for all\noption, or a non-nullish non-boolean value for verbatim option in\ndns.lookup() and dnsPromises.lookup() throws an\nERR_INVALID_ARG_TYPE error.
Type: End-of-Life
\nUse 'hashAlgorithm' instead of 'hash', and 'mgf1HashAlgorithm' instead of 'mgf1Hash'.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/crypto-rsa-pss-update\n",
"displayName": "DEP0154: RSA-PSS generate key pair options"
},
{
"textRaw": "DEP0155: Trailing slashes in pattern specifier resolutions",
"name": "dep0155:_trailing_slashes_in_pattern_specifier_resolutions",
"type": "module",
"meta": {
"changes": [
{
"version": "v17.0.0",
"pr-url": "https://github.com/nodejs/node/pull/40117",
"description": "Runtime deprecation."
},
{
"version": "v16.10.0",
"pr-url": "https://github.com/nodejs/node/pull/40039",
"description": "Documentation-only deprecation with `--pending-deprecation` support."
}
]
},
"desc": "Type: Runtime
\nThe remapping of specifiers ending in \"/\" like import 'pkg/x/' is deprecated\nfor package \"exports\" and \"imports\" pattern resolutions.
Type: Documentation-only
\nMove to <Stream> API instead, as the http.ClientRequest,\nhttp.ServerResponse, and http.IncomingMessage are all stream-based.\nCheck stream.destroyed instead of the .aborted property, and listen for\n'close' instead of 'abort', 'aborted' event.
The .aborted property and 'abort' event are only useful for detecting\n.abort() calls. For closing a request early, use the Stream\n.destroy([error]) then check the .destroyed property and 'close' event\nshould have the same effect. The receiving end should also check the\nreadable.readableEnded value on http.IncomingMessage to get whether\nit was an aborted or graceful destroy.
Type: End-of-Life
\nAn undocumented feature of Node.js streams was to support thenables in\nimplementation methods. This is now deprecated, use callbacks instead and avoid\nuse of async function for streams implementation methods.
\nThis feature caused users to encounter unexpected problems where the user\nimplements the function in callback style but uses e.g. an async method which\nwould cause an error since mixing promise and callback semantics is not valid.
\nconst w = new Writable({\n async final(callback) {\n await someOp();\n callback();\n },\n});\n",
"displayName": "DEP0157: Thenable support in streams"
},
{
"textRaw": "DEP0158: `buffer.slice(start, end)`",
"name": "dep0158:_`buffer.slice(start,_end)`",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v17.5.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41596",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nThis method was deprecated because it is not compatible with\nUint8Array.prototype.slice(), which is a superclass of Buffer.
Use buffer.subarray which does the same thing instead.
Type: End-of-Life
\nThis error code was removed due to adding more confusion to\nthe errors used for value type validation.
", "displayName": "DEP0159: `ERR_INVALID_CALLBACK`" }, { "textRaw": "DEP0160: `process.on('multipleResolves', handler)`", "name": "dep0160:_`process.on('multipleresolves',_handler)`", "type": "module", "meta": { "changes": [ { "version": "v25.0.0", "pr-url": "https://github.com/nodejs/node/pull/58707", "description": "End-of-Life." }, { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41896", "description": "Runtime deprecation." }, { "version": [ "v17.6.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/41872", "description": "Documentation-only deprecation." } ] }, "desc": "Type: End-of-Life
\nThis event was deprecated and removed because it did not work with V8 promise\ncombinators which diminished its usefulness.
", "displayName": "DEP0160: `process.on('multipleResolves', handler)`" }, { "textRaw": "DEP0161: `process._getActiveRequests()` and `process._getActiveHandles()`", "name": "dep0161:_`process._getactiverequests()`_and_`process._getactivehandles()`", "type": "module", "meta": { "changes": [ { "version": [ "v17.6.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/41587", "description": "Documentation-only deprecation." } ] }, "desc": "Type: Documentation-only
\nThe process._getActiveHandles() and process._getActiveRequests()\nfunctions are not intended for public use and can be removed in future\nreleases.
Use process.getActiveResourcesInfo() to get a list of types of active\nresources and not the actual references.
Type: End-of-Life
\nImplicit coercion of objects with own toString property, passed as second\nparameter in fs.write(), fs.writeFile(), fs.appendFile(),\nfs.writeFileSync(), and fs.appendFileSync() is deprecated.\nConvert them to primitive strings.
Type: Deprecation revoked
\nThese methods were deprecated because their use could leave the channel object\nvulnerable to being garbage-collected if not strongly referenced by the user.\nThe deprecation was revoked because channel objects are now resistant to\ngarbage collection when the channel has active subscribers.
", "displayName": "DEP0163: `channel.subscribe(onMessage)`, `channel.unsubscribe(onMessage)`" }, { "textRaw": "DEP0164: `process.exit(code)`, `process.exitCode` coercion to integer", "name": "dep0164:_`process.exit(code)`,_`process.exitcode`_coercion_to_integer", "type": "module", "meta": { "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/43716", "description": "End-of-Life." }, { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44711", "description": "Runtime deprecation." }, { "version": [ "v18.10.0", "v16.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/44714", "description": "Documentation-only deprecation of `process.exitCode` integer coercion." }, { "version": [ "v18.7.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/43738", "description": "Documentation-only deprecation of `process.exit(code)` integer coercion." } ] }, "desc": "Type: End-of-Life
\nValues other than undefined, null, integer numbers, and integer strings\n(e.g., '1') are deprecated as value for the code parameter in\nprocess.exit() and as value to assign to process.exitCode.
Type: End-of-Life
\nThe --trace-atomics-wait flag has been removed because\nit uses the V8 hook SetAtomicsWaitCallback,\nthat will be removed in a future V8 release.
Type: Runtime
\nPackage imports and exports targets mapping into paths including a double slash\n(of \"/\" or \"\\\") are deprecated and will fail with a resolution validation\nerror in a future release. This same deprecation also applies to pattern matches\nstarting or ending in a slash.
", "displayName": "DEP0166: Double slashes in imports and exports targets" }, { "textRaw": "DEP0167: Weak `DiffieHellmanGroup` instances (`modp1`, `modp2`, `modp5`)", "name": "dep0167:_weak_`diffiehellmangroup`_instances_(`modp1`,_`modp2`,_`modp5`)", "type": "module", "meta": { "changes": [ { "version": [ "v18.10.0", "v16.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/44588", "description": "Documentation-only deprecation." } ] }, "desc": "Type: Documentation-only
\nThe well-known MODP groups modp1, modp2, and modp5 are deprecated because\nthey are not secure against practical attacks. See RFC 8247 Section 2.4 for\ndetails.
These groups might be removed in future versions of Node.js. Applications that\nrely on these groups should evaluate using stronger MODP groups instead.
", "displayName": "DEP0167: Weak `DiffieHellmanGroup` instances (`modp1`, `modp2`, `modp5`)" }, { "textRaw": "DEP0168: Unhandled exception in Node-API callbacks", "name": "dep0168:_unhandled_exception_in_node-api_callbacks", "type": "module", "meta": { "changes": [ { "version": [ "v18.3.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/36510", "description": "Runtime deprecation." } ] }, "desc": "Type: Runtime
\nThe implicit suppression of uncaught exceptions in Node-API callbacks is now\ndeprecated.
\nSet the flag --force-node-api-uncaught-exceptions-policy to force Node.js\nto emit an 'uncaughtException' event if the exception is not handled in\nNode-API callbacks.
Type: Application (non-node_modules code only)
url.parse() behavior is not standardized and prone to errors that\nhave security implications. Use the WHATWG URL API instead. CVEs are not\nissued for url.parse() vulnerabilities.
Passing a string argument to url.format() invokes url.parse()\ninternally, and is therefore also covered by this deprecation.
Type: End-of-Life
\nurl.parse() used to accept URLs with ports that are not numbers. This\nbehavior might result in host name spoofing with unexpected input. These URLs\nwill throw an error (which the WHATWG URL API also does).
Type: Documentation-only
\nIn a future version of Node.js, message.headers,\nmessage.headersDistinct, message.trailers, and\nmessage.trailersDistinct will be read-only.
Type: End-of-Life
\nOlder versions of Node.js would add the asyncResource when a function is\nbound to an AsyncResource. It no longer does.
Type: End-of-Life
\nThe assert.CallTracker API has been removed.
Type: Runtime
\nCalling util.promisify on a function that returns a Promise will ignore\nthe result of said promise, which can lead to unhandled promise rejections.
Type: Documentation-only
\nThe util.toUSVString() API is deprecated. Please use\nString.prototype.toWellFormed instead.
Type: End-of-Life
\nF_OK, R_OK, W_OK and X_OK getters exposed directly on node:fs were\nremoved. Get them from fs.constants or fs.promises.constants instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/fs-access-mode-constants\n",
"displayName": "DEP0176: `fs.F_OK`, `fs.R_OK`, `fs.W_OK`, `fs.X_OK`"
},
{
"textRaw": "DEP0177: `util.types.isWebAssemblyCompiledModule`",
"name": "dep0177:_`util.types.iswebassemblycompiledmodule`",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v21.7.0",
"v20.12.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51442",
"description": "End-of-Life."
},
{
"version": [
"v21.3.0",
"v20.11.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50486",
"description": "A deprecation code has been assigned."
},
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/32116",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: End-of-Life
\nThe util.types.isWebAssemblyCompiledModule API has been removed.\nPlease use value instanceof WebAssembly.Module instead.
Type: End-of-Life
\nThe dirent.path property has been removed due to its lack of consistency across\nrelease lines. Please use dirent.parentPath instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/dirent-path-to-parent-path\n",
"displayName": "DEP0178: `dirent.path`"
},
{
"textRaw": "DEP0179: `Hash` constructor",
"name": "dep0179:_`hash`_constructor",
"type": "module",
"meta": {
"changes": [
{
"version": "v22.0.0",
"pr-url": "https://github.com/nodejs/node/pull/51880",
"description": "Runtime deprecation."
},
{
"version": [
"v21.5.0",
"v20.12.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51077",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Runtime
\nCalling Hash class directly with Hash() or new Hash() is\ndeprecated due to being internals, not intended for public use.\nPlease use the crypto.createHash() method to create Hash instances.
Type: Runtime
\nCalling fs.Stats class directly with Stats() or new Stats() is\ndeprecated due to being internals, not intended for public use.
Type: Runtime
\nCalling Hmac class directly with Hmac() or new Hmac() is\ndeprecated due to being internals, not intended for public use.\nPlease use the crypto.createHmac() method to create Hmac instances.
Type: Runtime
\nApplications that intend to use authentication tags that are shorter than the\ndefault authentication tag length must set the authTagLength option of the\ncrypto.createDecipheriv() function to the appropriate length.
For ciphers in GCM mode, the decipher.setAuthTag() function accepts\nauthentication tags of any valid length (see DEP0090). This behavior\nis deprecated to better align with recommendations per NIST SP 800-38D.
Type: Documentation-only
\nOpenSSL 3 has deprecated support for custom engines with a recommendation to\nswitch to its new provider model. The clientCertEngine option for\nhttps.request(), tls.createSecureContext(), and tls.createServer();\nthe privateKeyEngine and privateKeyIdentifier for tls.createSecureContext();\nand crypto.setEngine() all depend on this functionality from OpenSSL.
Type: Runtime
\nInstantiating classes without the new qualifier exported by the node:zlib module is deprecated.\nIt is recommended to use the new qualifier instead. This applies to all Zlib classes, such as Deflate,\nDeflateRaw, Gunzip, Inflate, InflateRaw, Unzip, and Zlib.
Type: End-of-Life
\nInstantiating classes without the new qualifier exported by the node:repl module is deprecated.\nThe new qualifier must be used instead. This applies to all REPL classes, including\nREPLServer and Recoverable.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/repl-classes-with-new\n",
"displayName": "DEP0185: Instantiating `node:repl` classes without `new`"
},
{
"textRaw": "DEP0187: Passing invalid argument types to `fs.existsSync`",
"name": "dep0187:_passing_invalid_argument_types_to_`fs.existssync`",
"type": "module",
"meta": {
"changes": [
{
"version": "v24.0.0",
"pr-url": "https://github.com/nodejs/node/pull/55753",
"description": "Runtime deprecation."
},
{
"version": [
"v23.4.0",
"v22.13.0",
"v20.19.3"
],
"pr-url": "https://github.com/nodejs/node/pull/55892",
"description": "Documentation-only."
}
]
},
"desc": "Type: Runtime
\nPassing non-supported argument types is deprecated and, instead of returning false,\nwill throw an error in a future version.
Type: Documentation-only
\nThese properties are unconditionally true. Any checks based on these properties are redundant.
Type: Documentation-only
\nprocess.features.tls_alpn, process.features.tls_ocsp, and process.features.tls_sni are\ndeprecated, as their values are guaranteed to be identical to that of process.features.tls.
Type: Runtime
\nWhen an args array is passed to child_process.execFile or child_process.spawn with the option\n{ shell: true }, the values are not escaped, only space-separated, which can lead to shell injection.
Type: Documentation-only (supports --pending-deprecation)
The node:repl module exports a builtinModules property that contains an array\nof built-in modules. This was incomplete and matched the already deprecated\nrepl._builtinLibs (DEP0142) instead it's better to rely\nupon require('node:module').builtinModules.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/repl-builtin-modules\n",
"displayName": "DEP0191: `repl.builtinModules`"
},
{
"textRaw": "DEP0192: `require('node:_tls_common')` and `require('node:_tls_wrap')`",
"name": "dep0192:_`require('node:_tls_common')`_and_`require('node:_tls_wrap')`",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v24.2.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57643",
"description": "Runtime deprecation."
}
]
},
"desc": "Type: Runtime
\nThe node:_tls_common and node:_tls_wrap modules are deprecated as they should be considered\nan internal nodejs implementation rather than a public facing API, use node:tls instead.
Type: Runtime
\nThe node:_stream_duplex, node:_stream_passthrough, node:_stream_readable, node:_stream_transform,\nnode:_stream_wrap and node:_stream_writable modules are deprecated as they should be considered\nan internal nodejs implementation rather than a public facing API, use node:stream instead.
Type: End-of-Life
\nThe support for priority signaling has been removed following its deprecation in the RFC 9113.
", "displayName": "DEP0194: HTTP/2 priority signaling" }, { "textRaw": "DEP0195: Instantiating `node:http` classes without `new`", "name": "dep0195:_instantiating_`node:http`_classes_without_`new`", "type": "module", "meta": { "changes": [ { "version": [ "v24.2.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/58518", "description": "Documentation-only deprecation." } ] }, "desc": "Type: Documentation-only
\nInstantiating classes without the new qualifier exported by the node:http module is deprecated.\nIt is recommended to use the new qualifier instead. This applies to all http classes, such as\nOutgoingMessage, IncomingMessage, ServerResponse and ClientRequest.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/http-classes-with-new\n",
"displayName": "DEP0195: Instantiating `node:http` classes without `new`"
},
{
"textRaw": "DEP0196: Calling `node:child_process` functions with `options.shell` as an empty string",
"name": "dep0196:_calling_`node:child_process`_functions_with_`options.shell`_as_an_empty_string",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v24.2.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/58564",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nCalling the process-spawning functions with { shell: '' } is almost certainly\nunintentional, and can cause aberrant behavior.
To make child_process.execFile or child_process.spawn invoke the\ndefault shell, use { shell: true }. If the intention is not to invoke a shell\n(default behavior), either omit the shell option, or set it to false or a\nnullish value.
To make child_process.exec invoke the default shell, either omit the\nshell option, or set it to a nullish value. If the intention is not to invoke\na shell, use child_process.execFile instead.
Type: Documentation-only
\nThe util.types.isNativeError API is deprecated. Please use Error.isError instead.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/types-is-native-error\n",
"displayName": "DEP0197: `util.types.isNativeError()`"
},
{
"textRaw": "DEP0198: Creating SHAKE-128 and SHAKE-256 digests without an explicit `options.outputLength`",
"name": "dep0198:_creating_shake-128_and_shake-256_digests_without_an_explicit_`options.outputlength`",
"type": "module",
"meta": {
"changes": [
{
"version": "v25.0.0",
"pr-url": "https://github.com/nodejs/node/pull/59008",
"description": "Runtime deprecation."
},
{
"version": [
"v24.4.0",
"v22.18.0",
"v20.19.5"
],
"pr-url": "https://github.com/nodejs/node/pull/58942",
"description": "Documentation-only deprecation with support for `--pending-deprecation`."
}
]
},
"desc": "Type: Runtime
\nCreating SHAKE-128 and SHAKE-256 digests without an explicit options.outputLength is deprecated.
Type: Documentation-only
\nThe node:_http_agent, node:_http_client, node:_http_common, node:_http_incoming,\nnode:_http_outgoing and node:_http_server modules are deprecated as they should be considered\nan internal nodejs implementation rather than a public facing API, use node:http instead.
Type: Documentation-only
\nAllowing a fs.Dir object to be closed on garbage collection is\ndeprecated. In the future, doing so might result in a thrown error that will\nterminate the process.
Please ensure that all fs.Dir objects are explicitly closed using\nDir.prototype.close() or using keyword:
import { opendir } from 'node:fs/promises';\n\n{\n await using dir = await opendir('/async/disposable/directory');\n} // Closed by dir[Symbol.asyncDispose]()\n\n{\n using dir = await opendir('/sync/disposable/directory');\n} // Closed by dir[Symbol.dispose]()\n\n{\n const dir = await opendir('/unconditionally/iterated/directory');\n for await (const entry of dir) {\n // process an entry\n } // Closed by iterator\n}\n\n{\n let dir;\n try {\n dir = await opendir('/legacy/closeable/directory');\n } finally {\n await dir?.close();\n }\n}\n",
"displayName": "DEP0200: Closing fs.Dir on garbage collection"
},
{
"textRaw": "DEP0201: Passing `options.type` to `Duplex.toWeb()`",
"name": "dep0201:_passing_`options.type`_to_`duplex.toweb()`",
"type": "module",
"meta": {
"changes": [
{
"version": "v25.7.0",
"pr-url": "https://github.com/nodejs/node/pull/61632",
"description": "Documentation-only deprecation."
}
]
},
"desc": "Type: Documentation-only
\nPassing the type option to Duplex.toWeb() is deprecated. To specify the\ntype of the readable half of the constructed readable-writable pair, use the\nreadableType option instead.
Type: Documentation-only
\nThe Http1IncomingMessage and Http1ServerResponse options of\nhttp2.createServer() and http2.createSecureServer() are\ndeprecated. Use http1Options.IncomingMessage and\nhttp1Options.ServerResponse instead.
// Deprecated\nconst server = http2.createSecureServer({\n allowHTTP1: true,\n Http1IncomingMessage: MyIncomingMessage,\n Http1ServerResponse: MyServerResponse,\n});\n\n// Use this instead\nconst server = http2.createSecureServer({\n allowHTTP1: true,\n http1Options: {\n IncomingMessage: MyIncomingMessage,\n ServerResponse: MyServerResponse,\n },\n});\n",
"displayName": "DEP0202: `Http1IncomingMessage` and `Http1ServerResponse` options of HTTP/2 servers"
}
],
"displayName": "List of deprecated APIs"
}
],
"source": "doc/api/deprecations.md"
},
{
"textRaw": "Errors",
"name": "Errors",
"introduced_in": "v4.0.0",
"type": "misc",
"desc": "Applications running in Node.js will generally experience the following\ncategories of errors:
\n<EvalError>, <SyntaxError>, <RangeError>,\n<ReferenceError>, <TypeError>, and <URIError>.DOMExceptions.AssertionErrors are a special class of error that can be triggered when\nNode.js detects an exceptional logic violation that should never occur. These\nare raised typically by the node:assert module.All JavaScript and system errors raised by Node.js inherit from, or are\ninstances of, the standard JavaScript <Error> class and are guaranteed\nto provide at least the properties available on that class.
The error.message property of errors raised by Node.js may be changed in\nany versions. Use error.code to identify an error instead. For a\nDOMException, use domException.name to identify its type.
Node.js supports several mechanisms for propagating and handling errors that\noccur while an application is running. How these errors are reported and\nhandled depends entirely on the type of Error and the style of the API that is\ncalled.
All JavaScript errors are handled as exceptions that immediately generate\nand throw an error using the standard JavaScript throw mechanism. These\nare handled using the try…catch construct provided by the\nJavaScript language.
// Throws with a ReferenceError because z is not defined.\ntry {\n const m = 1;\n const n = m + z;\n} catch (err) {\n // Handle the error here.\n}\n\nAny use of the JavaScript throw mechanism will raise an exception that\nmust be handled or the Node.js process will exit immediately.
With few exceptions, Synchronous APIs (any blocking method that does not\nreturn a <Promise> nor accept a callback function, such as\nfs.readFileSync), will use throw to report errors.
Errors that occur within Asynchronous APIs may be reported in multiple ways:
\nSome asynchronous methods returns a <Promise>, you should always take into\naccount that it might be rejected. See --unhandled-rejections flag for\nhow the process will react to an unhandled promise rejection.
const fs = require('node:fs/promises');\n\n(async () => {\n let data;\n try {\n data = await fs.readFile('a file that does not exist');\n } catch (err) {\n console.error('There was an error reading the file!', err);\n return;\n }\n // Otherwise handle the data\n})();\n\nMost asynchronous methods that accept a callback function will accept an\nError object passed as the first argument to that function. If that first\nargument is not null and is an instance of Error, then an error occurred\nthat should be handled.
const fs = require('node:fs');\nfs.readFile('a file that does not exist', (err, data) => {\n if (err) {\n console.error('There was an error reading the file!', err);\n return;\n }\n // Otherwise handle the data\n});\n\nWhen an asynchronous method is called on an object that is an\nEventEmitter, errors can be routed to that object's 'error' event.
const net = require('node:net');\nconst connection = net.connect('localhost');\n\n// Adding an 'error' event handler to a stream:\nconnection.on('error', (err) => {\n // If the connection is reset by the server, or if it can't\n // connect at all, or on any sort of error encountered by\n // the connection, the error will be sent here.\n console.error(err);\n});\n\nconnection.pipe(process.stdout);\n\nA handful of typically asynchronous methods in the Node.js API may still\nuse the throw mechanism to raise exceptions that must be handled using\ntry…catch. There is no comprehensive list of such methods; please\nrefer to the documentation of each method to determine the appropriate\nerror handling mechanism required.
The use of the 'error' event mechanism is most common for stream-based\nand event emitter-based APIs, which themselves represent a series of\nasynchronous operations over time (as opposed to a single operation that may\npass or fail).
For all EventEmitter objects, if an 'error' event handler is not\nprovided, the error will be thrown, causing the Node.js process to report an\nuncaught exception and crash unless either: a handler has been registered for\nthe 'uncaughtException' event, or the deprecated node:domain\nmodule is used.
const EventEmitter = require('node:events');\nconst ee = new EventEmitter();\n\nsetImmediate(() => {\n // This will crash the process because no 'error' event\n // handler has been added.\n ee.emit('error', new Error('This will crash'));\n});\n\nErrors generated in this way cannot be intercepted using try…catch as\nthey are thrown after the calling code has already exited.
Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.
" }, { "textRaw": "Exceptions vs. errors", "name": "Exceptions vs. errors", "type": "misc", "desc": "A JavaScript exception is a value that is thrown as a result of an invalid\noperation or as the target of a throw statement. While it is not required\nthat these values are instances of Error or classes which inherit from\nError, all exceptions thrown by Node.js or the JavaScript runtime will be\ninstances of Error.
Some exceptions are unrecoverable at the JavaScript layer. Such exceptions\nwill always cause the Node.js process to crash. Examples include assert()\nchecks or abort() calls in the C++ layer.
Errors originating in crypto or tls are of class Error, and in addition to\nthe standard .code and .message properties, may have some additional\nOpenSSL-specific properties.
An array of errors that can give context to where in the OpenSSL library an\nerror originates from.
" }, { "textRaw": "`error.function`", "name": "function", "type": "property", "desc": "The OpenSSL function the error originates in.
" }, { "textRaw": "`error.library`", "name": "library", "type": "property", "desc": "The OpenSSL library the error originates in.
" }, { "textRaw": "`error.reason`", "name": "reason", "type": "property", "desc": "A human-readable string describing the reason for the error.
\n" } ], "displayName": "OpenSSL errors" }, { "textRaw": "Node.js error codes", "name": "node.js_error_codes", "type": "misc", "desc": "", "modules": [ { "textRaw": "`ABORT_ERR`", "name": "`abort_err`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Used when an operation has been aborted (typically using an AbortController).
APIs not using AbortSignals typically do not raise an error with this code.
This code does not use the regular ERR_* convention Node.js errors use in\norder to be compatible with the web platform's AbortError.
A special type of error that is triggered whenever Node.js tries to get access\nto a resource restricted by the Permission Model.
\n", "displayName": "`ERR_ACCESS_DENIED`" }, { "textRaw": "`ERR_AMBIGUOUS_ARGUMENT`", "name": "`err_ambiguous_argument`", "type": "module", "desc": "A function argument is being used in a way that suggests that the function\nsignature may be misunderstood. This is thrown by the node:assert module when\nthe message parameter in assert.throws(block, message) matches the error\nmessage thrown by block because that usage suggests that the user believes\nmessage is the expected message rather than the message the AssertionError\nwill display if block does not throw.
An iterable argument (i.e. a value that works with for...of loops) was\nrequired, but not provided to a Node.js API.
A special type of error that can be triggered whenever Node.js detects an\nexceptional logic violation that should never occur. These are raised typically\nby the node:assert module.
An attempt was made to register something that is not a function as an\nAsyncHooks callback.
An operation related to module loading is customized by an asynchronous loader\nhook that never settled the promise before the loader thread exits.
\n", "displayName": "`ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED`" }, { "textRaw": "`ERR_ASYNC_TYPE`", "name": "`err_async_type`", "type": "module", "desc": "The type of an asynchronous resource was invalid. Users are also able\nto define their own types if using the public embedder API.
\n", "displayName": "`ERR_ASYNC_TYPE`" }, { "textRaw": "`ERR_BROTLI_COMPRESSION_FAILED`", "name": "`err_brotli_compression_failed`", "type": "module", "desc": "Data passed to a Brotli stream was not successfully compressed.
\n", "displayName": "`ERR_BROTLI_COMPRESSION_FAILED`" }, { "textRaw": "`ERR_BROTLI_INVALID_PARAM`", "name": "`err_brotli_invalid_param`", "type": "module", "desc": "An invalid parameter key was passed during construction of a Brotli stream.
\n", "displayName": "`ERR_BROTLI_INVALID_PARAM`" }, { "textRaw": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`", "name": "`err_buffer_context_not_available`", "type": "module", "desc": "An attempt was made to create a Node.js Buffer instance from addon or embedder\ncode, while in a JS engine Context that is not associated with a Node.js\ninstance. The data passed to the Buffer method will have been released\nby the time the method returns.
When encountering this error, a possible alternative to creating a Buffer\ninstance is to create a normal Uint8Array, which only differs in the\nprototype of the resulting object. Uint8Arrays are generally accepted in all\nNode.js core APIs where Buffers are; they are available in all Contexts.
An operation outside the bounds of a Buffer was attempted.
An attempt has been made to create a Buffer larger than the maximum allowed\nsize.
Node.js was unable to watch for the SIGINT signal.
A child process was closed before the parent received a reply.
\n", "displayName": "`ERR_CHILD_CLOSED_BEFORE_REPLY`" }, { "textRaw": "`ERR_CHILD_PROCESS_IPC_REQUIRED`", "name": "`err_child_process_ipc_required`", "type": "module", "desc": "Used when a child process is being forked without specifying an IPC channel.
\n", "displayName": "`ERR_CHILD_PROCESS_IPC_REQUIRED`" }, { "textRaw": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`", "name": "`err_child_process_stdio_maxbuffer`", "type": "module", "desc": "Used when the main process is trying to read data from the child process's\nSTDERR/STDOUT, and the data's length is longer than the maxBuffer option.
There was an attempt to use a MessagePort instance in a closed\nstate, usually after .close() has been called.
Console was instantiated without stdout stream, or Console has a\nnon-writable stdout or stderr stream.
A class constructor was called that is not callable.
\n", "displayName": "`ERR_CONSTRUCT_CALL_INVALID`" }, { "textRaw": "`ERR_CONSTRUCT_CALL_REQUIRED`", "name": "`err_construct_call_required`", "type": "module", "desc": "A constructor for a class was called without new.
The vm context passed into the API is not yet initialized. This could happen\nwhen an error occurs (and is caught) during the creation of the\ncontext, for example, when the allocation fails or the maximum call stack\nsize is reached when the context is created.
\n", "displayName": "`ERR_CONTEXT_NOT_INITIALIZED`" }, { "textRaw": "`ERR_CPU_PROFILE_ALREADY_STARTED`", "name": "`err_cpu_profile_already_started`", "type": "module", "meta": { "added": [ "v24.8.0", "v22.20.0" ], "changes": [] }, "desc": "The CPU profile with the given name is already started.
\n", "displayName": "`ERR_CPU_PROFILE_ALREADY_STARTED`" }, { "textRaw": "`ERR_CPU_PROFILE_NOT_STARTED`", "name": "`err_cpu_profile_not_started`", "type": "module", "meta": { "added": [ "v24.8.0", "v22.20.0" ], "changes": [] }, "desc": "The CPU profile with the given name is not started.
\n", "displayName": "`ERR_CPU_PROFILE_NOT_STARTED`" }, { "textRaw": "`ERR_CPU_PROFILE_TOO_MANY`", "name": "`err_cpu_profile_too_many`", "type": "module", "meta": { "added": [ "v24.8.0", "v22.20.0" ], "changes": [] }, "desc": "There are too many CPU profiles being collected.
\n", "displayName": "`ERR_CPU_PROFILE_TOO_MANY`" }, { "textRaw": "`ERR_CRYPTO_ARGON2_NOT_SUPPORTED`", "name": "`err_crypto_argon2_not_supported`", "type": "module", "desc": "Argon2 is not supported by the current version of OpenSSL being used.
\n", "displayName": "`ERR_CRYPTO_ARGON2_NOT_SUPPORTED`" }, { "textRaw": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`", "name": "`err_crypto_custom_engine_not_supported`", "type": "module", "desc": "An OpenSSL engine was requested (for example, through the clientCertEngine or\nprivateKeyEngine TLS options) that is not supported by the version of OpenSSL\nbeing used, likely due to the compile-time flag OPENSSL_NO_ENGINE.
An invalid value for the format argument was passed to the crypto.ECDH()\nclass getPublicKey() method.
An invalid value for the key argument has been passed to the\ncrypto.ECDH() class computeSecret() method. It means that the public\nkey lies outside of the elliptic curve.
An invalid crypto engine identifier was passed to\nrequire('node:crypto').setEngine().
The --force-fips command-line argument was used but there was an attempt\nto enable or disable FIPS mode in the node:crypto module.
An attempt was made to enable or disable FIPS mode, but FIPS mode was not\navailable.
\n", "displayName": "`ERR_CRYPTO_FIPS_UNAVAILABLE`" }, { "textRaw": "`ERR_CRYPTO_HASH_FINALIZED`", "name": "`err_crypto_hash_finalized`", "type": "module", "desc": "hash.digest() was called multiple times. The hash.digest() method must\nbe called no more than one time per instance of a Hash object.
hash.update() failed for any reason. This should rarely, if ever, happen.
The given crypto keys are incompatible with the attempted operation.
\n", "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY`" }, { "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`", "name": "`err_crypto_incompatible_key_options`", "type": "module", "desc": "The selected public or private key encoding is incompatible with other options.
\n", "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`" }, { "textRaw": "`ERR_CRYPTO_INITIALIZATION_FAILED`", "name": "`err_crypto_initialization_failed`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Initialization of the crypto subsystem failed.
\n", "displayName": "`ERR_CRYPTO_INITIALIZATION_FAILED`" }, { "textRaw": "`ERR_CRYPTO_INVALID_AUTH_TAG`", "name": "`err_crypto_invalid_auth_tag`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid authentication tag was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_AUTH_TAG`" }, { "textRaw": "`ERR_CRYPTO_INVALID_COUNTER`", "name": "`err_crypto_invalid_counter`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid counter was provided for a counter-mode cipher.
\n", "displayName": "`ERR_CRYPTO_INVALID_COUNTER`" }, { "textRaw": "`ERR_CRYPTO_INVALID_CURVE`", "name": "`err_crypto_invalid_curve`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid elliptic-curve was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_CURVE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_DIGEST`", "name": "`err_crypto_invalid_digest`", "type": "module", "desc": "An invalid crypto digest algorithm was specified.
\n", "displayName": "`ERR_CRYPTO_INVALID_DIGEST`" }, { "textRaw": "`ERR_CRYPTO_INVALID_IV`", "name": "`err_crypto_invalid_iv`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid initialization vector was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_IV`" }, { "textRaw": "`ERR_CRYPTO_INVALID_JWK`", "name": "`err_crypto_invalid_jwk`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid JSON Web Key was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_JWK`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYLEN`", "name": "`err_crypto_invalid_keylen`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid key length was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_KEYLEN`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYPAIR`", "name": "`err_crypto_invalid_keypair`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid key pair was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_KEYPAIR`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYTYPE`", "name": "`err_crypto_invalid_keytype`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid key type was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_KEYTYPE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`", "name": "`err_crypto_invalid_key_object_type`", "type": "module", "desc": "The given crypto key object's type is invalid for the attempted operation.
\n", "displayName": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_MESSAGELEN`", "name": "`err_crypto_invalid_messagelen`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An invalid message length was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_MESSAGELEN`" }, { "textRaw": "`ERR_CRYPTO_INVALID_SCRYPT_PARAMS`", "name": "`err_crypto_invalid_scrypt_params`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "One or more crypto.scrypt() or crypto.scryptSync() parameters are\noutside their legal range.
A crypto method was used on an object that was in an invalid state. For\ninstance, calling cipher.getAuthTag() before calling cipher.final().
An invalid authentication tag length was provided.
\n", "displayName": "`ERR_CRYPTO_INVALID_TAG_LENGTH`" }, { "textRaw": "`ERR_CRYPTO_JOB_INIT_FAILED`", "name": "`err_crypto_job_init_failed`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Initialization of an asynchronous crypto operation failed.
\n", "displayName": "`ERR_CRYPTO_JOB_INIT_FAILED`" }, { "textRaw": "`ERR_CRYPTO_JWK_UNSUPPORTED_CURVE`", "name": "`err_crypto_jwk_unsupported_curve`", "type": "module", "desc": "Key's Elliptic Curve is not registered for use in the\nJSON Web Key Elliptic Curve Registry.
\n", "displayName": "`ERR_CRYPTO_JWK_UNSUPPORTED_CURVE`" }, { "textRaw": "`ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE`", "name": "`err_crypto_jwk_unsupported_key_type`", "type": "module", "desc": "Key's Asymmetric Key Type is not registered for use in the\nJSON Web Key Types Registry.
\n", "displayName": "`ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE`" }, { "textRaw": "`ERR_CRYPTO_KEM_NOT_SUPPORTED`", "name": "`err_crypto_kem_not_supported`", "type": "module", "meta": { "added": [ "v24.7.0" ], "changes": [] }, "desc": "Attempted to use KEM operations while Node.js was not compiled with\nOpenSSL with KEM support.
\n", "displayName": "`ERR_CRYPTO_KEM_NOT_SUPPORTED`" }, { "textRaw": "`ERR_CRYPTO_OPERATION_FAILED`", "name": "`err_crypto_operation_failed`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "A crypto operation failed for an otherwise unspecified reason.
\n", "displayName": "`ERR_CRYPTO_OPERATION_FAILED`" }, { "textRaw": "`ERR_CRYPTO_PBKDF2_ERROR`", "name": "`err_crypto_pbkdf2_error`", "type": "module", "desc": "The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide\nmore details and therefore neither does Node.js.
\n", "displayName": "`ERR_CRYPTO_PBKDF2_ERROR`" }, { "textRaw": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`", "name": "`err_crypto_scrypt_not_supported`", "type": "module", "desc": "Node.js was compiled without scrypt support. Not possible with the official\nrelease binaries but can happen with custom builds, including distro builds.
A signing key was not provided to the sign.sign() method.
crypto.timingSafeEqual() was called with Buffer, TypedArray, or\nDataView arguments of different lengths.
An unknown cipher was specified.
\n", "displayName": "`ERR_CRYPTO_UNKNOWN_CIPHER`" }, { "textRaw": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`", "name": "`err_crypto_unknown_dh_group`", "type": "module", "desc": "An unknown Diffie-Hellman group name was given. See\ncrypto.getDiffieHellman() for a list of valid group names.
An attempt to invoke an unsupported crypto operation was made.
\n", "displayName": "`ERR_CRYPTO_UNSUPPORTED_OPERATION`" }, { "textRaw": "`ERR_DEBUGGER_ERROR`", "name": "`err_debugger_error`", "type": "module", "meta": { "added": [ "v16.4.0", "v14.17.4" ], "changes": [] }, "desc": "An error occurred with the debugger.
\n", "displayName": "`ERR_DEBUGGER_ERROR`" }, { "textRaw": "`ERR_DEBUGGER_STARTUP_ERROR`", "name": "`err_debugger_startup_error`", "type": "module", "meta": { "added": [ "v16.4.0", "v14.17.4" ], "changes": [] }, "desc": "The debugger timed out waiting for the required host/port to be free.
\n", "displayName": "`ERR_DEBUGGER_STARTUP_ERROR`" }, { "textRaw": "`ERR_DIR_CLOSED`", "name": "`err_dir_closed`", "type": "module", "desc": "The fs.Dir was previously closed.
A synchronous read or close call was attempted on an fs.Dir which has\nongoing asynchronous operations.
Loading native addons has been disabled using --no-addons.
A call to process.dlopen() failed.
c-ares failed to set the DNS server.
The node:domain module was not usable since it could not establish the\nrequired error handling hooks, because\nprocess.setUncaughtExceptionCaptureCallback() had been called at an\nearlier point in time.
process.setUncaughtExceptionCaptureCallback() could not be called\nbecause the node:domain module has been loaded at an earlier point in time.
The stack trace is extended to include the point in time at which the\nnode:domain module had been loaded.
v8.startupSnapshot.setDeserializeMainFunction() could not be called\nbecause it had already been called before.
Data provided to TextDecoder() API was invalid according to the encoding\nprovided.
Encoding provided to TextDecoder() API was not one of the\nWHATWG Supported Encodings.
--print cannot be used with ESM input.
Thrown when an attempt is made to recursively dispatch an event on EventTarget.
The JS execution context is not associated with a Node.js environment.\nThis may occur when Node.js is used as an embedded library and some hooks\nfor the JS engine are not set up properly.
\n", "displayName": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`" }, { "textRaw": "`ERR_FALSY_VALUE_REJECTION`", "name": "`err_falsy_value_rejection`", "type": "module", "desc": "A Promise that was callbackified via util.callbackify() was rejected with a\nfalsy value.
Used when a feature that is not available\nto the current platform which is running Node.js is used.
\n", "displayName": "`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`" }, { "textRaw": "`ERR_FS_CP_DIR_TO_NON_DIR`", "name": "`err_fs_cp_dir_to_non_dir`", "type": "module", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "desc": "An attempt was made to copy a directory to a non-directory (file, symlink,\netc.) using fs.cp().
An attempt was made to copy over a file that already existed with\nfs.cp(), with the force and errorOnExist set to true.
When using fs.cp(), src or dest pointed to an invalid path.
An attempt was made to copy a named pipe with fs.cp().
An attempt was made to copy a non-directory (file, symlink, etc.) to a directory\nusing fs.cp().
An attempt was made to copy to a socket with fs.cp().
When using fs.cp(), a symlink in dest pointed to a subdirectory\nof src.
An attempt was made to copy to an unknown file type with fs.cp().
Path is a directory.
\n", "displayName": "`ERR_FS_EISDIR`" }, { "textRaw": "`ERR_FS_FILE_TOO_LARGE`", "name": "`err_fs_file_too_large`", "type": "module", "desc": "An attempt was made to read a file larger than the supported 2 GiB limit for\nfs.readFile(). This is not a limitation of Buffer, but an internal I/O constraint.\nFor handling larger files, consider using fs.createReadStream() to read the\nfile in chunks.
The number of file system events queued without being handled exceeded the size specified in\nmaxQueue in fs.watch().
HTTP/2 ALTSVC frames require a valid origin.
\n", "displayName": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`" }, { "textRaw": "`ERR_HTTP2_ALTSVC_LENGTH`", "name": "`err_http2_altsvc_length`", "type": "module", "desc": "HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.
\n", "displayName": "`ERR_HTTP2_ALTSVC_LENGTH`" }, { "textRaw": "`ERR_HTTP2_CONNECT_AUTHORITY`", "name": "`err_http2_connect_authority`", "type": "module", "desc": "For HTTP/2 requests using the CONNECT method, the :authority pseudo-header\nis required.
For HTTP/2 requests using the CONNECT method, the :path pseudo-header is\nforbidden.
For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is\nforbidden.
A non-specific HTTP/2 error has occurred.
\n", "displayName": "`ERR_HTTP2_ERROR`" }, { "textRaw": "`ERR_HTTP2_GOAWAY_SESSION`", "name": "`err_http2_goaway_session`", "type": "module", "desc": "New HTTP/2 Streams may not be opened after the Http2Session has received a\nGOAWAY frame from the connected peer.
An additional headers was specified after an HTTP/2 response was initiated.
\n", "displayName": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`" }, { "textRaw": "`ERR_HTTP2_HEADERS_SENT`", "name": "`err_http2_headers_sent`", "type": "module", "desc": "An attempt was made to send multiple response headers.
\n", "displayName": "`ERR_HTTP2_HEADERS_SENT`" }, { "textRaw": "`ERR_HTTP2_HEADER_SINGLE_VALUE`", "name": "`err_http2_header_single_value`", "type": "module", "desc": "Multiple values were provided for an HTTP/2 header field that was required to\nhave only a single value.
\n", "displayName": "`ERR_HTTP2_HEADER_SINGLE_VALUE`" }, { "textRaw": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`", "name": "`err_http2_info_status_not_allowed`", "type": "module", "desc": "Informational HTTP status codes (1xx) may not be set as the response status\ncode on HTTP/2 responses.
HTTP/1 connection specific headers are forbidden to be used in HTTP/2\nrequests and responses.
\n", "displayName": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`" }, { "textRaw": "`ERR_HTTP2_INVALID_HEADER_VALUE`", "name": "`err_http2_invalid_header_value`", "type": "module", "desc": "An invalid HTTP/2 header value was specified.
\n", "displayName": "`ERR_HTTP2_INVALID_HEADER_VALUE`" }, { "textRaw": "`ERR_HTTP2_INVALID_INFO_STATUS`", "name": "`err_http2_invalid_info_status`", "type": "module", "desc": "An invalid HTTP informational status code has been specified. Informational\nstatus codes must be an integer between 100 and 199 (inclusive).
HTTP/2 ORIGIN frames require a valid origin.
Input Buffer and Uint8Array instances passed to the\nhttp2.getUnpackedSettings() API must have a length that is a multiple of\nsix.
Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme,\nand :method) may be used.
An action was performed on an Http2Session object that had already been\ndestroyed.
An invalid value has been specified for an HTTP/2 setting.
\n", "displayName": "`ERR_HTTP2_INVALID_SETTING_VALUE`" }, { "textRaw": "`ERR_HTTP2_INVALID_STREAM`", "name": "`err_http2_invalid_stream`", "type": "module", "desc": "An operation was performed on a stream that had already been destroyed.
\n", "displayName": "`ERR_HTTP2_INVALID_STREAM`" }, { "textRaw": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`", "name": "`err_http2_max_pending_settings_ack`", "type": "module", "desc": "Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is\nrequired to send an acknowledgment that it has received and applied the new\nSETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may\nbe sent at any given time. This error code is used when that limit has been\nreached.
An attempt was made to initiate a new push stream from within a push stream.\nNested push streams are not permitted.
\n", "displayName": "`ERR_HTTP2_NESTED_PUSH`" }, { "textRaw": "`ERR_HTTP2_NO_MEM`", "name": "`err_http2_no_mem`", "type": "module", "desc": "Out of memory when using the http2session.setLocalWindowSize(windowSize) API.
An attempt was made to directly manipulate (read, write, pause, resume, etc.) a\nsocket attached to an Http2Session.
HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.
The number of streams created on a single HTTP/2 session reached the maximum\nlimit.
\n", "displayName": "`ERR_HTTP2_OUT_OF_STREAMS`" }, { "textRaw": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`", "name": "`err_http2_payload_forbidden`", "type": "module", "desc": "A message payload was specified for an HTTP response code for which a payload is\nforbidden.
\n", "displayName": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`" }, { "textRaw": "`ERR_HTTP2_PING_CANCEL`", "name": "`err_http2_ping_cancel`", "type": "module", "desc": "An HTTP/2 ping was canceled.
\n", "displayName": "`ERR_HTTP2_PING_CANCEL`" }, { "textRaw": "`ERR_HTTP2_PING_LENGTH`", "name": "`err_http2_ping_length`", "type": "module", "desc": "HTTP/2 ping payloads must be exactly 8 bytes in length.
\n", "displayName": "`ERR_HTTP2_PING_LENGTH`" }, { "textRaw": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`", "name": "`err_http2_pseudoheader_not_allowed`", "type": "module", "desc": "An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header\nkey names that begin with the : prefix.
An attempt was made to create a push stream, which had been disabled by the\nclient.
\n", "displayName": "`ERR_HTTP2_PUSH_DISABLED`" }, { "textRaw": "`ERR_HTTP2_SEND_FILE`", "name": "`err_http2_send_file`", "type": "module", "desc": "An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend a directory.
An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend something other than a regular file, but offset or length options were\nprovided.
The Http2Session closed with a non-zero error code.
The Http2Session settings canceled.
An attempt was made to connect a Http2Session object to a net.Socket or\ntls.TLSSocket that had already been bound to another Http2Session object.
An attempt was made to use the socket property of an Http2Session that\nhas already been closed.
Use of the 101 Informational status code is forbidden in HTTP/2.
An invalid HTTP status code has been specified. Status codes must be an integer\nbetween 100 and 599 (inclusive).
An Http2Stream was destroyed before any data was transmitted to the connected\npeer.
A non-zero error code was been specified in an RST_STREAM frame.
When setting the priority for an HTTP/2 stream, the stream may be marked as\na dependency for a parent stream. This error code is used when an attempt is\nmade to mark a stream and dependent of itself.
\n", "displayName": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`" }, { "textRaw": "`ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS`", "name": "`err_http2_too_many_custom_settings`", "type": "module", "desc": "The number of supported custom settings (10) has been exceeded.
\n", "displayName": "`ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS`" }, { "textRaw": "`ERR_HTTP2_TOO_MANY_INVALID_FRAMES`", "name": "`err_http2_too_many_invalid_frames`", "type": "module", "meta": { "added": [ "v15.14.0" ], "changes": [] }, "desc": "The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,\nas specified through the maxSessionInvalidFrames option, has been exceeded.
Trailing headers have already been sent on the Http2Stream.
The http2stream.sendTrailers() method cannot be called until after the\n'wantTrailers' event is emitted on an Http2Stream object. The\n'wantTrailers' event will only be emitted if the waitForTrailers option\nis set for the Http2Stream.
http2.connect() was passed a URL that uses any protocol other than http: or\nhttps:.
An error is thrown when writing to an HTTP response which does not allow\ncontents.
\n", "displayName": "`ERR_HTTP_BODY_NOT_ALLOWED`" }, { "textRaw": "`ERR_HTTP_CONTENT_LENGTH_MISMATCH`", "name": "`err_http_content_length_mismatch`", "type": "module", "desc": "Response body size doesn't match with the specified content-length header value.
\n", "displayName": "`ERR_HTTP_CONTENT_LENGTH_MISMATCH`" }, { "textRaw": "`ERR_HTTP_HEADERS_SENT`", "name": "`err_http_headers_sent`", "type": "module", "desc": "An attempt was made to add more headers after the headers had already been sent.
\n", "displayName": "`ERR_HTTP_HEADERS_SENT`" }, { "textRaw": "`ERR_HTTP_INVALID_HEADER_VALUE`", "name": "`err_http_invalid_header_value`", "type": "module", "desc": "An invalid HTTP header value was specified.
\n", "displayName": "`ERR_HTTP_INVALID_HEADER_VALUE`" }, { "textRaw": "`ERR_HTTP_INVALID_STATUS_CODE`", "name": "`err_http_invalid_status_code`", "type": "module", "desc": "Status code was outside the regular status code range (100-999).
\n", "displayName": "`ERR_HTTP_INVALID_STATUS_CODE`" }, { "textRaw": "`ERR_HTTP_REQUEST_TIMEOUT`", "name": "`err_http_request_timeout`", "type": "module", "desc": "The client has not sent the entire request within the allowed time.
\n", "displayName": "`ERR_HTTP_REQUEST_TIMEOUT`" }, { "textRaw": "`ERR_HTTP_SOCKET_ASSIGNED`", "name": "`err_http_socket_assigned`", "type": "module", "desc": "The given ServerResponse was already assigned a socket.
Changing the socket encoding is not allowed per RFC 7230 Section 3.
\n", "displayName": "`ERR_HTTP_SOCKET_ENCODING`" }, { "textRaw": "`ERR_HTTP_TRAILER_INVALID`", "name": "`err_http_trailer_invalid`", "type": "module", "desc": "The Trailer header was set even though the transfer encoding does not support\nthat.
An attempt was made to construct an object using a non-public constructor.
\n", "displayName": "`ERR_ILLEGAL_CONSTRUCTOR`" }, { "textRaw": "`ERR_IMPORT_ATTRIBUTE_MISSING`", "name": "`err_import_attribute_missing`", "type": "module", "meta": { "added": [ "v21.1.0" ], "changes": [] }, "desc": "An import attribute is missing, preventing the specified module to be imported.
\n", "displayName": "`ERR_IMPORT_ATTRIBUTE_MISSING`" }, { "textRaw": "`ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE`", "name": "`err_import_attribute_type_incompatible`", "type": "module", "meta": { "added": [ "v21.1.0" ], "changes": [] }, "desc": "An import type attribute was provided, but the specified module is of a\ndifferent type.
An import attribute is not supported by this version of Node.js.
\n", "displayName": "`ERR_IMPORT_ATTRIBUTE_UNSUPPORTED`" }, { "textRaw": "`ERR_INCOMPATIBLE_OPTION_PAIR`", "name": "`err_incompatible_option_pair`", "type": "module", "desc": "An option pair is incompatible with each other and cannot be used at the same\ntime.
\n", "displayName": "`ERR_INCOMPATIBLE_OPTION_PAIR`" }, { "textRaw": "`ERR_INPUT_TYPE_NOT_ALLOWED`", "name": "`err_input_type_not_allowed`", "type": "module", "desc": "The --input-type flag was used to attempt to execute a file. This flag can\nonly be used with input via --eval, --print, or STDIN.
While using the node:inspector module, an attempt was made to activate the\ninspector when it already started to listen on a port. Use inspector.close()\nbefore activating it on a different address.
While using the node:inspector module, an attempt was made to connect when the\ninspector was already connected.
While using the node:inspector module, an attempt was made to use the\ninspector after the session had already closed.
An error occurred while issuing a command via the node:inspector module.
The inspector is not active when inspector.waitForDebugger() is called.
The node:inspector module is not available for use.
While using the node:inspector module, an attempt was made to use the\ninspector before it was connected.
An API was called on the main thread that can only be used from\nthe worker thread.
\n", "displayName": "`ERR_INSPECTOR_NOT_WORKER`" }, { "textRaw": "`ERR_INTERNAL_ASSERTION`", "name": "`err_internal_assertion`", "type": "module", "desc": "There was a bug in Node.js or incorrect usage of Node.js internals.\nTo fix the error, open an issue at https://github.com/nodejs/node/issues.
\n", "displayName": "`ERR_INTERNAL_ASSERTION`" }, { "textRaw": "`ERR_INVALID_ADDRESS`", "name": "`err_invalid_address`", "type": "module", "desc": "The provided address is not understood by the Node.js API.
\n", "displayName": "`ERR_INVALID_ADDRESS`" }, { "textRaw": "`ERR_INVALID_ADDRESS_FAMILY`", "name": "`err_invalid_address_family`", "type": "module", "desc": "The provided address family is not understood by the Node.js API.
\n", "displayName": "`ERR_INVALID_ADDRESS_FAMILY`" }, { "textRaw": "`ERR_INVALID_ARG_TYPE`", "name": "`err_invalid_arg_type`", "type": "module", "desc": "An argument of the wrong type was passed to a Node.js API.
\n", "displayName": "`ERR_INVALID_ARG_TYPE`" }, { "textRaw": "`ERR_INVALID_ARG_VALUE`", "name": "`err_invalid_arg_value`", "type": "module", "desc": "An invalid or unsupported value was passed for a given argument.
\n", "displayName": "`ERR_INVALID_ARG_VALUE`" }, { "textRaw": "`ERR_INVALID_ASYNC_ID`", "name": "`err_invalid_async_id`", "type": "module", "desc": "An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id\nless than -1 should never happen.
A swap was performed on a Buffer but its size was not compatible with the\noperation.
Invalid characters were detected in headers.
\n", "displayName": "`ERR_INVALID_CHAR`" }, { "textRaw": "`ERR_INVALID_CURSOR_POS`", "name": "`err_invalid_cursor_pos`", "type": "module", "desc": "A cursor on a given stream cannot be moved to a specified row without a\nspecified column.
\n", "displayName": "`ERR_INVALID_CURSOR_POS`" }, { "textRaw": "`ERR_INVALID_FD`", "name": "`err_invalid_fd`", "type": "module", "desc": "A file descriptor ('fd') was not valid (e.g. it was a negative value).
\n", "displayName": "`ERR_INVALID_FD`" }, { "textRaw": "`ERR_INVALID_FD_TYPE`", "name": "`err_invalid_fd_type`", "type": "module", "desc": "A file descriptor ('fd') type was not valid.
\n", "displayName": "`ERR_INVALID_FD_TYPE`" }, { "textRaw": "`ERR_INVALID_FILE_URL_HOST`", "name": "`err_invalid_file_url_host`", "type": "module", "desc": "A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible host. This\nsituation can only occur on Unix-like systems where only localhost or an empty\nhost is supported.
A Node.js API that consumes file: URLs (such as certain functions in the\nfs module) encountered a file URL with an incompatible path. The exact\nsemantics for determining whether a path can be used is platform-dependent.
The thrown error object includes an input property that contains the URL object\nof the invalid file: URL.
An attempt was made to send an unsupported \"handle\" over an IPC communication\nchannel to a child process. See subprocess.send() and process.send()\nfor more information.
An invalid HTTP token was supplied.
\n", "displayName": "`ERR_INVALID_HTTP_TOKEN`" }, { "textRaw": "`ERR_INVALID_IP_ADDRESS`", "name": "`err_invalid_ip_address`", "type": "module", "desc": "An IP address is not valid.
\n", "displayName": "`ERR_INVALID_IP_ADDRESS`" }, { "textRaw": "`ERR_INVALID_MIME_SYNTAX`", "name": "`err_invalid_mime_syntax`", "type": "module", "desc": "The syntax of a MIME is not valid.
\n", "displayName": "`ERR_INVALID_MIME_SYNTAX`" }, { "textRaw": "`ERR_INVALID_MODULE`", "name": "`err_invalid_module`", "type": "module", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "desc": "An attempt was made to load a module that does not exist or was otherwise not\nvalid.
\n", "displayName": "`ERR_INVALID_MODULE`" }, { "textRaw": "`ERR_INVALID_MODULE_SPECIFIER`", "name": "`err_invalid_module_specifier`", "type": "module", "desc": "The imported module string is an invalid URL, package name, or package subpath\nspecifier.
\n", "displayName": "`ERR_INVALID_MODULE_SPECIFIER`" }, { "textRaw": "`ERR_INVALID_OBJECT_DEFINE_PROPERTY`", "name": "`err_invalid_object_define_property`", "type": "module", "desc": "An error occurred while setting an invalid attribute on the property of\nan object.
\n", "displayName": "`ERR_INVALID_OBJECT_DEFINE_PROPERTY`" }, { "textRaw": "`ERR_INVALID_PACKAGE_CONFIG`", "name": "`err_invalid_package_config`", "type": "module", "desc": "An invalid package.json file failed parsing.
The package.json \"exports\" field contains an invalid target mapping\nvalue for the attempted module resolution.
An invalid options.protocol was passed to http.request().
Both breakEvalOnSigint and eval options were set in the REPL config,\nwhich is not supported.
The input may not be used in the REPL. The conditions under which this\nerror is used are described in the REPL documentation.
Thrown in case a function option does not provide a valid value for one of its\nreturned object properties on execution.
\n", "displayName": "`ERR_INVALID_RETURN_PROPERTY`" }, { "textRaw": "`ERR_INVALID_RETURN_PROPERTY_VALUE`", "name": "`err_invalid_return_property_value`", "type": "module", "desc": "Thrown in case a function option does not provide an expected value\ntype for one of its returned object properties on execution.
\n", "displayName": "`ERR_INVALID_RETURN_PROPERTY_VALUE`" }, { "textRaw": "`ERR_INVALID_RETURN_VALUE`", "name": "`err_invalid_return_value`", "type": "module", "desc": "Thrown in case a function option does not return an expected value\ntype on execution, such as when a function is expected to return a promise.
\n", "displayName": "`ERR_INVALID_RETURN_VALUE`" }, { "textRaw": "`ERR_INVALID_STATE`", "name": "`err_invalid_state`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Indicates that an operation cannot be completed due to an invalid state.\nFor instance, an object may have already been destroyed, or may be\nperforming another operation.
\n", "displayName": "`ERR_INVALID_STATE`" }, { "textRaw": "`ERR_INVALID_SYNC_FORK_INPUT`", "name": "`err_invalid_sync_fork_input`", "type": "module", "desc": "A Buffer, TypedArray, DataView, or string was provided as stdio input to\nan asynchronous fork. See the documentation for the child_process module\nfor more information.
A Node.js API function was called with an incompatible this value.
const urlSearchParams = new URLSearchParams('foo=bar&baz=new');\n\nconst buf = Buffer.alloc(1);\nurlSearchParams.has.call(buf, 'foo');\n// Throws a TypeError with code 'ERR_INVALID_THIS'\n\n",
"displayName": "`ERR_INVALID_THIS`"
},
{
"textRaw": "`ERR_INVALID_TUPLE`",
"name": "`err_invalid_tuple`",
"type": "module",
"desc": "An element in the iterable provided to the WHATWG\nURLSearchParams constructor did not\nrepresent a [name, value] tuple – that is, if an element is not iterable, or\ndoes not consist of exactly two elements.
The provided TypeScript syntax is not valid.
\n", "displayName": "`ERR_INVALID_TYPESCRIPT_SYNTAX`" }, { "textRaw": "`ERR_INVALID_URI`", "name": "`err_invalid_uri`", "type": "module", "desc": "An invalid URI was passed.
\n", "displayName": "`ERR_INVALID_URI`" }, { "textRaw": "`ERR_INVALID_URL`", "name": "`err_invalid_url`", "type": "module", "desc": "An invalid URL was passed to the WHATWG URL\nconstructor or the legacy url.parse() to be parsed.\nThe thrown error object typically has an additional property 'input' that\ncontains the URL that failed to parse.
An invalid URLPattern was passed to the WHATWG\nURLPattern constructor to be parsed.
An attempt was made to use a URL of an incompatible scheme (protocol) for a\nspecific purpose. It is only used in the WHATWG URL API support in the\nfs module (which only accepts URLs with 'file' scheme), but may be used\nin other Node.js APIs as well in the future.
An attempt was made to use an IPC communication channel that was already closed.
\n", "displayName": "`ERR_IPC_CHANNEL_CLOSED`" }, { "textRaw": "`ERR_IPC_DISCONNECTED`", "name": "`err_ipc_disconnected`", "type": "module", "desc": "An attempt was made to disconnect an IPC communication channel that was already\ndisconnected. See the documentation for the child_process module\nfor more information.
An attempt was made to create a child Node.js process using more than one IPC\ncommunication channel. See the documentation for the child_process module\nfor more information.
An attempt was made to open an IPC communication channel with a synchronously\nforked Node.js process. See the documentation for the child_process module\nfor more information.
IP is blocked by net.BlockList.
An ESM loader hook returned without calling next() and without explicitly\nsignaling a short circuit.
An error occurred while loading a SQLite extension.
\n", "displayName": "`ERR_LOAD_SQLITE_EXTENSION`" }, { "textRaw": "`ERR_MEMORY_ALLOCATION_FAILED`", "name": "`err_memory_allocation_failed`", "type": "module", "desc": "An attempt was made to allocate memory (usually in the C++ layer) but it\nfailed.
\n", "displayName": "`ERR_MEMORY_ALLOCATION_FAILED`" }, { "textRaw": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`", "name": "`err_message_target_context_unavailable`", "type": "module", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "A message posted to a MessagePort could not be deserialized in the target\nvm Context. Not all Node.js objects can be successfully instantiated in\nany context at this time, and attempting to transfer them using postMessage()\ncan fail on the receiving side in that case.
A method is required but not implemented.
\n", "displayName": "`ERR_METHOD_NOT_IMPLEMENTED`" }, { "textRaw": "`ERR_MISSING_ARGS`", "name": "`err_missing_args`", "type": "module", "desc": "A required argument of a Node.js API was not passed. This is only used for\nstrict compliance with the API specification (which in some cases may accept\nfunc(undefined) but not func()). In most native Node.js APIs,\nfunc(undefined) and func() are treated identically, and the\nERR_INVALID_ARG_TYPE error code may be used instead.
For APIs that accept options objects, some options might be mandatory. This code\nis thrown if a required option is missing.
\n", "displayName": "`ERR_MISSING_OPTION`" }, { "textRaw": "`ERR_MISSING_PASSPHRASE`", "name": "`err_missing_passphrase`", "type": "module", "desc": "An attempt was made to read an encrypted key without specifying a passphrase.
\n", "displayName": "`ERR_MISSING_PASSPHRASE`" }, { "textRaw": "`ERR_MISSING_PLATFORM_FOR_WORKER`", "name": "`err_missing_platform_for_worker`", "type": "module", "desc": "The V8 platform used by this instance of Node.js does not support creating\nWorkers. This is caused by lack of embedder support for Workers. In particular,\nthis error will not occur with standard builds of Node.js.
\n", "displayName": "`ERR_MISSING_PLATFORM_FOR_WORKER`" }, { "textRaw": "`ERR_MODULE_LINK_MISMATCH`", "name": "`err_module_link_mismatch`", "type": "module", "desc": "A module can not be linked because the same module requests in it are not\nresolved to the same module.
\n", "displayName": "`ERR_MODULE_LINK_MISMATCH`" }, { "textRaw": "`ERR_MODULE_NOT_FOUND`", "name": "`err_module_not_found`", "type": "module", "desc": "A module file could not be resolved by the ECMAScript modules loader while\nattempting an import operation or when loading the program entry point.
A callback was called more than once.
\nA callback is almost always meant to only be called once as the query\ncan either be fulfilled or rejected but not both at the same time. The latter\nwould be possible by calling a callback more than once.
\n", "displayName": "`ERR_MULTIPLE_CALLBACK`" }, { "textRaw": "`ERR_NAPI_CONS_FUNCTION`", "name": "`err_napi_cons_function`", "type": "module", "desc": "While using Node-API, a constructor passed was not a function.
While calling napi_create_dataview(), a given offset was outside the bounds\nof the dataview or offset + length was larger than a length of given buffer.
While calling napi_create_typedarray(), the provided offset was not a\nmultiple of the element size.
While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.
An error occurred while invoking the JavaScript portion of the thread-safe\nfunction.
\n", "displayName": "`ERR_NAPI_TSFN_CALL_JS`" }, { "textRaw": "`ERR_NAPI_TSFN_GET_UNDEFINED`", "name": "`err_napi_tsfn_get_undefined`", "type": "module", "desc": "An error occurred while attempting to retrieve the JavaScript undefined\nvalue.
A non-context-aware native addon was loaded in a process that disallows them.
\n", "displayName": "`ERR_NON_CONTEXT_AWARE_DISABLED`" }, { "textRaw": "`ERR_NOT_BUILDING_SNAPSHOT`", "name": "`err_not_building_snapshot`", "type": "module", "desc": "An attempt was made to use operations that can only be used when building\nV8 startup snapshot even though Node.js isn't building one.
\n", "displayName": "`ERR_NOT_BUILDING_SNAPSHOT`" }, { "textRaw": "`ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION`", "name": "`err_not_in_single_executable_application`", "type": "module", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [] }, "desc": "The operation cannot be performed when it's not in a single-executable\napplication.
\n", "displayName": "`ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION`" }, { "textRaw": "`ERR_NOT_SUPPORTED_IN_SNAPSHOT`", "name": "`err_not_supported_in_snapshot`", "type": "module", "desc": "An attempt was made to perform operations that are not supported when\nbuilding a startup snapshot.
\n", "displayName": "`ERR_NOT_SUPPORTED_IN_SNAPSHOT`" }, { "textRaw": "`ERR_NO_CRYPTO`", "name": "`err_no_crypto`", "type": "module", "desc": "An attempt was made to use crypto features while Node.js was not compiled with\nOpenSSL crypto support.
\n", "displayName": "`ERR_NO_CRYPTO`" }, { "textRaw": "`ERR_NO_ICU`", "name": "`err_no_icu`", "type": "module", "desc": "An attempt was made to use features that require ICU, but Node.js was not\ncompiled with ICU support.
\n", "displayName": "`ERR_NO_ICU`" }, { "textRaw": "`ERR_NO_TYPESCRIPT`", "name": "`err_no_typescript`", "type": "module", "meta": { "added": [ "v23.0.0", "v22.12.0" ], "changes": [] }, "desc": "An attempt was made to use features that require Native TypeScript support, but Node.js was not\ncompiled with TypeScript support.
\n", "displayName": "`ERR_NO_TYPESCRIPT`" }, { "textRaw": "`ERR_OPERATION_FAILED`", "name": "`err_operation_failed`", "type": "module", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "An operation failed. This is typically used to signal the general failure\nof an asynchronous operation.
\n", "displayName": "`ERR_OPERATION_FAILED`" }, { "textRaw": "`ERR_OPTIONS_BEFORE_BOOTSTRAPPING`", "name": "`err_options_before_bootstrapping`", "type": "module", "meta": { "added": [ "v23.10.0", "v22.16.0" ], "changes": [] }, "desc": "An attempt was made to get options before the bootstrapping was completed.
\n", "displayName": "`ERR_OPTIONS_BEFORE_BOOTSTRAPPING`" }, { "textRaw": "`ERR_OUT_OF_RANGE`", "name": "`err_out_of_range`", "type": "module", "desc": "A given value is out of the accepted range.
\n", "displayName": "`ERR_OUT_OF_RANGE`" }, { "textRaw": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`", "name": "`err_package_import_not_defined`", "type": "module", "desc": "The package.json \"imports\" field does not define the given internal\npackage specifier mapping.
The package.json \"exports\" field does not export the requested subpath.\nBecause exports are encapsulated, private internal modules that are not exported\ncannot be imported through the package resolution, unless using an absolute URL.
When strict set to true, thrown by util.parseArgs() if a <boolean>\nvalue is provided for an option of type <string>, or if a <string>\nvalue is provided for an option of type <boolean>.
Thrown by util.parseArgs(), when a positional argument is provided and\nallowPositionals is set to false.
When strict set to true, thrown by util.parseArgs() if an argument\nis not configured in options.
An invalid timestamp value was provided for a performance mark or measure.
\n", "displayName": "`ERR_PERFORMANCE_INVALID_TIMESTAMP`" }, { "textRaw": "`ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS`", "name": "`err_performance_measure_invalid_options`", "type": "module", "desc": "Invalid options were provided for a performance measure.
\n", "displayName": "`ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS`" }, { "textRaw": "`ERR_PROTO_ACCESS`", "name": "`err_proto_access`", "type": "module", "desc": "Accessing Object.prototype.__proto__ has been forbidden using\n--disable-proto=throw. Object.getPrototypeOf and\nObject.setPrototypeOf should be used to get and set the prototype of an\nobject.
Failed to proxy a request because the proxy configuration is invalid.
\n", "displayName": "`ERR_PROXY_INVALID_CONFIG`" }, { "textRaw": "`ERR_PROXY_TUNNEL`", "name": "`err_proxy_tunnel`", "type": "module", "desc": "Failed to establish proxy tunnel when NODE_USE_ENV_PROXY or --use-env-proxy is enabled.
A QUIC application error occurred.
\n", "displayName": "`ERR_QUIC_APPLICATION_ERROR`" }, { "textRaw": "`ERR_QUIC_CONNECTION_FAILED`", "name": "`err_quic_connection_failed`", "type": "module", "meta": { "added": [ "v23.0.0", "v22.10.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Establishing a QUIC connection failed.
\n", "displayName": "`ERR_QUIC_CONNECTION_FAILED`" }, { "textRaw": "`ERR_QUIC_ENDPOINT_CLOSED`", "name": "`err_quic_endpoint_closed`", "type": "module", "meta": { "added": [ "v23.0.0", "v22.10.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "A QUIC Endpoint closed with an error.
\n", "displayName": "`ERR_QUIC_ENDPOINT_CLOSED`" }, { "textRaw": "`ERR_QUIC_OPEN_STREAM_FAILED`", "name": "`err_quic_open_stream_failed`", "type": "module", "meta": { "added": [ "v23.0.0", "v22.10.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Opening a QUIC stream failed.
\n", "displayName": "`ERR_QUIC_OPEN_STREAM_FAILED`" }, { "textRaw": "`ERR_QUIC_TRANSPORT_ERROR`", "name": "`err_quic_transport_error`", "type": "module", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "A QUIC transport error occurred.
\n", "displayName": "`ERR_QUIC_TRANSPORT_ERROR`" }, { "textRaw": "`ERR_QUIC_VERSION_NEGOTIATION_ERROR`", "name": "`err_quic_version_negotiation_error`", "type": "module", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "A QUIC session failed because version negotiation is required.
\n", "displayName": "`ERR_QUIC_VERSION_NEGOTIATION_ERROR`" }, { "textRaw": "`ERR_REQUIRE_ASYNC_MODULE`", "name": "`err_require_async_module`", "type": "module", "desc": "When trying to require() a ES Module, the module turns out to be asynchronous.\nThat is, it contains top-level await.
To see where the top-level await is, use\n--experimental-print-required-tla (this would execute the modules\nbefore looking for the top-level awaits).
When trying to require() a ES Module, a CommonJS to ESM or ESM to CommonJS edge\nparticipates in an immediate cycle.\nThis is not allowed because ES Modules cannot be evaluated while they are\nalready being evaluated.
To avoid the cycle, the require() call involved in a cycle should not happen\nat the top-level of either an ES Module (via createRequire()) or a CommonJS\nmodule, and should be done lazily in an inner function.
An attempt was made to require() an ES Module.
This error has been deprecated since require() now supports loading synchronous\nES modules. When require() encounters an ES module that contains top-level\nawait, it will throw ERR_REQUIRE_ASYNC_MODULE instead.
Script execution was interrupted by SIGINT (For\nexample, Ctrl+C was pressed.)
Script execution timed out, possibly due to bugs in the script being executed.
\n", "displayName": "`ERR_SCRIPT_EXECUTION_TIMEOUT`" }, { "textRaw": "`ERR_SERVER_ALREADY_LISTEN`", "name": "`err_server_already_listen`", "type": "module", "desc": "The server.listen() method was called while a net.Server was already\nlistening. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.
The server.close() method was called when a net.Server was not\nrunning. This applies to all instances of net.Server, including HTTP, HTTPS,\nand HTTP/2 Server instances.
A key was passed to single executable application APIs to identify an asset,\nbut no match could be found.
\n", "displayName": "`ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND`" }, { "textRaw": "`ERR_SOCKET_ALREADY_BOUND`", "name": "`err_socket_already_bound`", "type": "module", "desc": "An attempt was made to bind a socket that has already been bound.
\n", "displayName": "`ERR_SOCKET_ALREADY_BOUND`" }, { "textRaw": "`ERR_SOCKET_BAD_BUFFER_SIZE`", "name": "`err_socket_bad_buffer_size`", "type": "module", "desc": "An invalid (negative) size was passed for either the recvBufferSize or\nsendBufferSize options in dgram.createSocket().
An API function expecting a port >= 0 and < 65536 received an invalid value.
\n", "displayName": "`ERR_SOCKET_BAD_PORT`" }, { "textRaw": "`ERR_SOCKET_BAD_TYPE`", "name": "`err_socket_bad_type`", "type": "module", "desc": "An API function expecting a socket type (udp4 or udp6) received an invalid\nvalue.
While using dgram.createSocket(), the size of the receive or send Buffer\ncould not be determined.
An attempt was made to operate on an already closed socket.
\n", "displayName": "`ERR_SOCKET_CLOSED`" }, { "textRaw": "`ERR_SOCKET_CLOSED_BEFORE_CONNECTION`", "name": "`err_socket_closed_before_connection`", "type": "module", "desc": "When calling net.Socket.write() on a connecting socket and the socket was\nclosed before the connection was established.
The socket was unable to connect to any address returned by the DNS within the\nallowed timeout when using the family autoselection algorithm.
\n", "displayName": "`ERR_SOCKET_CONNECTION_TIMEOUT`" }, { "textRaw": "`ERR_SOCKET_DGRAM_IS_CONNECTED`", "name": "`err_socket_dgram_is_connected`", "type": "module", "desc": "A dgram.connect() call was made on an already connected socket.
A dgram.disconnect() or dgram.remoteAddress() call was made on a\ndisconnected socket.
A call was made and the UDP subsystem was not running.
\n", "displayName": "`ERR_SOCKET_DGRAM_NOT_RUNNING`" }, { "textRaw": "`ERR_SOURCE_MAP_CORRUPT`", "name": "`err_source_map_corrupt`", "type": "module", "desc": "The source map could not be parsed because it does not exist, or is corrupt.
\n", "displayName": "`ERR_SOURCE_MAP_CORRUPT`" }, { "textRaw": "`ERR_SOURCE_MAP_MISSING_SOURCE`", "name": "`err_source_map_missing_source`", "type": "module", "desc": "A file imported from a source map was not found.
\n", "displayName": "`ERR_SOURCE_MAP_MISSING_SOURCE`" }, { "textRaw": "`ERR_SOURCE_PHASE_NOT_DEFINED`", "name": "`err_source_phase_not_defined`", "type": "module", "meta": { "added": [ "v24.0.0" ], "changes": [] }, "desc": "The provided module import does not provide a source phase imports representation for source phase\nimport syntax import source x from 'x' or import.source(x).
An error was returned from SQLite.
\n", "displayName": "`ERR_SQLITE_ERROR`" }, { "textRaw": "`ERR_SRI_PARSE`", "name": "`err_sri_parse`", "type": "module", "desc": "A string was provided for a Subresource Integrity check, but was unable to be\nparsed. Check the format of integrity attributes by looking at the\nSubresource Integrity specification.
\n", "displayName": "`ERR_SRI_PARSE`" }, { "textRaw": "`ERR_STREAM_ALREADY_FINISHED`", "name": "`err_stream_already_finished`", "type": "module", "desc": "A stream method was called that cannot complete because the stream was\nfinished.
\n", "displayName": "`ERR_STREAM_ALREADY_FINISHED`" }, { "textRaw": "`ERR_STREAM_CANNOT_PIPE`", "name": "`err_stream_cannot_pipe`", "type": "module", "desc": "An attempt was made to call stream.pipe() on a Writable stream.
A stream method was called that cannot complete because the stream was\ndestroyed using stream.destroy().
An attempt was made to call stream.write() with a null chunk.
An error returned by stream.finished() and stream.pipeline(), when a stream\nor a pipeline ends non gracefully with no explicit error.
An attempt was made to call stream.push() after a null(EOF) had been\npushed to the stream.
An attempt was made to pipe to a closed or destroyed stream in a pipeline.
\n", "displayName": "`ERR_STREAM_UNABLE_TO_PIPE`" }, { "textRaw": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`", "name": "`err_stream_unshift_after_end_event`", "type": "module", "desc": "An attempt was made to call stream.unshift() after the 'end' event was\nemitted.
Prevents an abort if a string decoder was set on the Socket or if the decoder\nis in objectMode.
const Socket = require('node:net').Socket;\nconst instance = new Socket();\n\ninstance.setEncoding('utf8');\n\n",
"displayName": "`ERR_STREAM_WRAP`"
},
{
"textRaw": "`ERR_STREAM_WRITE_AFTER_END`",
"name": "`err_stream_write_after_end`",
"type": "module",
"desc": "An attempt was made to call stream.write() after stream.end() has been\ncalled.
An attempt has been made to create a string longer than the maximum allowed\nlength.
\n", "displayName": "`ERR_STRING_TOO_LONG`" }, { "textRaw": "`ERR_SYNTHETIC`", "name": "`err_synthetic`", "type": "module", "desc": "An artificial error object used to capture the call stack for diagnostic\nreports.
\n", "displayName": "`ERR_SYNTHETIC`" }, { "textRaw": "`ERR_SYSTEM_ERROR`", "name": "`err_system_error`", "type": "module", "desc": "An unspecified or non-specific system error has occurred within the Node.js\nprocess. The error object will have an err.info object property with\nadditional details.
This error represents a failed test. Additional information about the failure\nis available via the cause property. The failureType property specifies\nwhat the test was doing when the failure occurred.
This error is thrown when an ALPNCallback returns a value that is not in the\nlist of ALPN protocols offered by the client.
This error is thrown when creating a TLSServer if the TLS options include\nboth ALPNProtocols and ALPNCallback. These options are mutually exclusive.
This error is thrown by checkServerIdentity if a user-supplied\nsubjectaltname property violates encoding rules. Certificate objects produced\nby Node.js itself always comply with encoding rules and will never cause\nthis error.
While using TLS, the host name/IP of the peer did not match any of the\nsubjectAltNames in its certificate.
While using TLS, the parameter offered for the Diffie-Hellman (DH)\nkey-agreement protocol is too small. By default, the key length must be greater\nthan or equal to 1024 bits to avoid vulnerabilities, even though it is strongly\nrecommended to use 2048 bits or larger for stronger security.
A TLS/SSL handshake timed out. In this case, the server must also abort the\nconnection.
\n", "displayName": "`ERR_TLS_HANDSHAKE_TIMEOUT`" }, { "textRaw": "`ERR_TLS_INVALID_CONTEXT`", "name": "`err_tls_invalid_context`", "type": "module", "meta": { "added": [ "v13.3.0" ], "changes": [] }, "desc": "The context must be a SecureContext.
The specified secureProtocol method is invalid. It is either unknown, or\ndisabled because it is insecure.
Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.
The TLS socket must be connected and securely established. Ensure the 'secure'\nevent is emitted before continuing.
\n", "displayName": "`ERR_TLS_INVALID_STATE`" }, { "textRaw": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`", "name": "`err_tls_protocol_version_conflict`", "type": "module", "desc": "Attempting to set a TLS protocol minVersion or maxVersion conflicts with an\nattempt to set the secureProtocol explicitly. Use one mechanism or the other.
Failed to set PSK identity hint. Hint may be too long.
\n", "displayName": "`ERR_TLS_PSK_SET_IDENTITY_HINT_FAILED`" }, { "textRaw": "`ERR_TLS_RENEGOTIATION_DISABLED`", "name": "`err_tls_renegotiation_disabled`", "type": "module", "desc": "An attempt was made to renegotiate TLS on a socket instance with renegotiation\ndisabled.
\n", "displayName": "`ERR_TLS_RENEGOTIATION_DISABLED`" }, { "textRaw": "`ERR_TLS_REQUIRED_SERVER_NAME`", "name": "`err_tls_required_server_name`", "type": "module", "desc": "While using TLS, the server.addContext() method was called without providing\na host name in the first parameter.
An excessive amount of TLS renegotiations is detected, which is a potential\nvector for denial-of-service attacks.
\n", "displayName": "`ERR_TLS_SESSION_ATTACK`" }, { "textRaw": "`ERR_TLS_SNI_FROM_SERVER`", "name": "`err_tls_sni_from_server`", "type": "module", "desc": "An attempt was made to issue Server Name Indication from a TLS server-side\nsocket, which is only valid from a client.
\n", "displayName": "`ERR_TLS_SNI_FROM_SERVER`" }, { "textRaw": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`", "name": "`err_trace_events_category_required`", "type": "module", "desc": "The trace_events.createTracing() method requires at least one trace event\ncategory.
The node:trace_events module could not be loaded because Node.js was compiled\nwith the --without-v8-platform flag.
Trailing junk found after the end of the compressed stream.\nThis error is thrown when extra, unexpected data is detected\nafter the end of a compressed stream (for example, in zlib\nor gzip decompression).
\n", "displayName": "`ERR_TRAILING_JUNK_AFTER_STREAM_END`" }, { "textRaw": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`", "name": "`err_transform_already_transforming`", "type": "module", "desc": "A Transform stream finished while it was still transforming.
A Transform stream finished with data still in the write buffer.
The initialization of a TTY failed due to a system error.
\n", "displayName": "`ERR_TTY_INIT_FAILED`" }, { "textRaw": "`ERR_UNAVAILABLE_DURING_EXIT`", "name": "`err_unavailable_during_exit`", "type": "module", "desc": "Function was called within a process.on('exit') handler that shouldn't be\ncalled within process.on('exit') handler.
process.setUncaughtExceptionCaptureCallback() was called twice,\nwithout first resetting the callback to null.
This error is designed to prevent accidentally overwriting a callback registered\nfrom another module.
\n", "displayName": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`" }, { "textRaw": "`ERR_UNESCAPED_CHARACTERS`", "name": "`err_unescaped_characters`", "type": "module", "desc": "A string that contained unescaped characters was received.
\n", "displayName": "`ERR_UNESCAPED_CHARACTERS`" }, { "textRaw": "`ERR_UNHANDLED_ERROR`", "name": "`err_unhandled_error`", "type": "module", "desc": "An unhandled error occurred (for instance, when an 'error' event is emitted\nby an EventEmitter but an 'error' handler is not registered).
Used to identify a specific kind of internal Node.js error that should not\ntypically be triggered by user code. Instances of this error point to an\ninternal bug within the Node.js binary itself.
\n", "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" }, { "textRaw": "`ERR_UNKNOWN_CREDENTIAL`", "name": "`err_unknown_credential`", "type": "module", "desc": "A Unix group or user identifier that does not exist was passed.
\n", "displayName": "`ERR_UNKNOWN_CREDENTIAL`" }, { "textRaw": "`ERR_UNKNOWN_ENCODING`", "name": "`err_unknown_encoding`", "type": "module", "desc": "An invalid or unknown encoding option was passed to an API.
\n", "displayName": "`ERR_UNKNOWN_ENCODING`" }, { "textRaw": "`ERR_UNKNOWN_FILE_EXTENSION`", "name": "`err_unknown_file_extension`", "type": "module", "desc": "An attempt was made to load a module with an unknown or unsupported file\nextension.
\n", "displayName": "`ERR_UNKNOWN_FILE_EXTENSION`" }, { "textRaw": "`ERR_UNKNOWN_MODULE_FORMAT`", "name": "`err_unknown_module_format`", "type": "module", "desc": "An attempt was made to load a module with an unknown or unsupported format.
\n", "displayName": "`ERR_UNKNOWN_MODULE_FORMAT`" }, { "textRaw": "`ERR_UNKNOWN_SIGNAL`", "name": "`err_unknown_signal`", "type": "module", "desc": "An invalid or unknown process signal was passed to an API expecting a valid\nsignal (such as subprocess.kill()).
import a directory URL is unsupported. Instead,\nself-reference a package using its name and define a custom subpath in\nthe \"exports\" field of the package.json file.
import './'; // unsupported\nimport './index.js'; // supported\nimport 'package-name'; // supported\n\n",
"displayName": "`ERR_UNSUPPORTED_DIR_IMPORT`"
},
{
"textRaw": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`",
"name": "`err_unsupported_esm_url_scheme`",
"type": "module",
"desc": "import with URL schemes other than file and data is unsupported.
Type stripping is not supported for files descendent of a node_modules directory.
An attempt was made to resolve an invalid module referrer. This can happen when\nimporting or calling import.meta.resolve() with either:
file.try {\n // Trying to import the package 'bare-specifier' from a `data:` URL module:\n await import('data:text/javascript,import \"bare-specifier\"');\n} catch (e) {\n console.log(e.code); // ERR_UNSUPPORTED_RESOLVE_REQUEST\n}\n\n",
"displayName": "`ERR_UNSUPPORTED_RESOLVE_REQUEST`"
},
{
"textRaw": "`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`",
"name": "`err_unsupported_typescript_syntax`",
"type": "module",
"meta": {
"added": [
"v23.7.0",
"v22.14.0"
],
"changes": []
},
"desc": "The provided TypeScript syntax is unsupported.\nThis could happen when using TypeScript syntax that requires\ntransformation with type-stripping.
\n", "displayName": "`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`" }, { "textRaw": "`ERR_USE_AFTER_CLOSE`", "name": "`err_use_after_close`", "type": "module", "desc": "An attempt was made to use something that was already closed.
\n", "displayName": "`ERR_USE_AFTER_CLOSE`" }, { "textRaw": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`", "name": "`err_valid_performance_entry_type`", "type": "module", "desc": "While using the Performance Timing API (perf_hooks), no valid performance\nentry types are found.
A dynamic import callback was not specified.
\n", "displayName": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`" }, { "textRaw": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG`", "name": "`err_vm_dynamic_import_callback_missing_flag`", "type": "module", "desc": "A dynamic import callback was invoked without --experimental-vm-modules.
The module attempted to be linked is not eligible for linking, because of one of\nthe following reasons:
\nlinkingStatus is 'linked')linkingStatus is 'linking')linkingStatus is 'errored')The cachedData option passed to a module constructor is invalid.
Cached data cannot be created for modules which have already been evaluated.
\n", "displayName": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`" }, { "textRaw": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`", "name": "`err_vm_module_different_context`", "type": "module", "desc": "The module being returned from the linker function is from a different context\nthan the parent module. Linked modules must share the same context.
\n", "displayName": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`" }, { "textRaw": "`ERR_VM_MODULE_LINK_FAILURE`", "name": "`err_vm_module_link_failure`", "type": "module", "desc": "The module was unable to be linked due to a failure.
\n", "displayName": "`ERR_VM_MODULE_LINK_FAILURE`" }, { "textRaw": "`ERR_VM_MODULE_NOT_MODULE`", "name": "`err_vm_module_not_module`", "type": "module", "desc": "The fulfilled value of a linking promise is not a vm.Module object.
The current module's status does not allow for this operation. The specific\nmeaning of the error depends on the specific function.
\n", "displayName": "`ERR_VM_MODULE_STATUS`" }, { "textRaw": "`ERR_WASI_ALREADY_STARTED`", "name": "`err_wasi_already_started`", "type": "module", "desc": "The WASI instance has already started.
\n", "displayName": "`ERR_WASI_ALREADY_STARTED`" }, { "textRaw": "`ERR_WASI_NOT_STARTED`", "name": "`err_wasi_not_started`", "type": "module", "desc": "The WASI instance has not been started.
\n", "displayName": "`ERR_WASI_NOT_STARTED`" }, { "textRaw": "`ERR_WEBASSEMBLY_NOT_SUPPORTED`", "name": "`err_webassembly_not_supported`", "type": "module", "desc": "A feature requiring WebAssembly was used, but WebAssembly is not supported or\nhas been disabled in the current environment (for example, when running with\n--jitless).
The Response that has been passed to WebAssembly.compileStreaming or to\nWebAssembly.instantiateStreaming is not a valid WebAssembly response.
The Worker initialization failed.
The execArgv option passed to the Worker constructor contains\ninvalid flags.
The destination thread threw an error while processing a message sent via postMessageToThread().
The thread requested in postMessageToThread() is invalid or has no workerMessage listener.
The thread id requested in postMessageToThread() is the current thread id.
Sending a message via postMessageToThread() timed out.
An operation failed because the Worker instance is not currently running.
The Worker instance terminated because it reached its memory limit.
The path for the main script of a worker is neither an absolute path\nnor a relative path starting with ./ or ../.
All attempts at serializing an uncaught exception from a worker thread failed.
\n", "displayName": "`ERR_WORKER_UNSERIALIZABLE_ERROR`" }, { "textRaw": "`ERR_WORKER_UNSUPPORTED_OPERATION`", "name": "`err_worker_unsupported_operation`", "type": "module", "desc": "The requested functionality is not supported in worker threads.
\n", "displayName": "`ERR_WORKER_UNSUPPORTED_OPERATION`" }, { "textRaw": "`ERR_ZLIB_INITIALIZATION_FAILED`", "name": "`err_zlib_initialization_failed`", "type": "module", "desc": "Creation of a zlib object failed due to incorrect configuration.
An invalid parameter key was passed during construction of a Zstd stream.
\n", "displayName": "`ERR_ZSTD_INVALID_PARAM`" }, { "textRaw": "`HPE_CHUNK_EXTENSIONS_OVERFLOW`", "name": "`hpe_chunk_extensions_overflow`", "type": "module", "meta": { "added": [ "v21.6.2", "v20.11.1", "v18.19.1" ], "changes": [] }, "desc": "Too much data was received for a chunk extensions. In order to protect against\nmalicious or malconfigured clients, if more than 16 KiB of data is received\nthen an Error with this code will be emitted.
Too much HTTP header data was received. In order to protect against malicious or\nmalconfigured clients, if more than maxHeaderSize of HTTP header data is received then\nHTTP parsing will abort without a request or response object being created, and\nan Error with this code will be emitted.
Server is sending both a Content-Length header and Transfer-Encoding: chunked.
Transfer-Encoding: chunked allows the server to maintain an HTTP persistent\nconnection for dynamically generated content.\nIn this case, the Content-Length HTTP header cannot be used.
Use Content-Length or Transfer-Encoding: chunked.
A module file could not be resolved by the CommonJS modules loader while\nattempting a require() operation or when loading the program entry point.
The value passed to postMessage() contained an object that is not supported\nfor transferring.
The native call from process.cpuUsage could not be processed.
The UTF-16 encoding was used with hash.digest(). While the\nhash.digest() method does allow an encoding argument to be passed in,\ncausing the method to return a string rather than a Buffer, the UTF-16\nencoding (e.g. ucs or utf16le) is not supported.
An incompatible combination of options was passed to crypto.scrypt() or\ncrypto.scryptSync(). New versions of Node.js use the error code\nERR_INCOMPATIBLE_OPTION_PAIR instead, which is consistent with other APIs.
An invalid symlink type was passed to the fs.symlink() or\nfs.symlinkSync() methods.
Used when a failure occurs sending an individual frame on the HTTP/2\nsession.
\n", "displayName": "`ERR_HTTP2_FRAME_ERROR`" }, { "textRaw": "`ERR_HTTP2_HEADERS_OBJECT`", "name": "`err_http2_headers_object`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "Used when an HTTP/2 Headers Object is expected.
\n", "displayName": "`ERR_HTTP2_HEADERS_OBJECT`" }, { "textRaw": "`ERR_HTTP2_HEADER_REQUIRED`", "name": "`err_http2_header_required`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "Used when a required header is missing in an HTTP/2 message.
\n", "displayName": "`ERR_HTTP2_HEADER_REQUIRED`" }, { "textRaw": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`", "name": "`err_http2_info_headers_after_respond`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "HTTP/2 informational headers must only be sent prior to calling the\nHttp2Stream.prototype.respond() method.
Used when an action has been performed on an HTTP/2 Stream that has already\nbeen closed.
\n", "displayName": "`ERR_HTTP2_STREAM_CLOSED`" }, { "textRaw": "`ERR_HTTP_INVALID_CHAR`", "name": "`err_http_invalid_char`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "Used when an invalid character is found in an HTTP response status message\n(reason phrase).
\n", "displayName": "`ERR_HTTP_INVALID_CHAR`" }, { "textRaw": "`ERR_IMPORT_ASSERTION_TYPE_FAILED`", "name": "`err_import_assertion_type_failed`", "type": "module", "meta": { "added": [ "v17.1.0", "v16.14.0" ], "changes": [], "removed": [ "v21.1.0" ] }, "desc": "An import assertion has failed, preventing the specified module to be imported.
\n", "displayName": "`ERR_IMPORT_ASSERTION_TYPE_FAILED`" }, { "textRaw": "`ERR_IMPORT_ASSERTION_TYPE_MISSING`", "name": "`err_import_assertion_type_missing`", "type": "module", "meta": { "added": [ "v17.1.0", "v16.14.0" ], "changes": [], "removed": [ "v21.1.0" ] }, "desc": "An import assertion is missing, preventing the specified module to be imported.
\n", "displayName": "`ERR_IMPORT_ASSERTION_TYPE_MISSING`" }, { "textRaw": "`ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED`", "name": "`err_import_assertion_type_unsupported`", "type": "module", "meta": { "added": [ "v17.1.0", "v16.14.0" ], "changes": [], "removed": [ "v21.1.0" ] }, "desc": "An import attribute is not supported by this version of Node.js.
\n", "displayName": "`ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED`" }, { "textRaw": "`ERR_INDEX_OUT_OF_RANGE`", "name": "`err_index_out_of_range`", "type": "module", "meta": { "added": [ "v10.0.0" ], "changes": [], "removed": [ "v11.0.0" ] }, "desc": "A given index was out of the accepted range (e.g. negative offsets).
\n", "displayName": "`ERR_INDEX_OUT_OF_RANGE`" }, { "textRaw": "`ERR_INVALID_OPT_VALUE`", "name": "`err_invalid_opt_value`", "type": "module", "meta": { "added": [ "v8.0.0" ], "changes": [], "removed": [ "v15.0.0" ] }, "desc": "An invalid or unexpected value was passed in an options object.
\n", "displayName": "`ERR_INVALID_OPT_VALUE`" }, { "textRaw": "`ERR_INVALID_OPT_VALUE_ENCODING`", "name": "`err_invalid_opt_value_encoding`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v15.0.0" ] }, "desc": "An invalid or unknown file encoding was passed.
\n", "displayName": "`ERR_INVALID_OPT_VALUE_ENCODING`" }, { "textRaw": "`ERR_INVALID_PERFORMANCE_MARK`", "name": "`err_invalid_performance_mark`", "type": "module", "meta": { "added": [ "v8.5.0" ], "changes": [], "removed": [ "v16.7.0" ] }, "desc": "While using the Performance Timing API (perf_hooks), a performance mark is\ninvalid.
An invalid transfer object was passed to postMessage().
An attempt was made to load a resource, but the resource did not match the\nintegrity defined by the policy manifest. See the documentation for policy\nmanifests for more information.
\n", "displayName": "`ERR_MANIFEST_ASSERT_INTEGRITY`" }, { "textRaw": "`ERR_MANIFEST_DEPENDENCY_MISSING`", "name": "`err_manifest_dependency_missing`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "An attempt was made to load a resource, but the resource was not listed as a\ndependency from the location that attempted to load it. See the documentation\nfor policy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_DEPENDENCY_MISSING`" }, { "textRaw": "`ERR_MANIFEST_INTEGRITY_MISMATCH`", "name": "`err_manifest_integrity_mismatch`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "An attempt was made to load a policy manifest, but the manifest had multiple\nentries for a resource which did not match each other. Update the manifest\nentries to match in order to resolve this error. See the documentation for\npolicy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_INTEGRITY_MISMATCH`" }, { "textRaw": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`", "name": "`err_manifest_invalid_resource_field`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "A policy manifest resource had an invalid value for one of its fields. Update\nthe manifest entry to match in order to resolve this error. See the\ndocumentation for policy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`" }, { "textRaw": "`ERR_MANIFEST_INVALID_SPECIFIER`", "name": "`err_manifest_invalid_specifier`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "A policy manifest resource had an invalid value for one of its dependency\nmappings. Update the manifest entry to match to resolve this error. See the\ndocumentation for policy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_INVALID_SPECIFIER`" }, { "textRaw": "`ERR_MANIFEST_PARSE_POLICY`", "name": "`err_manifest_parse_policy`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "An attempt was made to load a policy manifest, but the manifest was unable to\nbe parsed. See the documentation for policy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_PARSE_POLICY`" }, { "textRaw": "`ERR_MANIFEST_TDZ`", "name": "`err_manifest_tdz`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "An attempt was made to read from a policy manifest, but the manifest\ninitialization has not yet taken place. This is likely a bug in Node.js.
\n", "displayName": "`ERR_MANIFEST_TDZ`" }, { "textRaw": "`ERR_MANIFEST_UNKNOWN_ONERROR`", "name": "`err_manifest_unknown_onerror`", "type": "module", "meta": { "changes": [], "removed": [ "v22.2.0" ] }, "desc": "A policy manifest was loaded, but had an unknown value for its \"onerror\"\nbehavior. See the documentation for policy manifests for more information.
\n", "displayName": "`ERR_MANIFEST_UNKNOWN_ONERROR`" }, { "textRaw": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`", "name": "`err_missing_message_port_in_transfer_list`", "type": "module", "meta": { "changes": [], "removed": [ "v15.0.0" ] }, "desc": "This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST\nin Node.js 15.0.0, because it is no longer accurate as other types of\ntransferable objects also exist now.
An object that needs to be explicitly listed in the transferList argument\nis in the object passed to a postMessage() call, but is not provided\nin the transferList for that call. Usually, this is a MessagePort.
In Node.js versions prior to v15.0.0, the error code being used here was\nERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. However, the set of\ntransferable object types has been expanded to cover more types than\nMessagePort.
Used by the Node-API when Constructor.prototype is not an object.
On the main thread, values are removed from the queue associated with the\nthread-safe function in an idle loop. This error indicates that an error\nhas occurred when attempting to start the loop.
\n", "displayName": "`ERR_NAPI_TSFN_START_IDLE_LOOP`" }, { "textRaw": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`", "name": "`err_napi_tsfn_stop_idle_loop`", "type": "module", "meta": { "added": [ "v10.6.0", "v8.16.0" ], "changes": [], "removed": [ "v14.2.0", "v12.17.0" ] }, "desc": "Once no more items are left in the queue, the idle loop must be suspended. This\nerror indicates that the idle loop has failed to stop.
\n", "displayName": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`" }, { "textRaw": "`ERR_NO_LONGER_SUPPORTED`", "name": "`err_no_longer_supported`", "type": "module", "desc": "A Node.js API was called in an unsupported manner, such as\nBuffer.write(string, encoding, offset[, length]).
Used generically to identify that an operation caused an out of memory\ncondition.
\n", "displayName": "`ERR_OUTOFMEMORY`" }, { "textRaw": "`ERR_PARSE_HISTORY_DATA`", "name": "`err_parse_history_data`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "The node:repl module was unable to parse data from the REPL history file.
Data could not be sent on a socket.
\n", "displayName": "`ERR_SOCKET_CANNOT_SEND`" }, { "textRaw": "`ERR_STDERR_CLOSE`", "name": "`err_stderr_close`", "type": "module", "meta": { "changes": [ { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/23053", "description": "Rather than emitting an error, `process.stderr.end()` now only closes the stream side but not the underlying resource, making this error obsolete." } ], "removed": [ "v10.12.0" ] }, "desc": "An attempt was made to close the process.stderr stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.
An attempt was made to close the process.stdout stream. By design, Node.js\ndoes not allow stdout or stderr streams to be closed by user code.
Used when an attempt is made to use a readable stream that has not implemented\nreadable._read().
An error representing a failing lexer state.
\n", "displayName": "`ERR_TAP_LEXER_ERROR`" }, { "textRaw": "`ERR_TAP_PARSER_ERROR`", "name": "`err_tap_parser_error`", "type": "module", "desc": "An error representing a failing parser state. Additional information about\nthe token causing the error is available via the cause property.
This error represents a failed TAP validation.
\n", "displayName": "`ERR_TAP_VALIDATION_ERROR`" }, { "textRaw": "`ERR_TLS_RENEGOTIATION_FAILED`", "name": "`err_tls_renegotiation_failed`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "Used when a TLS renegotiation request has failed in a non-specific way.
\n", "displayName": "`ERR_TLS_RENEGOTIATION_FAILED`" }, { "textRaw": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`", "name": "`err_transferring_externalized_sharedarraybuffer`", "type": "module", "meta": { "added": [ "v10.5.0" ], "changes": [], "removed": [ "v14.0.0" ] }, "desc": "A SharedArrayBuffer whose memory is not managed by the JavaScript engine\nor by Node.js was encountered during serialization. Such a SharedArrayBuffer\ncannot be serialized.
This can only happen when native addons create SharedArrayBuffers in\n\"externalized\" mode, or put existing SharedArrayBuffer into externalized mode.
An attempt was made to launch a Node.js process with an unknown stdin file\ntype. This error is usually an indication of a bug within Node.js itself,\nalthough it is possible for user code to trigger it.
An attempt was made to launch a Node.js process with an unknown stdout or\nstderr file type. This error is usually an indication of a bug within Node.js\nitself, although it is possible for user code to trigger it.
The V8 BreakIterator API was used but the full ICU data set is not installed.
Used when a given value is out of the accepted range.
\n", "displayName": "`ERR_VALUE_OUT_OF_RANGE`" }, { "textRaw": "`ERR_VM_MODULE_LINKING_ERRORED`", "name": "`err_vm_module_linking_errored`", "type": "module", "meta": { "added": [ "v10.0.0" ], "changes": [], "removed": [ "v18.1.0", "v16.17.0" ] }, "desc": "The linker function returned a module for which linking has failed.
\n", "displayName": "`ERR_VM_MODULE_LINKING_ERRORED`" }, { "textRaw": "`ERR_VM_MODULE_NOT_LINKED`", "name": "`err_vm_module_not_linked`", "type": "module", "desc": "The module must be successfully linked before instantiation.
\n", "displayName": "`ERR_VM_MODULE_NOT_LINKED`" }, { "textRaw": "`ERR_WORKER_UNSUPPORTED_EXTENSION`", "name": "`err_worker_unsupported_extension`", "type": "module", "meta": { "added": [ "v11.0.0" ], "changes": [], "removed": [ "v16.9.0" ] }, "desc": "The pathname used for the main script of a worker has an\nunknown file extension.
\n", "displayName": "`ERR_WORKER_UNSUPPORTED_EXTENSION`" }, { "textRaw": "`ERR_ZLIB_BINDING_CLOSED`", "name": "`err_zlib_binding_closed`", "type": "module", "meta": { "added": [ "v9.0.0" ], "changes": [], "removed": [ "v10.0.0" ] }, "desc": "Used when an attempt is made to use a zlib object after it has already been\nclosed.
The certificate is not yet valid: the notBefore date is after the current time.
\n", "displayName": "`CERT_NOT_YET_VALID`" }, { "textRaw": "`CERT_HAS_EXPIRED`", "name": "`cert_has_expired`", "type": "module", "desc": "The certificate has expired: the notAfter date is before the current time.
\n", "displayName": "`CERT_HAS_EXPIRED`" }, { "textRaw": "`CRL_NOT_YET_VALID`", "name": "`crl_not_yet_valid`", "type": "module", "desc": "The certificate revocation list (CRL) has a future issue date.
\n", "displayName": "`CRL_NOT_YET_VALID`" }, { "textRaw": "`CRL_HAS_EXPIRED`", "name": "`crl_has_expired`", "type": "module", "desc": "The certificate revocation list (CRL) has expired.
\n", "displayName": "`CRL_HAS_EXPIRED`" }, { "textRaw": "`CERT_REVOKED`", "name": "`cert_revoked`", "type": "module", "desc": "The certificate has been revoked; it is on a certificate revocation list (CRL).
\n", "displayName": "`CERT_REVOKED`" } ], "displayName": "Time Validity Errors" }, { "textRaw": "Trust or Chain Related Errors", "name": "trust_or_chain_related_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`UNABLE_TO_GET_ISSUER_CERT`", "name": "`unable_to_get_issuer_cert`", "type": "module", "desc": "The issuer certificate of a looked up certificate could not be found. This\nnormally means the list of trusted certificates is not complete.
\n", "displayName": "`UNABLE_TO_GET_ISSUER_CERT`" }, { "textRaw": "`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`", "name": "`unable_to_get_issuer_cert_locally`", "type": "module", "desc": "The certificate’s issuer is not known. This is the case if the issuer is not\nincluded in the trusted certificate list.
\n", "displayName": "`UNABLE_TO_GET_ISSUER_CERT_LOCALLY`" }, { "textRaw": "`DEPTH_ZERO_SELF_SIGNED_CERT`", "name": "`depth_zero_self_signed_cert`", "type": "module", "desc": "The passed certificate is self-signed and the same certificate cannot be found\nin the list of trusted certificates.
\n", "displayName": "`DEPTH_ZERO_SELF_SIGNED_CERT`" }, { "textRaw": "`SELF_SIGNED_CERT_IN_CHAIN`", "name": "`self_signed_cert_in_chain`", "type": "module", "desc": "The certificate’s issuer is not known. This is the case if the issuer is not\nincluded in the trusted certificate list.
\n", "displayName": "`SELF_SIGNED_CERT_IN_CHAIN`" }, { "textRaw": "`CERT_CHAIN_TOO_LONG`", "name": "`cert_chain_too_long`", "type": "module", "desc": "The certificate chain length is greater than the maximum depth.
\n", "displayName": "`CERT_CHAIN_TOO_LONG`" }, { "textRaw": "`UNABLE_TO_GET_CRL`", "name": "`unable_to_get_crl`", "type": "module", "desc": "The CRL reference by the certificate could not be found.
\n", "displayName": "`UNABLE_TO_GET_CRL`" }, { "textRaw": "`UNABLE_TO_VERIFY_LEAF_SIGNATURE`", "name": "`unable_to_verify_leaf_signature`", "type": "module", "desc": "No signatures could be verified because the chain contains only one certificate\nand it is not self signed.
\n", "displayName": "`UNABLE_TO_VERIFY_LEAF_SIGNATURE`" }, { "textRaw": "`CERT_UNTRUSTED`", "name": "`cert_untrusted`", "type": "module", "desc": "The root certificate authority (CA) is not marked as trusted for the specified\npurpose.
\n", "displayName": "`CERT_UNTRUSTED`" } ], "displayName": "Trust or Chain Related Errors" }, { "textRaw": "Basic Extension Errors", "name": "basic_extension_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`INVALID_CA`", "name": "`invalid_ca`", "type": "module", "desc": "A CA certificate is invalid. Either it is not a CA or its extensions are not\nconsistent with the supplied purpose.
\n", "displayName": "`INVALID_CA`" }, { "textRaw": "`PATH_LENGTH_EXCEEDED`", "name": "`path_length_exceeded`", "type": "module", "desc": "The basicConstraints pathlength parameter has been exceeded.
\n", "displayName": "`PATH_LENGTH_EXCEEDED`" } ], "displayName": "Basic Extension Errors" }, { "textRaw": "Name Related Errors", "name": "name_related_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`HOSTNAME_MISMATCH`", "name": "`hostname_mismatch`", "type": "module", "desc": "Certificate does not match provided name.
\n", "displayName": "`HOSTNAME_MISMATCH`" } ], "displayName": "Name Related Errors" }, { "textRaw": "Usage and Policy Errors", "name": "usage_and_policy_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`INVALID_PURPOSE`", "name": "`invalid_purpose`", "type": "module", "desc": "The supplied certificate cannot be used for the specified purpose.
\n", "displayName": "`INVALID_PURPOSE`" }, { "textRaw": "`CERT_REJECTED`", "name": "`cert_rejected`", "type": "module", "desc": "The root CA is marked to reject the specified purpose.
\n", "displayName": "`CERT_REJECTED`" } ], "displayName": "Usage and Policy Errors" }, { "textRaw": "Formatting Errors", "name": "formatting_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`CERT_SIGNATURE_FAILURE`", "name": "`cert_signature_failure`", "type": "module", "desc": "The signature of the certificate is invalid.
\n", "displayName": "`CERT_SIGNATURE_FAILURE`" }, { "textRaw": "`CRL_SIGNATURE_FAILURE`", "name": "`crl_signature_failure`", "type": "module", "desc": "The signature of the certificate revocation list (CRL) is invalid.
\n", "displayName": "`CRL_SIGNATURE_FAILURE`" }, { "textRaw": "`ERROR_IN_CERT_NOT_BEFORE_FIELD`", "name": "`error_in_cert_not_before_field`", "type": "module", "desc": "The certificate notBefore field contains an invalid time.
\n", "displayName": "`ERROR_IN_CERT_NOT_BEFORE_FIELD`" }, { "textRaw": "`ERROR_IN_CERT_NOT_AFTER_FIELD`", "name": "`error_in_cert_not_after_field`", "type": "module", "desc": "The certificate notAfter field contains an invalid time.
\n", "displayName": "`ERROR_IN_CERT_NOT_AFTER_FIELD`" }, { "textRaw": "`ERROR_IN_CRL_LAST_UPDATE_FIELD`", "name": "`error_in_crl_last_update_field`", "type": "module", "desc": "The CRL lastUpdate field contains an invalid time.
\n", "displayName": "`ERROR_IN_CRL_LAST_UPDATE_FIELD`" }, { "textRaw": "`ERROR_IN_CRL_NEXT_UPDATE_FIELD`", "name": "`error_in_crl_next_update_field`", "type": "module", "desc": "The CRL nextUpdate field contains an invalid time.
\n", "displayName": "`ERROR_IN_CRL_NEXT_UPDATE_FIELD`" }, { "textRaw": "`UNABLE_TO_DECRYPT_CERT_SIGNATURE`", "name": "`unable_to_decrypt_cert_signature`", "type": "module", "desc": "The certificate signature could not be decrypted. This means that the actual\nsignature value could not be determined rather than it not matching the expected\nvalue, this is only meaningful for RSA keys.
\n", "displayName": "`UNABLE_TO_DECRYPT_CERT_SIGNATURE`" }, { "textRaw": "`UNABLE_TO_DECRYPT_CRL_SIGNATURE`", "name": "`unable_to_decrypt_crl_signature`", "type": "module", "desc": "The certificate revocation list (CRL) signature could not be decrypted: this\nmeans that the actual signature value could not be determined rather than it not\nmatching the expected value.
\n", "displayName": "`UNABLE_TO_DECRYPT_CRL_SIGNATURE`" }, { "textRaw": "`UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY`", "name": "`unable_to_decode_issuer_public_key`", "type": "module", "desc": "The public key in the certificate SubjectPublicKeyInfo could not be read.
\n", "displayName": "`UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY`" } ], "displayName": "Formatting Errors" }, { "textRaw": "Other OpenSSL Errors", "name": "other_openssl_errors", "type": "module", "desc": "", "modules": [ { "textRaw": "`OUT_OF_MEM`", "name": "`out_of_mem`", "type": "module", "desc": "An error occurred trying to allocate memory. This should never happen.
", "displayName": "`OUT_OF_MEM`" } ], "displayName": "Other OpenSSL Errors" } ], "displayName": "OpenSSL Error Codes" } ], "classes": [ { "textRaw": "Class: `Error`", "name": "Error", "type": "class", "desc": "A generic JavaScript <Error> object that does not denote any specific\ncircumstance of why the error occurred. Error objects capture a \"stack trace\"\ndetailing the point in the code at which the Error was instantiated, and may\nprovide a text description of the error.
All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.
Creates a new Error object and sets the error.message property to the\nprovided text message. If an object is passed as message, the text message\nis generated by calling String(message). If the cause option is provided,\nit is assigned to the error.cause property. The error.stack property will\nrepresent the point in the code at which new Error() was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit, whichever is smaller.
Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack; // Similar to `new Error().stack`\n\nThe first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.
The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.
The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:
function a() {\n b();\n}\n\nfunction b() {\n c();\n}\n\nfunction c() {\n // Create an error without stack trace to avoid calculating the stack trace twice.\n const { stackTraceLimit } = Error;\n Error.stackTraceLimit = 0;\n const error = new Error();\n Error.stackTraceLimit = stackTraceLimit;\n\n // Capture the stack trace above function b\n Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace\n throw error;\n}\n\na();\n"
}
],
"properties": [
{
"textRaw": "Type: {number}",
"name": "stackTraceLimit",
"type": "number",
"desc": "The Error.stackTraceLimit property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack or\nError.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.
" }, { "textRaw": "Type: {any}", "name": "cause", "type": "any", "meta": { "added": [ "v16.9.0" ], "changes": [] }, "desc": "If present, the error.cause property is the underlying cause of the Error.\nIt is used when catching an error and throwing a new one with a different\nmessage or code in order to still have access to the original error.
The error.cause property is typically set by calling\nnew Error(message, { cause }). It is not set by the constructor if the\ncause option is not provided.
This property allows errors to be chained. When serializing Error objects,\nutil.inspect() recursively serializes error.cause if it is set.
const cause = new Error('The remote HTTP server responded with a 500 status');\nconst symptom = new Error('The message failed to send', { cause });\n\nconsole.log(symptom);\n// Prints:\n// Error: The message failed to send\n// at REPL2:1:17\n// at Script.runInThisContext (node:vm:130:12)\n// ... 7 lines matching cause stack trace ...\n// at [_line] [as _line] (node:internal/readline/interface:886:18) {\n// [cause]: Error: The remote HTTP server responded with a 500 status\n// at REPL1:1:15\n// at Script.runInThisContext (node:vm:130:12)\n// at REPLServer.defaultEval (node:repl:574:29)\n// at bound (node:domain:426:15)\n// at REPLServer.runBound [as eval] (node:domain:437:12)\n// at REPLServer.onLine (node:repl:902:10)\n// at REPLServer.emit (node:events:549:35)\n// at REPLServer.emit (node:domain:482:12)\n// at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)\n// at [_line] [as _line] (node:internal/readline/interface:886:18)\n"
},
{
"textRaw": "Type: {string}",
"name": "code",
"type": "string",
"desc": "The error.code property is a string label that identifies the kind of error.\nerror.code is the most stable way to identify an error. It will only change\nbetween major versions of Node.js. In contrast, error.message strings may\nchange between any versions of Node.js. See Node.js error codes for details\nabout specific codes.
The error.message property is the string description of the error as set by\ncalling new Error(message). The message passed to the constructor will also\nappear in the first line of the stack trace of the Error, however changing\nthis property after the Error object is created may not change the first\nline of the stack trace (for example, when error.stack is read before this\nproperty is changed).
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n"
},
{
"textRaw": "Type: {string}",
"name": "stack",
"type": "string",
"desc": "The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.
Error: Things keep happening!\n at /home/gbusey/file.js:525:2\n at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n at increaseSynergy (/home/gbusey/actors.js:701:6)\n\nThe first line is formatted as <error class name>: <error message>, and\nis followed by a series of stack frames (each line beginning with \"at \").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.
Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify which\nitself calls a JavaScript function, the frame representing the cheetahify call\nwill not be present in the stack traces:
const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n // `cheetahify()` *synchronously* calls speedy.\n cheetahify(function speedy() {\n throw new Error('oh no!');\n });\n}\n\nmakeFaster();\n// will throw:\n// /home/gbusey/file.js:6\n// throw new Error('oh no!');\n// ^\n// Error: oh no!\n// at speedy (/home/gbusey/file.js:6:11)\n// at makeFaster (/home/gbusey/file.js:5:3)\n// at Object.<anonymous> (/home/gbusey/file.js:10:1)\n// at Module._compile (module.js:456:26)\n// at Object.Module._extensions..js (module.js:474:10)\n// at Module.load (module.js:356:32)\n// at Function.Module._load (module.js:312:12)\n// at Function.Module.runMain (module.js:497:10)\n// at startup (node.js:119:16)\n// at node.js:906:3\n\nThe location information will be one of:
\nnative, if the frame represents a call internal to V8 (as in [].forEach).plain-filename.js:line:column, if the frame represents a call internal\nto Node.js./absolute/path/to/file.js:line:column, if the frame represents a call in\na user program (using CommonJS module system), or its dependencies.<transport-protocol>:///url/to/module/file.mjs:line:column, if the frame\nrepresents a call in a user program (using ES module system), or\nits dependencies.The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit or the number of available frames on the current event\nloop tick.
error.stack is a getter/setter for a hidden internal property which is only\npresent on builtin Error objects (those for which Error.isError returns\ntrue). If error is not a builtin error object, then the error.stack getter\nwill always return undefined, and the setter will do nothing. This can occur\nif the accessor is manually invoked with a this value that is not a builtin\nerror object, such as a <Proxy>.
<errors.Error>Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.
<errors.Error>Indicates that a provided argument was not within the set or range of\nacceptable values for a function; whether that is a numeric range, or\noutside the set of options for a given function parameter.
\nrequire('node:net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n\nNode.js will generate and throw RangeError instances immediately as a form\nof argument validation.
<errors.Error>Indicates that an attempt is being made to access a variable that is not\ndefined. Such errors commonly indicate typos in code, or an otherwise broken\nprogram.
\nWhile client code may generate and propagate these errors, in practice, only V8\nwill do so.
\ndoesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n\nUnless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.
<errors.Error>Indicates that a program is not valid JavaScript. These errors may only be\ngenerated and propagated as a result of code evaluation. Code evaluation may\nhappen as a result of eval, Function, require, or vm. These errors\nare almost always indicative of a broken program.
try {\n require('node:vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n // 'err' will be a SyntaxError.\n}\n\nSyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.
<errors.Error>Node.js generates system errors when exceptions occur within its runtime\nenvironment. These usually occur when an application violates an operating\nsystem constraint. For example, a system error will occur if an application\nattempts to read a file that does not exist.
\naddress <string> If present, the address to which a network connection\nfailedcode <string> The string error codedest <string> If present, the file path destination when reporting a file\nsystem errorerrno <number> The system-provided error numberinfo <Object> If present, extra details about the error conditionmessage <string> A system-provided human-readable description of the errorpath <string> If present, the file path when reporting a file system errorport <number> If present, the network connection port that is not availablesyscall <string> The name of the system call that triggered the errorIf present, error.address is a string describing the address to which a\nnetwork connection failed.
The error.code property is a string representing the error code.
If present, error.dest is the file path destination when reporting a file\nsystem error.
The error.errno property is a negative number which corresponds\nto the error code defined in libuv Error handling.
On Windows the error number provided by the system will be normalized by libuv.
\nTo get the string representation of the error code, use\nutil.getSystemErrorName(error.errno).
If present, error.info is an object with details about the error condition.
error.message is a system-provided human-readable description of the error.
If present, error.path is a string containing a relevant invalid pathname.
If present, error.port is the network connection port that is not available.
The error.syscall property is a string describing the syscall that failed.
This is a list of system errors commonly-encountered when writing a Node.js\nprogram. For a comprehensive list, see the errno(3) man page.
EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.
EADDRINUSE (Address already in use): An attempt to bind a server\n(net, http, or https) to a local address failed due to\nanother server on the local system already occupying that address.
ECONNREFUSED (Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.
ECONNRESET (Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http\nand net modules.
EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.
EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.
EMFILE (Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048 in the same shell that will run the Node.js process.
ENOENT (No such file or directory): Commonly raised by fs operations\nto indicate that a component of the specified pathname does not exist. No\nentity (file or directory) could be found by the given path.
ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.
ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.
ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.
EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.
EPIPE (Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net and\nhttp layers, indicative that the remote side of the stream being\nwritten to has been closed.
ETIMEDOUT (Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http or net. Often a sign that a socket.end()\nwas not properly called.
<errors.Error>Indicates that a provided argument is not an allowable type. For example,\npassing a function to a parameter which expects a string would be a TypeError.
require('node:url').parse(() => { });\n// Throws TypeError, since it expected a string.\n\nNode.js will generate and throw TypeError instances immediately as a form\nof argument validation.
These objects are available in all modules.
\nThe following variables may appear to be global but are not. They exist only in\nthe scope of CommonJS modules:
\n__dirname__filenameexportsmodulerequire()The objects listed here are specific to Node.js. There are built-in objects\nthat are part of the JavaScript language itself, which are also globally\naccessible.
", "miscs": [ { "textRaw": "`__dirname`", "name": "`__dirname`", "type": "misc", "desc": "This variable may appear to be global but is not. See __dirname.
This variable may appear to be global but is not. See __filename.
<Object>Used to print to stdout and stderr. See the console section.
A browser-compatible implementation of the Web Crypto API.
", "displayName": "`crypto`" }, { "textRaw": "`ErrorEvent`", "name": "`errorevent`", "type": "misc", "meta": { "added": [ "v25.0.0" ], "changes": [] }, "desc": "A browser-compatible implementation of <ErrorEvent>.
This variable may appear to be global but is not. See exports.
A browser-compatible implementation of the fetch() function.
const res = await fetch('https://nodejs.org/api/documentation.json');\nif (res.ok) {\n const data = await res.json();\n console.log(data);\n}\n\nThe implementation is based upon undici, an HTTP/1.1 client\nwritten from scratch for Node.js. You can figure out which version of undici is bundled\nin your Node.js process reading the process.versions.undici property.
You can use a custom dispatcher to dispatch requests passing it in fetch's options object.\nThe dispatcher must be compatible with undici's\nDispatcher class.
fetch(url, { dispatcher: new MyAgent() });\n\nIt is possible to change the global dispatcher in Node.js by installing undici and using\nthe setGlobalDispatcher() method. Calling this method will affect both undici and\nNode.js.
import { setGlobalDispatcher } from 'undici';\nsetGlobalDispatcher(new MyAgent());\n",
"displayName": "Custom dispatcher"
},
{
"textRaw": "Related classes",
"name": "related_classes",
"type": "module",
"desc": "The following globals are available to use with fetch:
<Object> The global namespace object.In browsers, the top-level scope has traditionally been the global scope. This\nmeans that var something will define a new global variable, except within\nECMAScript modules. In Node.js, this is different. The top-level scope is not\nthe global scope; var something inside a Node.js module will be local to that\nmodule, regardless of whether it is a CommonJS module or an\nECMAScript module.
A browser-compatible implementation of localStorage. Data is stored\nunencrypted in the file specified by the --localstorage-file CLI flag.\nThe maximum amount of data that can be stored is 10 MB.\nAny modification of this data outside of the Web Storage API is not supported.\nlocalStorage data is not stored per user or per request when used in the context\nof a server, it is shared across all users and requests.
This variable may appear to be global but is not. See module.
A partial implementation of window.navigator.
The navigator.hardwareConcurrency read-only property returns the number of\nlogical processors available to the current Node.js instance.
console.log(`This process is running on ${navigator.hardwareConcurrency} logical processors`);\n"
},
{
"textRaw": "Type: {string}",
"name": "language",
"type": "string",
"meta": {
"added": [
"v21.2.0"
],
"changes": []
},
"desc": "The navigator.language read-only property returns a string representing the\npreferred language of the Node.js instance. The language will be determined by\nthe ICU library used by Node.js at runtime based on the\ndefault language of the operating system.
The value is representing the language version as defined in RFC 5646.
\nThe fallback value on builds without ICU is 'en-US'.
console.log(`The preferred language of the Node.js instance has the tag '${navigator.language}'`);\n"
},
{
"textRaw": "Type: {string[]}",
"name": "languages",
"type": "string[]",
"meta": {
"added": [
"v21.2.0"
],
"changes": []
},
"desc": "The navigator.languages read-only property returns an array of strings\nrepresenting the preferred languages of the Node.js instance.\nBy default navigator.languages contains only the value of\nnavigator.language, which will be determined by the ICU library used by\nNode.js at runtime based on the default language of the operating system.
The fallback value on builds without ICU is ['en-US'].
console.log(`The preferred languages are '${navigator.languages}'`);\n"
},
{
"textRaw": "`navigator.locks`",
"name": "locks",
"type": "property",
"meta": {
"added": [
"v24.5.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "The navigator.locks read-only property returns a LockManager instance that\ncan be used to coordinate access to resources that may be shared across multiple\nthreads within the same process. This global implementation matches the semantics\nof the browser LockManager API.
// Request an exclusive lock\nawait navigator.locks.request('my_resource', async (lock) => {\n // The lock has been acquired.\n console.log(`Lock acquired: ${lock.name}`);\n // Lock is automatically released when the function returns\n});\n\n// Request a shared lock\nawait navigator.locks.request('shared_resource', { mode: 'shared' }, async (lock) => {\n // Multiple shared locks can be held simultaneously\n console.log(`Shared lock acquired: ${lock.name}`);\n});\n\n// Request an exclusive lock\nnavigator.locks.request('my_resource', async (lock) => {\n // The lock has been acquired.\n console.log(`Lock acquired: ${lock.name}`);\n // Lock is automatically released when the function returns\n}).then(() => {\n console.log('Lock released');\n});\n\n// Request a shared lock\nnavigator.locks.request('shared_resource', { mode: 'shared' }, async (lock) => {\n // Multiple shared locks can be held simultaneously\n console.log(`Shared lock acquired: ${lock.name}`);\n}).then(() => {\n console.log('Shared lock released');\n});\n\nSee worker_threads.locks for detailed API documentation.
The navigator.platform read-only property returns a string identifying the\nplatform on which the Node.js instance is running.
console.log(`This process is running on ${navigator.platform}`);\n"
},
{
"textRaw": "Type: {string}",
"name": "userAgent",
"type": "string",
"meta": {
"added": [
"v21.1.0"
],
"changes": []
},
"desc": "The navigator.userAgent read-only property returns user agent\nconsisting of the runtime name and major version number.
console.log(`The user-agent is ${navigator.userAgent}`); // Prints \"Node.js/21\"\n"
}
],
"displayName": "`navigator`"
},
{
"textRaw": "`performance`",
"name": "`performance`",
"type": "misc",
"meta": {
"added": [
"v16.0.0"
],
"changes": []
},
"desc": "The perf_hooks.performance object.
<Object>The process object. See the process object section.
A browser-compatible implementation of sessionStorage. Data is stored in\nmemory, with a storage quota of 10 MB. sessionStorage data persists only within\nthe currently running process, and is not shared between workers.
A utility class used to signal cancelation in selected Promise-based APIs.\nThe API is based on the Web API <AbortController>.
const ac = new AbortController();\n\nac.signal.addEventListener('abort', () => console.log('Aborted!'),\n { once: true });\n\nac.abort();\n\nconsole.log(ac.signal.aborted); // Prints true\n",
"methods": [
{
"textRaw": "`abortController.abort([reason])`",
"name": "abort",
"type": "method",
"meta": {
"added": [
"v15.0.0",
"v14.17.0"
],
"changes": [
{
"version": [
"v17.2.0",
"v16.14.0"
],
"pr-url": "https://github.com/nodejs/node/pull/40807",
"description": "Added the new optional reason argument."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`reason` {any} An optional reason, retrievable on the `AbortSignal`'s `reason` property.",
"name": "reason",
"type": "any",
"desc": "An optional reason, retrievable on the `AbortSignal`'s `reason` property.",
"optional": true
}
]
}
],
"desc": "Triggers the abort signal, causing the abortController.signal to emit\nthe 'abort' event.
<EventTarget>The AbortSignal is used to notify observers when the\nabortController.abort() method is called.
Returns a new already aborted AbortSignal.
Returns a new AbortSignal which will be aborted in delay milliseconds.
Returns a new AbortSignal which will be aborted if any of the provided\nsignals are aborted. Its abortSignal.reason will be set to whichever\none of the signals caused it to be aborted.
The 'abort' event is emitted when the abortController.abort() method\nis called. The callback is invoked with a single object argument with a\nsingle type property set to 'abort':
const ac = new AbortController();\n\n// Use either the onabort property...\nac.signal.onabort = () => console.log('aborted!');\n\n// Or the EventTarget API...\nac.signal.addEventListener('abort', (event) => {\n console.log(event.type); // Prints 'abort'\n}, { once: true });\n\nac.abort();\n\nThe AbortController with which the AbortSignal is associated will only\never trigger the 'abort' event once. We recommended that code check\nthat the abortSignal.aborted attribute is false before adding an 'abort'\nevent listener.
Any event listeners attached to the AbortSignal should use the\n{ once: true } option (or, if using the EventEmitter APIs to attach a\nlistener, use the once() method) to ensure that the event listener is\nremoved as soon as the 'abort' event is handled. Failure to do so may\nresult in memory leaks.
True after the AbortController has been aborted.
An optional callback function that may be set by user code to be notified\nwhen the abortController.abort() function has been called.
An optional reason specified when the AbortSignal was triggered.
const ac = new AbortController();\nac.abort(new Error('boom!'));\nconsole.log(ac.signal.reason); // Error: boom!\n"
}
],
"methods": [
{
"textRaw": "`abortSignal.throwIfAborted()`",
"name": "throwIfAborted",
"type": "method",
"meta": {
"added": [
"v17.3.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "If abortSignal.aborted is true, throws abortSignal.reason.
See <Blob>.
See <BroadcastChannel>.
<Function>Used to handle binary data. See the buffer section.
" }, { "textRaw": "Class: `ByteLengthQueuingStrategy`", "name": "ByteLengthQueuingStrategy", "type": "class", "meta": { "added": [ "v18.0.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "desc": "A browser-compatible implementation of ByteLengthQueuingStrategy.
A browser-compatible implementation of <CloseEvent>. Disable this API\nwith the --no-experimental-websocket CLI flag.
A browser-compatible implementation of CompressionStream.
A browser-compatible implementation of CountQueuingStrategy.
A browser-compatible implementation of <Crypto>. This global is available\nonly if the Node.js binary was compiled with including support for the node:crypto module.
A browser-compatible implementation of <CryptoKey>. This global is available\nonly if the Node.js binary was compiled with including support for the node:crypto module.
A browser-compatible implementation of <CustomEvent>.
A browser-compatible implementation of DecompressionStream.
The WHATWG <DOMException> class.
A browser-compatible implementation of the Event class. See\nEventTarget and Event API for more details.
A browser-compatible implementation of <EventSource>.
A browser-compatible implementation of the EventTarget class. See\nEventTarget and Event API for more details.
See <File>.
A browser-compatible implementation of <FormData>.
A browser-compatible implementation of <Headers>.
The MessageChannel class. See MessageChannel for more details.
A browser-compatible implementation of <MessageEvent>.
The MessagePort class. See MessagePort for more details.
A partial implementation of the Navigator API.
" }, { "textRaw": "Class: `PerformanceEntry`", "name": "PerformanceEntry", "type": "class", "meta": { "added": [ "v19.0.0" ], "changes": [] }, "desc": "The PerformanceEntry class. See PerformanceEntry for more details.
The PerformanceMark class. See PerformanceMark for more details.
The PerformanceMeasure class. See PerformanceMeasure for more details.
The PerformanceObserver class. See PerformanceObserver for more details.
The PerformanceObserverEntryList class. See\nPerformanceObserverEntryList for more details.
The PerformanceResourceTiming class. See PerformanceResourceTiming for\nmore details.
A browser-compatible implementation of ReadableByteStreamController.
A browser-compatible implementation of ReadableStream.
A browser-compatible implementation of ReadableStreamBYOBReader.
A browser-compatible implementation of ReadableStreamBYOBRequest.
A browser-compatible implementation of ReadableStreamDefaultController.
A browser-compatible implementation of ReadableStreamDefaultReader.
A browser-compatible implementation of <Request>.
A browser-compatible implementation of <Response>.
A browser-compatible implementation of <Storage>.
A browser-compatible implementation of <SubtleCrypto>. This global is available\nonly if the Node.js binary was compiled with including support for the node:crypto module.
The WHATWG TextDecoder class. See the TextDecoder section.
A browser-compatible implementation of TextDecoderStream.
The WHATWG TextEncoder class. See the TextEncoder section.
A browser-compatible implementation of TextEncoderStream.
A browser-compatible implementation of TransformStream.
A browser-compatible implementation of TransformStreamDefaultController.
The WHATWG URL class. See the URL section.
The WHATWG URLPattern class. See the URLPattern section.
The WHATWG URLSearchParams class. See the URLSearchParams section.
<Object>The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.
" }, { "textRaw": "Class: `WebSocket`", "name": "WebSocket", "type": "class", "meta": { "added": [ "v21.0.0", "v20.10.0" ], "changes": [ { "version": "v22.4.0", "pr-url": "https://github.com/nodejs/node/pull/53352", "description": "No longer experimental." }, { "version": "v22.0.0", "pr-url": "https://github.com/nodejs/node/pull/51594", "description": "No longer behind `--experimental-websocket` CLI flag." } ] }, "desc": "A browser-compatible implementation of <WebSocket>. Disable this API\nwith the --no-experimental-websocket CLI flag.
A browser-compatible implementation of WritableStream.
A browser-compatible implementation of WritableStreamDefaultController.
A browser-compatible implementation of WritableStreamDefaultWriter.
Global alias for buffer.atob().
An automated migration is available (source):
\nnpx codemod@latest @nodejs/buffer-atob-btoa\n"
},
{
"textRaw": "`btoa(data)`",
"name": "btoa",
"type": "method",
"meta": {
"added": [
"v16.0.0"
],
"changes": []
},
"stability": 3,
"stabilityText": "Legacy. Use `buf.toString('base64')` instead.",
"signatures": [
{
"params": [
{
"name": "data"
}
]
}
],
"desc": "Global alias for buffer.btoa().
An automated migration is available (source):
\nnpx codemod@latest @nodejs/buffer-atob-btoa\n"
},
{
"textRaw": "`clearImmediate(immediateObject)`",
"name": "clearImmediate",
"type": "method",
"meta": {
"added": [
"v0.9.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"name": "immediateObject"
}
]
}
],
"desc": "clearImmediate is described in the timers section.
clearInterval is described in the timers section.
clearTimeout is described in the timers section.
The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.
The microtask queue is managed by V8 and may be used in a similar manner to\nthe process.nextTick() queue, which is managed by Node.js. The\nprocess.nextTick() queue is always processed before the microtask queue\nwithin each turn of the Node.js event loop.
// Here, `queueMicrotask()` is used to ensure the 'load' event is always\n// emitted asynchronously, and therefore consistently. Using\n// `process.nextTick()` here would result in the 'load' event always emitting\n// before any other promise jobs.\n\nDataHandler.prototype.load = async function load(key) {\n const hit = this._cache.get(key);\n if (hit !== undefined) {\n queueMicrotask(() => {\n this.emit('load', hit);\n });\n return;\n }\n\n const data = await fetchData(key);\n this._cache.set(key, data);\n this.emit('load', data);\n};\n"
},
{
"textRaw": "`require()`",
"name": "require",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "This variable may appear to be global but is not. See require().
setImmediate is described in the timers section.
setInterval is described in the timers section.
setTimeout is described in the timers section.
The WHATWG structuredClone method.
Node.js has many features that make it easier to write internationalized\nprograms. Some of them are:
\nIntl objectString.prototype.localeCompare() and\nDate.prototype.toLocaleString()require('node:buffer').transcode()require('node:util').TextDecoderRegExp Unicode Property EscapesNode.js and the underlying V8 engine use\nInternational Components for Unicode (ICU) to implement these features\nin native C/C++ code. The full ICU data set is provided by Node.js by default.\nHowever, due to the size of the ICU data file, several\noptions are provided for customizing the ICU data set either when\nbuilding or running Node.js.
", "miscs": [ { "textRaw": "Options for building Node.js", "name": "options_for_building_node.js", "type": "misc", "desc": "To control how ICU is used in Node.js, four configure options are available\nduring compilation. Additional details on how to compile Node.js are documented\nin BUILDING.md.
--with-intl=none/--without-intl--with-intl=system-icu--with-intl=small-icu--with-intl=full-icu (default)An overview of available Node.js and JavaScript features for each configure\noption:
| Feature | none | system-icu | small-icu | full-icu |
|---|---|---|---|---|
String.prototype.normalize() | none (function is no-op) | full | full | full |
String.prototype.to*Case() | full | full | full | full |
Intl | none (object does not exist) | partial/full (depends on OS) | partial (English-only) | full |
String.prototype.localeCompare() | partial (not locale-aware) | full | full | full |
String.prototype.toLocale*Case() | partial (not locale-aware) | full | full | full |
Number.prototype.toLocaleString() | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
Date.prototype.toLocale*String() | partial (not locale-aware) | partial/full (depends on OS) | partial (English-only) | full |
| Legacy URL Parser | partial (no IDN support) | full | full | full |
| WHATWG URL Parser | partial (no IDN support) | full | full | full |
require('node:buffer').transcode() | none (function does not exist) | full | full | full |
| REPL | partial (inaccurate line editing) | full | full | full |
require('node:util').TextDecoder | partial (basic encodings support) | partial/full (depends on OS) | partial (Unicode-only) | full |
RegExp Unicode Property Escapes | none (invalid RegExp error) | full | full | full |
The \"(not locale-aware)\" designation denotes that the function carries out its\noperation just like the non-Locale version of the function, if one\nexists. For example, under none mode, Date.prototype.toLocaleString()'s\noperation is identical to that of Date.prototype.toString().
If this option is chosen, ICU is disabled and most internationalization\nfeatures mentioned above will be unavailable in the resulting node binary.
Node.js can link against an ICU build already installed on the system. In fact,\nmost Linux distributions already come with ICU installed, and this option would\nmake it possible to reuse the same set of data used by other components in the\nOS.
\nFunctionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under system-icu. Features that require ICU locale data in\naddition, such as Intl.DateTimeFormat may be fully or partially\nsupported, depending on the completeness of the ICU data installed on the\nsystem.
This option makes the resulting binary link against the ICU library statically,\nand includes a subset of ICU data (typically only the English locale) within\nthe node executable.
Functionalities that only require the ICU library itself, such as\nString.prototype.normalize() and the WHATWG URL parser, are fully\nsupported under small-icu. Features that require ICU locale data in addition,\nsuch as Intl.DateTimeFormat, generally only work with the English locale:
const january = new Date(9e8);\nconst english = new Intl.DateTimeFormat('en', { month: 'long' });\nconst spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n\nconsole.log(english.format(january));\n// Prints \"January\"\nconsole.log(spanish.format(january));\n// Prints either \"M01\" or \"January\" on small-icu, depending on the user’s default locale\n// Should print \"enero\"\n\nThis mode provides a balance between features and binary size.
", "modules": [ { "textRaw": "Providing ICU data at runtime", "name": "providing_icu_data_at_runtime", "type": "module", "desc": "If the small-icu option is used, one can still provide additional locale data\nat runtime so that the JS methods would work for all ICU locales. Assuming the\ndata file is stored at /runtime/directory/with/dat/file, it can be made\navailable to ICU through either:
The --with-icu-default-data-dir configure option:
./configure --with-icu-default-data-dir=/runtime/directory/with/dat/file --with-intl=small-icu\n\nThis only embeds the default data directory path into the binary.\nThe actual data file is going to be loaded at runtime from this directory\npath.
\nThe NODE_ICU_DATA environment variable:
env NODE_ICU_DATA=/runtime/directory/with/dat/file node\n\nThe --icu-data-dir CLI parameter:
node --icu-data-dir=/runtime/directory/with/dat/file\n\nWhen more than one of them is specified, the --icu-data-dir CLI parameter has\nthe highest precedence, then the NODE_ICU_DATA environment variable, then\nthe --with-icu-default-data-dir configure option.
ICU is able to automatically find and load a variety of data formats, but the\ndata must be appropriate for the ICU version, and the file correctly named.\nThe most common name for the data file is icudtX[bl].dat, where X denotes\nthe intended ICU version, and b or l indicates the system's endianness.\nNode.js would fail to load if the expected data file cannot be read from the\nspecified directory. The name of the data file corresponding to the current\nNode.js version can be computed with:
`icudt${process.versions.icu.split('.')[0]}${os.endianness()[0].toLowerCase()}.dat`;\n\nCheck \"ICU Data\" article in the ICU User Guide for other supported formats\nand more details on ICU data in general.
\nThe full-icu npm module can greatly simplify ICU data installation by\ndetecting the ICU version of the running node executable and downloading the\nappropriate data file. After installing the module through npm i full-icu,\nthe data file will be available at ./node_modules/full-icu. This path can be\nthen passed either to NODE_ICU_DATA or --icu-data-dir as shown above to\nenable full Intl support.
This option makes the resulting binary link against ICU statically and include\na full set of ICU data. A binary created this way has no further external\ndependencies and supports all locales, but might be rather large. This is\nthe default behavior if no --with-intl flag is passed. The official binaries\nare also built in this mode.
To verify that ICU is enabled at all (system-icu, small-icu, or\nfull-icu), simply checking the existence of Intl should suffice:
const hasICU = typeof Intl === 'object';\n\nAlternatively, checking for process.versions.icu, a property defined only\nwhen ICU is enabled, works too:
const hasICU = typeof process.versions.icu === 'string';\n\nTo check for support for a non-English locale (i.e. full-icu or\nsystem-icu), Intl.DateTimeFormat can be a good distinguishing factor:
const hasFullICU = (() => {\n try {\n const january = new Date(9e8);\n const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n return spanish.format(january) === 'enero';\n } catch (err) {\n return false;\n }\n})();\n\nFor more verbose tests for Intl support, the following resources may be found\nto be helpful:
Intl support is\nbuilt correctly.ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import and\nexport statements.
The following example of an ES module exports a function:
\n// addTwo.mjs\nfunction addTwo(num) {\n return num + 2;\n}\n\nexport { addTwo };\n\nThe following example of an ES module imports the function from addTwo.mjs:
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n\nNode.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.
\n", "displayName": "Introduction" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "
Node.js has two module systems: CommonJS modules and ECMAScript modules.
\nAuthors can tell Node.js to interpret JavaScript as an ES module via the .mjs\nfile extension, the package.json \"type\" field with a value \"module\",\nor the --input-type flag with a value of \"module\". These are explicit\nmarkers of code being intended to run as an ES module.
Inversely, authors can explicitly tell Node.js to interpret JavaScript as\nCommonJS via the .cjs file extension, the package.json \"type\" field\nwith a value \"commonjs\", or the --input-type flag with a value of\n\"commonjs\".
When code lacks explicit markers for either module system, Node.js will inspect\nthe source code of a module to look for ES module syntax. If such syntax is\nfound, Node.js will run the code as an ES module; otherwise it will run the\nmodule as CommonJS. See Determining module system for more details.
\n" }, { "textRaw": "Packages", "name": "packages", "type": "misc", "desc": "
This section was moved to Modules: Packages.
", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "type": "misc", "modules": [ { "textRaw": "Terminology", "name": "terminology", "type": "module", "desc": "The specifier of an import statement is the string after the from keyword,\ne.g. 'node:path' in import { sep } from 'node:path'. Specifiers are also\nused in export from statements, and as the argument to an import()\nexpression.
There are three types of specifiers:
\nRelative specifiers like './startup.js' or '../config.mjs'. They refer\nto a path relative to the location of the importing file. The file extension\nis always necessary for these.
Bare specifiers like 'some-package' or 'some-package/shuffle'. They can\nrefer to the main entry point of a package by the package name, or a\nspecific feature module within a package prefixed by the package name as per\nthe examples respectively. Including the file extension is only necessary\nfor packages without an \"exports\" field.
Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer\ndirectly and explicitly to a full path.
Bare specifier resolutions are handled by the Node.js module\nresolution and loading algorithm.\nAll other specifier resolutions are always only resolved with\nthe standard relative URL resolution semantics.
\nLike in CommonJS, module files within packages can be accessed by appending a\npath to the package name unless the package's package.json contains an\n\"exports\" field, in which case files within packages can only be accessed\nvia the paths defined in \"exports\".
For details on these package resolution rules that apply to bare specifiers in\nthe Node.js module resolution, see the packages documentation.
", "displayName": "Terminology" }, { "textRaw": "Mandatory file extensions", "name": "mandatory_file_extensions", "type": "module", "desc": "A file extension must be provided when using the import keyword to resolve\nrelative or absolute specifiers. Directory indexes (e.g. './startup/index.js')\nmust also be fully specified.
This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.
ES modules are resolved and cached as URLs. This means that special characters\nmust be percent-encoded, such as # with %23 and ? with %3F.
file:, node:, and data: URL schemes are supported. A specifier like\n'https://example.com/app.js' is not supported natively in Node.js unless using\na custom HTTPS loader.
Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.
import './foo.mjs?query=1'; // loads ./foo.mjs with query of \"?query=1\"\nimport './foo.mjs?query=2'; // loads ./foo.mjs with query of \"?query=2\"\n\nThe volume root may be referenced via /, //, or file:///. Given the\ndifferences between URL and path resolution (such as percent encoding\ndetails), it is recommended to use url.pathToFileURL when importing a path.
data: URLs are supported for importing with the following MIME types:
text/javascript for ES modulesapplication/json for JSONapplication/wasm for Wasmimport 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"' with { type: 'json' };\n\ndata: URLs only resolve bare specifiers for builtin modules\nand absolute specifiers. Resolving\nrelative specifiers does not work because data: is not a\nspecial scheme. For example, attempting to load ./foo\nfrom data:text/javascript,import \"./foo\"; fails to resolve because there\nis no concept of relative resolution for data: URLs.
node: URLs are supported as an alternative means to load Node.js builtin\nmodules. This URL scheme allows for builtin modules to be referenced by valid\nabsolute URL strings.
import fs from 'node:fs/promises';\n\n",
"displayName": "`node:` imports"
}
],
"displayName": "URLs"
}
],
"displayName": "`import` Specifiers"
},
{
"textRaw": "Import attributes",
"name": "import_attributes",
"type": "misc",
"meta": {
"added": [
"v17.1.0",
"v16.14.0"
],
"changes": [
{
"version": [
"v21.0.0",
"v20.10.0",
"v18.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50140",
"description": "Switch from Import Assertions to Import Attributes."
}
]
},
"desc": "Import attributes are an inline syntax for module import\nstatements to pass on more information alongside the module specifier.
\nimport fooData from './foo.json' with { type: 'json' };\n\nconst { default: barData } =\n await import('./bar.json', { with: { type: 'json' } });\n\nNode.js only supports the type attribute, for which it supports the following values:
Attribute type | Needed for |
|---|---|
'json' | JSON modules |
The type: 'json' attribute is mandatory when importing JSON modules.
Built-in modules provide named exports of their public API. A\ndefault export is also provided which is the value of the CommonJS exports.\nThe default export can be used for, among other things, modifying the named\nexports. Named exports of built-in modules are updated only by calling\nmodule.syncBuiltinESMExports().
import EventEmitter from 'node:events';\nconst e = new EventEmitter();\n\nimport { readFile } from 'node:fs';\nreadFile('./foo.txt', (err, source) => {\n if (err) {\n console.error(err);\n } else {\n console.log(source);\n }\n});\n\nimport fs, { readFileSync } from 'node:fs';\nimport { syncBuiltinESMExports } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n\n\n", "displayName": "Built-in modules" }, { "textRaw": "`import()` expressions", "name": "`import()`_expressions", "type": "misc", "desc": "When importing built-in modules, all the named exports (i.e. properties of the module exports object)\nare populated even if they are not individually accessed.\nThis can make initial imports of built-in modules slightly slower compared to loading them with\n
\nrequire()orprocess.getBuiltinModule(), where the module exports object is evaluated immediately,\nbut some of its properties may only be initialized when first accessed individually.
Dynamic import() provides an asynchronous way to import modules. It is\nsupported in both CommonJS and ES modules, and can be used to load both CommonJS\nand ES modules.
An import statement can reference an ES module or a CommonJS module.\nimport statements are permitted only in ES modules, but dynamic import()\nexpressions are supported in CommonJS for loading ES modules.
When importing CommonJS modules, the\nmodule.exports object is provided as the default export. Named exports may be\navailable, provided by static analysis as a convenience for better ecosystem\ncompatibility.
The CommonJS module require currently only supports loading synchronous ES\nmodules (that is, ES modules that do not use top-level await).
See Loading ECMAScript modules using require() for details.
CommonJS modules consist of a module.exports object which can be of any type.
To support this, when importing CommonJS from an ECMAScript module, a namespace\nwrapper for the CommonJS module is constructed, which always provides a\ndefault export key pointing to the CommonJS module.exports value.
In addition, a heuristic static analysis is performed against the source text of\nthe CommonJS module to get a best-effort static list of exports to provide on\nthe namespace from values on module.exports. This is necessary since these\nnamespaces must be constructed prior to the evaluation of the CJS module.
These CommonJS namespace objects also provide the default export as a\n'module.exports' named export, in order to unambiguously indicate that their\nrepresentation in CommonJS uses this value, and not the namespace value. This\nmirrors the semantics of the handling of the 'module.exports' export name in\nrequire(esm) interop support.
When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:
\nimport { default as cjs } from 'cjs';\n// Identical to the above\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n// <module.exports>\n// true\n\nThis Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n// [Module] { default: <module.exports>, 'module.exports': <module.exports> }\n// true\n\nFor better compatibility with existing usage in the JS ecosystem, Node.js\nin addition attempts to determine the CommonJS named exports of every imported\nCommonJS module to provide them as separate ES module exports using a static\nanalysis process.
\nFor example, consider a CommonJS module written:
\n// cjs.cjs\nexports.name = 'exported';\n\nThe preceding module supports named imports in ES modules:
\nimport { name } from './cjs.cjs';\nconsole.log(name);\n// Prints: 'exported'\n\nimport cjs from './cjs.cjs';\nconsole.log(cjs);\n// Prints: { name: 'exported' }\n\nimport * as m from './cjs.cjs';\nconsole.log(m);\n// Prints:\n// [Module] {\n// default: { name: 'exported' },\n// 'module.exports': { name: 'exported' },\n// name: 'exported'\n// }\n\nAs can be seen from the last example of the Module Namespace Exotic Object being\nlogged, the name export is copied off of the module.exports object and set\ndirectly on the ES module namespace when the module is imported.
Live binding updates or new exports added to module.exports are not detected\nfor these named exports.
The detection of named exports is based on common syntax patterns but does not\nalways correctly detect named exports. In these cases, using the default\nimport form described above can be a better option.
\nNamed exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See merve for the exact\nsemantics implemented.
", "displayName": "CommonJS Namespaces" }, { "textRaw": "Differences between ES modules and CommonJS", "name": "differences_between_es_modules_and_commonjs", "type": "module", "modules": [ { "textRaw": "No `require`, `exports`, or `module.exports`", "name": "no_`require`,_`exports`,_or_`module.exports`", "type": "module", "desc": "In most cases, the ES module import can be used to load CommonJS modules.
If needed, a require function can be constructed within an ES module using\nmodule.createRequire().
These CommonJS variables are not available in ES modules.
\n__filename and __dirname use cases can be replicated via\nimport.meta.filename and import.meta.dirname.
Addons are not currently supported with ES module imports.
\nThey can instead be loaded with module.createRequire() or\nprocess.dlopen.
To replace require.main === module, there is the import.meta.main API.
Relative resolution can be handled via new URL('./local', import.meta.url).
For a complete require.resolve replacement, there is the\nimport.meta.resolve API.
Alternatively module.createRequire() can be used.
NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.
require.extensions is not used by import. Module customization hooks can\nprovide a replacement.
require.cache is not used by import as the ES module loader has its own\nseparate cache.
", "displayName": "No `require.cache`" } ], "displayName": "Differences between ES modules and CommonJS" } ], "displayName": "Interoperability with CommonJS" }, { "textRaw": "JSON modules", "name": "json_modules", "type": "misc", "meta": { "changes": [ { "version": [ "v23.1.0", "v22.12.0", "v20.18.3", "v18.20.5" ], "pr-url": "https://github.com/nodejs/node/pull/55333", "description": "JSON modules are no longer experimental." } ] }, "desc": "
JSON files can be referenced by import:
import packageConfig from './package.json' with { type: 'json' };\n\nThe with { type: 'json' } syntax is mandatory; see Import Attributes.
The imported JSON only exposes a default export. There is no support for named\nexports. A cache entry is created in the CommonJS cache to avoid duplication.\nThe same object is returned in CommonJS if the JSON module has already been\nimported from the same path.
", "displayName": "JSON modules" }, { "textRaw": "Wasm modules", "name": "wasm_modules", "type": "misc", "meta": { "changes": [ { "version": [ "v24.5.0", "v22.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/57038", "description": "Wasm modules no longer require the `--experimental-wasm-modules` flag." } ] }, "desc": "
Importing both WebAssembly module instances and WebAssembly source phase\nimports is supported.
\nBoth of these integrations are in line with the\nES Module Integration Proposal for WebAssembly.
", "modules": [ { "textRaw": "Wasm Source Phase Imports", "name": "wasm_source_phase_imports", "type": "module", "meta": { "added": [ "v24.0.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate", "desc": "The Source Phase Imports proposal allows the import source keyword\ncombination to import a WebAssembly.Module object directly, instead of getting\na module instance already instantiated with its dependencies.
This is useful when needing custom instantiations for Wasm, while still\nresolving and loading it through the ES module integration.
\nFor example, to create multiple instances of a module, or to pass custom imports\ninto a new instance of library.wasm:
import source libraryModule from './library.wasm';\n\nconst instance1 = await WebAssembly.instantiate(libraryModule, importObject1);\n\nconst instance2 = await WebAssembly.instantiate(libraryModule, importObject2);\n\nIn addition to the static source phase, there is also a dynamic variant of the\nsource phase via the import.source dynamic phase import syntax:
const dynamicLibrary = await import.source('./library.wasm');\n\nconst instance = await WebAssembly.instantiate(dynamicLibrary, importObject);\n",
"displayName": "Wasm Source Phase Imports"
},
{
"textRaw": "JavaScript String Builtins",
"name": "javascript_string_builtins",
"type": "module",
"meta": {
"added": [
"v24.5.0",
"v22.19.0"
],
"changes": []
},
"stability": 1.2,
"stabilityText": "Release candidate",
"desc": "When importing WebAssembly modules, the\nWebAssembly JS String Builtins Proposal is automatically enabled through the\nESM Integration. This allows WebAssembly modules to directly use efficient\ncompile-time string builtins from the wasm:js-string namespace.
For example, the following Wasm module exports a string getLength function using\nthe wasm:js-string length builtin:
(module\n ;; Compile-time import of the string length builtin.\n (import \"wasm:js-string\" \"length\" (func $string_length (param externref) (result i32)))\n\n ;; Define getLength, taking a JS value parameter assumed to be a string,\n ;; calling string length on it and returning the result.\n (func $getLength (param $str externref) (result i32)\n local.get $str\n call $string_length\n )\n\n ;; Export the getLength function.\n (export \"getLength\" (func $get_length))\n)\n\nimport { getLength } from './string-len.wasm';\ngetLength('foo'); // Returns 3.\n\nWasm builtins are compile-time imports that are linked during module compilation\nrather than during instantiation. They do not behave like normal module graph\nimports and they cannot be inspected via WebAssembly.Module.imports(mod)\nor virtualized unless recompiling the module using the direct\nWebAssembly.compile API with string builtins disabled.
Importing a module in the source phase before it has been instantiated will also\nuse the compile-time builtins automatically:
\nimport source mod from './string-len.wasm';\nconst { exports: { getLength } } = await WebAssembly.instantiate(mod, {});\ngetLength('foo'); // Also returns 3.\n",
"displayName": "JavaScript String Builtins"
},
{
"textRaw": "Wasm Instance Phase Imports",
"name": "wasm_instance_phase_imports",
"type": "module",
"stability": 1.1,
"stabilityText": "Active development",
"desc": "Instance imports allow any .wasm files to be imported as normal modules,\nsupporting their module imports in turn.
For example, an index.js containing:
import * as M from './library.wasm';\nconsole.log(M);\n\nexecuted under:
\nnode index.mjs\n\nwould provide the exports interface for the instantiation of library.wasm.
When importing WebAssembly module instances, they cannot use import module\nnames or import/export names that start with reserved prefixes:
\nwasm-js: - reserved in all module import names, module names and export\nnames.wasm: - reserved in module import names and export names (imported module\nnames are allowed in order to support future builtin polyfills).Importing a module using the above reserved names will throw a\nWebAssembly.LinkError.
", "displayName": "Reserved Wasm Namespaces" } ], "displayName": "Wasm modules" }, { "textRaw": "Top-level `await`", "name": "top-level_`await`", "type": "misc", "meta": { "added": [ "v14.8.0" ], "changes": [] }, "desc": "
The await keyword may be used in the top level body of an ECMAScript module.
Assuming an a.mjs with
export const five = await Promise.resolve(5);\n\nAnd a b.mjs with
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n\nnode b.mjs # works\n\nIf a top level await expression never resolves, the node process will exit\nwith a 13 status code.
import { spawn } from 'node:child_process';\nimport { execPath } from 'node:process';\n\nspawn(execPath, [\n '--input-type=module',\n '--eval',\n // Never-resolving Promise:\n 'await new Promise(() => {})',\n]).once('exit', (code) => {\n console.log(code); // Logs `13`\n});\n\n", "displayName": "Top-level `await`" }, { "textRaw": "Loaders", "name": "loaders", "type": "misc", "desc": "
The former Loaders documentation is now at\nModules: Customization hooks.
", "displayName": "Loaders" }, { "textRaw": "Resolution and loading algorithm", "name": "resolution_and_loading_algorithm", "type": "misc", "modules": [ { "textRaw": "Features", "name": "features", "type": "module", "desc": "The default resolver has the following properties:
\nThe default loader has the following properties
\nnode: URLsdata: URLsfile: module loadingfile: loading\n(supports only .cjs, .js, and .mjs)The algorithm to load an ES module specifier is given through the\nESM_RESOLVE method below. It returns the resolved URL for a\nmodule specifier relative to a parentURL.
\nThe resolution algorithm determines the full resolved URL for a module\nload, along with its suggested module format. The resolution algorithm\ndoes not determine whether the resolved URL protocol can be loaded,\nor whether the file extensions are permitted, instead these validations\nare applied by Node.js during the load phase\n(for example, if it was asked to load a URL that has a protocol that is\nnot file:, data: or node:.
The algorithm also tries to determine the format of the file based\non the extension (see ESM_FILE_FORMAT algorithm below). If it does\nnot recognize the file extension (eg if it is not .mjs, .cjs, or\n.json), then a format of undefined is returned,\nwhich will throw during the load phase.
The algorithm to determine the module format of a resolved URL is\nprovided by ESM_FILE_FORMAT, which returns the unique module\nformat for any file. The \"module\" format is returned for an ECMAScript\nModule, while the \"commonjs\" format is used to indicate loading through the\nlegacy CommonJS loader. Additional formats such as \"addon\" can be extended in\nfuture updates.
\nIn the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.
\ndefaultConditions is the conditional environment name array,\n[\"node\", \"import\"].
The resolver can throw the following errors:
\nESM_RESOLVE(specifier, parentURL)
\n\n\n\n
\n- Let resolved be undefined.
\n- If specifier is a valid URL, then\n
\n\n
\n- Set resolved to the result of parsing and reserializing\nspecifier as a URL.
\n- Otherwise, if specifier starts with \"/\", \"./\", or \"../\", then\n
\n\n
\n- Set resolved to the URL resolution of specifier relative to\nparentURL.
\n- Otherwise, if specifier starts with \"#\", then\n
\n\n
\n- Set resolved to the result of\nPACKAGE_IMPORTS_RESOLVE(specifier,\nparentURL, defaultConditions).
\n- Otherwise,\n
\n\n
\n- Note: specifier is now a bare specifier.
\n- Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
\n- Let format be undefined.
\n- If resolved is a \"file:\" URL, then\n
\n\n
\n- If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2F\"\nand \"%5C\" respectively), then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If the file at resolved is a directory, then\n
\n\n
\n- Throw an Unsupported Directory Import error.
\n- If the file at resolved does not exist, then\n
\n\n
\n- Throw a Module Not Found error.
\n- Set resolved to the real path of resolved, maintaining the\nsame URL querystring and fragment components.
\n- Set format to the result of ESM_FILE_FORMAT(resolved).
\n- Otherwise,\n
\n\n
\n- Set format the module format of the content type associated with the\nURL resolved.
\n- Return format and resolved to the loading phase
\n
PACKAGE_RESOLVE(packageSpecifier, parentURL)
\n\n\n\n
\n- Let packageName be undefined.
\n- If packageSpecifier is an empty string, then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If packageSpecifier is a Node.js builtin module name, then\n
\n\n
\n- Return the string \"node:\" concatenated with packageSpecifier.
\n- If packageSpecifier does not start with \"@\", then\n
\n\n
\n- Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
\n- Otherwise,\n
\n\n
\n- If packageSpecifier does not contain a \"/\" separator, then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
\n- If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
\n- Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
\n- If selfUrl is not undefined, return selfUrl.
\n- While parentURL is not the file system root,\n
\n\n
\n- Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageName, relative to parentURL.
\n- Set parentURL to the parent folder URL of parentURL.
\n- If the folder at packageURL does not exist, then\n
\n\n
\n- Continue the next loop iteration.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is not null and pjson.exports is not null or\nundefined, then\n
\n\n
\n- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports, defaultConditions).
\n- Otherwise, if packageSubpath is equal to \".\", then\n
\n\n
\n- If pjson.main is a string, then\n
\n\n
\n- Return the URL resolution of main in packageURL.
\n- Otherwise,\n
\n\n
\n- Return the URL resolution of packageSubpath in packageURL.
\n- Throw a Module Not Found error.
\n
PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)
\n\n\n\n
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
\n- If packageURL is null, then\n
\n\n
\n- Return undefined.
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson is null or if pjson.exports is null or\nundefined, then\n
\n\n
\n- Return undefined.
\n- If pjson.name is equal to packageName, then\n
\n\n
\n- Return the result of PACKAGE_EXPORTS_RESOLVE(packageURL,\npackageSubpath, pjson.exports, defaultConditions).
\n- Otherwise, return undefined.
\n
PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)
\nNote: This function is directly invoked by the CommonJS resolution algorithm.
\n\n\n\n
\n- If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
\n- If subpath is equal to \".\", then\n
\n\n
\n- Let mainExport be undefined.
\n- If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
\n\n
\n- Set mainExport to exports.
\n- Otherwise if exports is an Object containing a \".\" property, then\n
\n\n
\n- Set mainExport to exports[\".\"].
\n- If mainExport is not undefined, then\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, null, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
\n\n
\n- Assert: subpath begins with \"./\".
\n- Let resolved be the result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nsubpath, exports, packageURL, false, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Throw a Package Path Not Exported error.
\n
PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)
\nNote: This function is directly invoked by the CommonJS resolution algorithm.
\n\n\n\n
\n- Assert: specifier begins with \"#\".
\n- If specifier is exactly equal to \"#\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(parentURL).
\n- If packageURL is not null, then\n
\n\n
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- If pjson.imports is a non-null Object, then\n
\n\n
\n- Let resolved be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(\nspecifier, pjson.imports, packageURL, true, conditions).
\n- If resolved is not null or undefined, return resolved.
\n- Throw a Package Import Not Defined error.
\n
PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)
\n\n\n\n
\n- If matchKey ends in \"/\", then\n
\n\n
\n- Throw an Invalid Module Specifier error.
\n- If matchKey is a key of matchObj and does not contain \"*\", then\n
\n\n
\n- Let target be the value of matchObj[matchKey].
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, null, isImports, conditions).
\n- Let expansionKeys be the list of keys of matchObj containing only a\nsingle \"*\", sorted by the sorting function PATTERN_KEY_COMPARE\nwhich orders in descending order of specificity.
\n- For each key expansionKey in expansionKeys, do\n
\n\n
\n- Let patternBase be the substring of expansionKey up to but excluding\nthe first \"*\" character.
\n- If matchKey starts with but is not equal to patternBase, then\n
\n\n
\n- Let patternTrailer be the substring of expansionKey from the\nindex after the first \"*\" character.
\n- If patternTrailer has zero length, or if matchKey ends with\npatternTrailer and the length of matchKey is greater than or\nequal to the length of expansionKey, then\n
\n\n
\n- Let target be the value of matchObj[expansionKey].
\n- Let patternMatch be the substring of matchKey starting at the\nindex of the length of patternBase up to the length of\nmatchKey minus the length of patternTrailer.
\n- Return the result of PACKAGE_TARGET_RESOLVE(packageURL,\ntarget, patternMatch, isImports, conditions).
\n- Return null.
\n
PATTERN_KEY_COMPARE(keyA, keyB)
\n\n\n\n
\n- Assert: keyA contains only a single \"*\".
\n- Assert: keyB contains only a single \"*\".
\n- Let baseLengthA be the index of \"*\" in keyA.
\n- Let baseLengthB be the index of \"*\" in keyB.
\n- If baseLengthA is greater than baseLengthB, return -1.
\n- If baseLengthB is greater than baseLengthA, return 1.
\n- If the length of keyA is greater than the length of keyB, return -1.
\n- If the length of keyB is greater than the length of keyA, return 1.
\n- Return 0.
\n
PACKAGE_TARGET_RESOLVE(packageURL, target, patternMatch,\nisImports, conditions)
\n\n\n\n
\n- If target is a String, then\n
\n\n
\n- If target does not start with \"./\", then\n
\n\n
\n- If isImports is false, or if target starts with \"../\" or\n\"/\", or if target is a valid URL, then\n
\n\n
\n- Throw an Invalid Package Target error.
\n- If patternMatch is a String, then\n
\n\n
\n- Return PACKAGE_RESOLVE(target with every instance of \"*\"\nreplaced by patternMatch, packageURL + \"/\").
\n- Return PACKAGE_RESOLVE(target, packageURL + \"/\").
\n- If target split on \"/\" or \"\\\" contains any \"\", \".\", \"..\",\nor \"node_modules\" segments after the first \".\" segment, case\ninsensitive and including percent encoded variants, throw an Invalid\nPackage Target error.
\n- Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
\n- Assert: packageURL is contained in resolvedTarget.
\n- If patternMatch is null, then\n
\n\n
\n- Return resolvedTarget.
\n- If patternMatch split on \"/\" or \"\\\" contains any \"\", \".\",\n\"..\", or \"node_modules\" segments, case insensitive and including\npercent encoded variants, throw an Invalid Module Specifier error.
\n- Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with patternMatch.
\n- Otherwise, if target is a non-null Object, then\n
\n\n
\n- If target contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
\n- For each property p of target, in object insertion order as,\n
\n\n
\n- If p equals \"default\" or conditions contains an entry for p,\nthen\n
\n\n
\n- Let targetValue be the value of the p property in target.
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, patternMatch, isImports,\nconditions).
\n- If resolved is equal to undefined, continue the loop.
\n- Return resolved.
\n- Return undefined.
\n- Otherwise, if target is an Array, then\n
\n\n
\n- If _target.length is zero, return null.
\n- For each item targetValue in target, do\n
\n\n
\n- Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, patternMatch, isImports,\nconditions), continuing the loop on any Invalid Package Target\nerror.
\n- If resolved is undefined, continue the loop.
\n- Return resolved.
\n- Return or throw the last fallback resolution null return or error.
\n- Otherwise, if target is null, return null.
\n- Otherwise throw an Invalid Package Target error.
\n
ESM_FILE_FORMAT(url)
\n\n\n\n
\n- Assert: url corresponds to an existing file.
\n- If url ends in \".mjs\", then\n
\n\n
\n- Return \"module\".
\n- If url ends in \".cjs\", then\n
\n\n
\n- Return \"commonjs\".
\n- If url ends in \".json\", then\n
\n\n
\n- Return \"json\".
\n- If url ends in\n\".wasm\", then\n
\n\n
\n- Return \"wasm\".
\n- If
\n--experimental-addon-modulesis enabled and url ends in\n\".node\", then\n\n
\n- Return \"addon\".
\n- Let packageURL be the result of LOOKUP_PACKAGE_SCOPE(url).
\n- Let pjson be the result of READ_PACKAGE_JSON(packageURL).
\n- Let packageType be null.
\n- If pjson?.type is \"module\" or \"commonjs\", then\n
\n\n
\n- Set packageType to pjson.type.
\n- If url ends in \".js\", then\n
\n\n
\n- If packageType is not null, then\n
\n\n
\n- Return packageType.
\n- If the result of DETECT_MODULE_SYNTAX(source) is true, then\n
\n\n
\n- Return \"module\".
\n- Return \"commonjs\".
\n- If url does not have any extension, then\n
\n\n
\n- If packageType is \"module\" and the file at url contains the\n\"application/wasm\" content type header for a WebAssembly module, then\n
\n\n
\n- Return \"wasm\".
\n- If packageType is not null, then\n
\n\n
\n- Return packageType.
\n- If the result of DETECT_MODULE_SYNTAX(source) is true, then\n
\n\n
\n- Return \"module\".
\n- Return \"commonjs\".
\n- Return undefined (will throw during load phase).
\n
LOOKUP_PACKAGE_SCOPE(url)
\n\n\n\n
\n- Let scopeURL be url.
\n- While scopeURL is not the file system root,\n
\n\n
\n- Set scopeURL to the parent URL of scopeURL.
\n- If scopeURL ends in a \"node_modules\" path segment, return null.
\n- Let pjsonURL be the resolution of \"package.json\" within\nscopeURL.
\n- if the file at pjsonURL exists, then\n
\n\n
\n- Return scopeURL.
\n- Return null.
\n
READ_PACKAGE_JSON(packageURL)
\n\n\n\n
\n- Let pjsonURL be the resolution of \"package.json\" within packageURL.
\n- If the file at pjsonURL does not exist, then\n
\n\n
\n- Return null.
\n- If the file at packageURL does not parse as valid JSON, then\n
\n\n
\n- Throw an Invalid Package Configuration error.
\n- Return the parsed JSON source of the file at pjsonURL.
\n
DETECT_MODULE_SYNTAX(source)
\n\n", "displayName": "Resolution Algorithm Specification" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "type": "module", "desc": "\n
\n- Parse source as an ECMAScript module.
\n- If the parse is successful, then\n
\n\n
\n- If source contains top-level
\nawait, staticimportorexport\nstatements, orimport.meta, return true.- If source contains a top-level lexical declaration (
\nconst,let,\norclass) of any of the CommonJS wrapper variables (require,\nexports,module,__filename, or__dirname) then return true.- Return false.
\n
Module customization hooks provide a mechanism for customizing the ESM\nspecifier resolution algorithm. An example that provides CommonJS-style\nresolution for ESM specifiers is commonjs-extension-resolution-loader.
", "displayName": "Customizing ESM specifier resolution algorithm" } ], "displayName": "Resolution and loading algorithm" } ], "properties": [ { "textRaw": "Type: {Object}", "name": "meta", "type": "Object", "desc": "The import.meta meta property is an Object that contains the following\nproperties. It is only supported in ES modules.
This is the same as the path.dirname() of the import.meta.filename.
\n", "shortDesc": "The directory name of the current module." }, { "textRaw": "Type: {string} The full absolute path and filename of the current module, with symlinks resolved.", "name": "filename", "type": "string", "meta": { "added": [ "v21.2.0", "v20.11.0" ], "changes": [ { "version": [ "v24.0.0", "v22.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/58011", "description": "This property is no longer experimental." } ] }, "desc": "Caveat: only present on
\nfile:modules.
This is the same as the url.fileURLToPath() of the import.meta.url.
\n", "shortDesc": "The full absolute path and filename of the current module, with symlinks resolved." }, { "textRaw": "Type: {string} The absolute `file:` URL of the module.", "name": "url", "type": "string", "desc": "Caveat only local modules support this property. Modules not using the\n
\nfile:protocol will not provide it.
This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.
\nThis enables useful patterns such as relative file loading:
\nimport { readFileSync } from 'node:fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n",
"shortDesc": "The absolute `file:` URL of the module."
},
{
"textRaw": "Type: {boolean} `true` when the current module is the entry point of the current process; `false` otherwise.",
"name": "main",
"type": "boolean",
"meta": {
"added": [
"v24.2.0",
"v22.18.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Early development",
"desc": "Equivalent to require.main === module in CommonJS.
Analogous to Python's __name__ == \"__main__\".
export function foo() {\n return 'Hello, world';\n}\n\nfunction main() {\n const message = foo();\n console.log(message);\n}\n\nif (import.meta.main) main();\n// `foo` can be imported from another module without possible side-effects from `main`\n",
"shortDesc": "`true` when the current module is the entry point of the current process; `false` otherwise."
}
],
"methods": [
{
"textRaw": "`import.meta.resolve(specifier)`",
"name": "resolve",
"type": "method",
"meta": {
"added": [
"v13.9.0",
"v12.16.2"
],
"changes": [
{
"version": [
"v20.6.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49028",
"description": "No longer behind `--experimental-import-meta-resolve` CLI flag, except for the non-standard `parentURL` parameter."
},
{
"version": [
"v20.6.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49038",
"description": "This API no longer throws when targeting `file:` URLs that do not map to an existing file on the local FS."
},
{
"version": [
"v20.0.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/44710",
"description": "This API now returns a string synchronously instead of a Promise."
},
{
"version": [
"v16.2.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38587",
"description": "Add support for WHATWG `URL` object to `parentURL` parameter."
}
]
},
"stability": 1.2,
"stabilityText": "Release candidate",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string} The module specifier to resolve relative to the current module.",
"name": "specifier",
"type": "string",
"desc": "The module specifier to resolve relative to the current module."
}
],
"return": {
"textRaw": "Returns: {string} The absolute URL string that the specifier would resolve to.",
"name": "return",
"type": "string",
"desc": "The absolute URL string that the specifier would resolve to."
}
}
],
"desc": "import.meta.resolve is a module-relative resolution function scoped to\neach module, returning the URL string.
const dependencyAsset = import.meta.resolve('component-lib/asset.css');\n// file:///app/node_modules/component-lib/asset.css\nimport.meta.resolve('./dep.js');\n// file:///app/dep.js\n\nAll features of the Node.js module resolution are supported. Dependency\nresolutions are subject to the permitted exports resolutions within the package.
\nCaveats:
\nrequire.resolve.Non-standard API:
\nWhen using the --experimental-import-meta-resolve flag, that function accepts\na second argument:
parent <string> | <URL> An optional absolute parent module URL to resolve from. Default: import.meta.urlA package is a folder tree described by a package.json file. The package\nconsists of the folder containing the package.json file and all subfolders\nuntil the next folder containing another package.json file, or a folder\nnamed node_modules.
This page provides guidance for package authors writing package.json files\nalong with a reference for the package.json fields defined by Node.js.
Node.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements or import()\nexpressions:
Files with an .mjs extension.
Files with a .js extension when the nearest parent package.json file\ncontains a top-level \"type\" field with a value of \"module\".
Strings passed in as an argument to --eval, or piped to node via STDIN,\nwith the flag --input-type=module.
Code containing syntax only successfully parsed as ES modules, such as\nimport or export statements or import.meta, with no explicit marker of\nhow it should be interpreted. Explicit markers are .mjs or .cjs\nextensions, package.json \"type\" fields with either \"module\" or\n\"commonjs\" values, or the --input-type flag. Dynamic import()\nexpressions are supported in either CommonJS or ES modules and would not force\na file to be treated as an ES module. See Syntax detection.
Node.js will treat the following as CommonJS when passed to node as the\ninitial input, or when referenced by import statements or import()\nexpressions:
Files with a .cjs extension.
Files with a .js extension when the nearest parent package.json file\ncontains a top-level field \"type\" with a value of \"commonjs\".
Strings passed in as an argument to --eval or --print, or piped to node\nvia STDIN, with the flag --input-type=commonjs.
Files with a .js extension with no parent package.json file or where the\nnearest parent package.json file lacks a type field, and where the code\ncan evaluate successfully as CommonJS. In other words, Node.js tries to run\nsuch \"ambiguous\" files as CommonJS first, and will retry evaluating them as ES\nmodules if the evaluation as CommonJS fails because the parser found ES module\nsyntax.
Writing ES module syntax in \"ambiguous\" files incurs a performance cost, and\ntherefore it is encouraged that authors be explicit wherever possible. In\nparticular, package authors should always include the \"type\" field in\ntheir package.json files, even in packages where all sources are CommonJS.\nBeing explicit about the type of the package will future-proof the package in\ncase the default type of Node.js ever changes, and it will also make things\neasier for build tools and loaders to determine how the files in the package\nshould be interpreted.
Node.js will inspect the source code of ambiguous input to determine whether it\ncontains ES module syntax; if such syntax is detected, the input will be treated\nas an ES module.
\nAmbiguous input is defined as:
\n.js extension or no extension; and either no controlling\npackage.json file or one that lacks a type field.--eval or STDIN) when --input-typeis not specified.ES module syntax is defined as syntax that would throw when evaluated as\nCommonJS. This includes the following:
\nimport statements (but not import() expressions, which are valid in\nCommonJS).export statements.import.meta references.await at the top level of a module.require, module,\nexports, __dirname, __filename).Node.js has two types of module resolution and loading, chosen based on how the module is requested.
\nWhen a module is requested via require() (available by default in CommonJS modules,\nand can be dynamically generated using createRequire() in both CommonJS and ES Modules):
require() supports folders as modules.require() will try to add\nextensions (.js, .json, and finally .node) and then attempt to resolve\nfolders as modules..json files are treated as JSON text files..node files are interpreted as compiled addon modules loaded with process.dlopen()..ts, .mts and .cts files are treated as TypeScript text files.require() can only be used to load ECMAScript modules from CommonJS modules if\nthe ECMAScript module and its dependencies are synchronous\n(i.e. they do not contain top-level await).When a module is requested via static import statements (only available in ES Modules)\nor import() expressions (available in both CommonJS and ES Modules):
import/import() does not support folders as modules,\ndirectory indexes (e.g. './startup/index.js') must be fully specified.file:// and data: URLs as specifiers by default..json files are treated as JSON text files. When importing JSON modules,\nan import type attribute is required (e.g.\nimport json from './data.json' with { type: 'json' })..node files are interpreted as compiled addon modules loaded with\nprocess.dlopen(), if --experimental-addon-modules is enabled..ts, .mts and .cts files are treated as TypeScript text files..js, .mjs, and .cjs extensions for JavaScript text\nfiles..wasm files are treated as WebAssembly modules.ERR_UNKNOWN_FILE_EXTENSION error.\nAdditional file extensions can be facilitated via customization hooks.import/import() can be used to load JavaScript CommonJS modules.\nSuch modules are passed through merve to try to identify named\nexports, which are available if they can be determined through static analysis.Regardless of how a module is requested, the resolution and loading process can be customized\nusing customization hooks.
", "displayName": "Module resolution and loading" }, { "textRaw": "`package.json` and file extensions", "name": "`package.json`_and_file_extensions", "type": "module", "desc": "Within a package, the package.json \"type\" field defines how\nNode.js should interpret .js files. If a package.json file does not have a\n\"type\" field, .js files are treated as CommonJS.
A package.json \"type\" value of \"module\" tells Node.js to interpret .js\nfiles within that package as using ES module syntax.
The \"type\" field applies not only to initial entry points (node my-app.js)\nbut also to files referenced by import statements and import() expressions.
// my-app.js, treated as an ES module because there is a package.json\n// file in the same folder with \"type\": \"module\".\n\nimport './startup/init.js';\n// Loaded as ES module since ./startup contains no package.json file,\n// and therefore inherits the \"type\" value from one level up.\n\nimport 'commonjs-package';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nimport './node_modules/commonjs-package/index.js';\n// Loaded as CommonJS since ./node_modules/commonjs-package/package.json\n// lacks a \"type\" field or contains \"type\": \"commonjs\".\n\nFiles ending with .mjs are always loaded as ES modules regardless of\nthe nearest parent package.json.
Files ending with .cjs are always loaded as CommonJS regardless of the\nnearest parent package.json.
import './legacy-file.cjs';\n// Loaded as CommonJS since .cjs is always loaded as CommonJS.\n\nimport 'commonjs-package/src/index.mjs';\n// Loaded as ES module since .mjs is always loaded as ES module.\n\nThe .mjs and .cjs extensions can be used to mix types within the same\npackage:
Within a \"type\": \"module\" package, Node.js can be instructed to\ninterpret a particular file as CommonJS by naming it with a .cjs\nextension (since both .js and .mjs files are treated as ES modules within\na \"module\" package).
Within a \"type\": \"commonjs\" package, Node.js can be instructed to\ninterpret a particular file as an ES module by naming it with an .mjs\nextension (since both .js and .cjs files are treated as CommonJS within a\n\"commonjs\" package).
Strings passed in as an argument to --eval (or -e), or piped to node via\nSTDIN, are treated as ES modules when the --input-type=module flag\nis set.
node --input-type=module --eval \"import { sep } from 'node:path'; console.log(sep);\"\n\necho \"import { sep } from 'node:path'; console.log(sep);\" | node --input-type=module\n\nFor completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.
In a package's package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". Both fields apply to both ES module\nand CommonJS module entry points.
The \"main\" field is supported in all versions of Node.js, but its\ncapabilities are limited: it only defines the main entry point of the package.
The \"exports\" provides a modern alternative to \"main\" allowing\nmultiple entry points to be defined, conditional entry resolution support\nbetween environments, and preventing any other entry points besides those\ndefined in \"exports\". This encapsulation allows module authors to\nclearly define the public interface for their package.
For new packages targeting the currently supported versions of Node.js, the\n\"exports\" field is recommended. For packages supporting Node.js 10 and\nbelow, the \"main\" field is required. If both \"exports\" and\n\"main\" are defined, the \"exports\" field takes precedence over\n\"main\" in supported versions of Node.js.
Conditional exports can be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import. For more information about supporting\nboth CommonJS and ES modules in a single package please consult\nthe dual CommonJS/ES module packages section.
Existing packages introducing the \"exports\" field will prevent consumers\nof the package from using any entry points that are not defined, including the\npackage.json (e.g. require('your-package/package.json')). This will\nlikely be a breaking change.
To make the introduction of \"exports\" non-breaking, ensure that every\npreviously supported entry point is exported. It is best to explicitly specify\nentry points so that the package's public API is well-defined. For example,\na project that previously exported main, lib,\nfeature, and the package.json could use the following package.exports:
{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./lib\": \"./lib/index.js\",\n \"./lib/index\": \"./lib/index.js\",\n \"./lib/index.js\": \"./lib/index.js\",\n \"./feature\": \"./feature/index.js\",\n \"./feature/index\": \"./feature/index.js\",\n \"./feature/index.js\": \"./feature/index.js\",\n \"./package.json\": \"./package.json\"\n }\n}\n\nAlternatively a project could choose to export entire folders both with and\nwithout extensioned subpaths using export patterns:
\n{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./lib\": \"./lib/index.js\",\n \"./lib/*\": \"./lib/*.js\",\n \"./lib/*.js\": \"./lib/*.js\",\n \"./feature\": \"./feature/index.js\",\n \"./feature/*\": \"./feature/*.js\",\n \"./feature/*.js\": \"./feature/*.js\",\n \"./package.json\": \"./package.json\"\n }\n}\n\nWith the above providing backwards-compatibility for any minor package versions,\na future major change for the package can then properly restrict the exports\nto only the specific feature exports exposed:
\n{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./lib/index.js\",\n \"./feature/*.js\": \"./feature/*.js\",\n \"./feature/internal/*\": null\n }\n}\n",
"modules": [
{
"textRaw": "Main entry point export",
"name": "main_entry_point_export",
"type": "module",
"desc": "When writing a new package, it is recommended to use the \"exports\" field:
{\n \"exports\": \"./index.js\"\n}\n\nWhen the \"exports\" field is defined, all subpaths of the package are\nencapsulated and no longer available to importers. For example,\nrequire('pkg/subpath.js') throws an ERR_PACKAGE_PATH_NOT_EXPORTED\nerror.
This encapsulation of exports provides more reliable guarantees\nabout package interfaces for tools and when handling semver upgrades for a\npackage. It is not a strong encapsulation since a direct require of any\nabsolute subpath of the package such as\nrequire('/path/to/node_modules/pkg/subpath.js') will still load subpath.js.
All currently supported versions of Node.js and modern build tools support the\n\"exports\" field. For projects using an older version of Node.js or a related\nbuild tool, compatibility can be achieved by including the \"main\" field\nalongside \"exports\" pointing to the same module:
{\n \"main\": \"./index.js\",\n \"exports\": \"./index.js\"\n}\n",
"displayName": "Main entry point export"
},
{
"textRaw": "Subpath exports",
"name": "subpath_exports",
"type": "module",
"meta": {
"added": [
"v12.7.0"
],
"changes": []
},
"desc": "When using the \"exports\" field, custom subpaths can be defined along\nwith the main entry point by treating the main entry point as the\n\".\" subpath:
{\n \"exports\": {\n \".\": \"./index.js\",\n \"./submodule.js\": \"./src/submodule.js\"\n }\n}\n\nNow only the defined subpath in \"exports\" can be imported by a consumer:
import submodule from 'es-module-package/submodule.js';\n// Loads ./node_modules/es-module-package/src/submodule.js\n\nWhile other subpaths will error:
\nimport submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n",
"modules": [
{
"textRaw": "Extensions in subpaths",
"name": "extensions_in_subpaths",
"type": "module",
"desc": "Package authors should provide either extensioned (import 'pkg/subpath.js') or\nextensionless (import 'pkg/subpath') subpaths in their exports. This ensures\nthat there is only one subpath for each exported module so that all dependents\nimport the same consistent specifier, keeping the package contract clear for\nconsumers and simplifying package subpath completions.
Traditionally, packages tended to use the extensionless style, which has the\nbenefits of readability and of masking the true path of the file within the\npackage.
\nWith import maps now providing a standard for package resolution in browsers\nand other JavaScript runtimes, using the extensionless style can result in\nbloated import map definitions. Explicit file extensions can avoid this issue by\nenabling the import map to utilize a packages folder mapping to map multiple\nsubpaths where possible instead of a separate map entry per package subpath\nexport. This also mirrors the requirement of using the full specifier path\nin relative and absolute import specifiers.
", "displayName": "Extensions in subpaths" }, { "textRaw": "Path Rules and Validation for Export Targets", "name": "path_rules_and_validation_for_export_targets", "type": "module", "desc": "When defining paths as targets in the \"exports\" field, Node.js enforces\nseveral rules to ensure security, predictability, and proper encapsulation.\nUnderstanding these rules is crucial for authors publishing packages.
All target paths in the \"exports\" map (the values associated with export\nkeys) must be relative URL strings starting with ./.
// package.json\n{\n \"name\": \"my-package\",\n \"exports\": {\n \".\": \"./dist/main.js\", // Correct\n \"./feature\": \"./lib/feature.js\", // Correct\n // \"./origin-relative\": \"/dist/main.js\", // Incorrect: Must start with ./\n // \"./absolute\": \"file:///dev/null\", // Incorrect: Must start with ./\n // \"./outside\": \"../common/util.js\" // Incorrect: Must start with ./\n }\n}\n\nReasons for this behavior include:
\nExport targets must not resolve to a location outside the package's root\ndirectory. Additionally, path segments like . (single dot), .. (double dot),\nor node_modules (and their URL-encoded equivalents) are generally disallowed\nwithin the target string after the initial ./ and in any subpath part\nsubstituted into a target pattern.
// package.json\n{\n \"name\": \"my-package\",\n \"exports\": {\n // \".\": \"./dist/../../elsewhere/file.js\", // Invalid: path traversal\n // \".\": \"././dist/main.js\", // Invalid: contains \".\" segment\n // \".\": \"./dist/../dist/main.js\", // Invalid: contains \"..\" segment\n // \"./utils/./helper.js\": \"./utils/helper.js\" // Key has invalid segment\n }\n}\n",
"displayName": "No path traversal or invalid segments"
}
],
"displayName": "Path Rules and Validation for Export Targets"
}
],
"displayName": "Subpath exports"
},
{
"textRaw": "Exports sugar",
"name": "exports_sugar",
"type": "module",
"meta": {
"added": [
"v12.11.0"
],
"changes": []
},
"desc": "If the \".\" export is the only export, the \"exports\" field provides sugar\nfor this case being the direct \"exports\" field value.
{\n \"exports\": {\n \".\": \"./index.js\"\n }\n}\n\ncan be written:
\n{\n \"exports\": \"./index.js\"\n}\n",
"displayName": "Exports sugar"
},
{
"textRaw": "Subpath imports",
"name": "subpath_imports",
"type": "module",
"meta": {
"added": [
"v14.6.0",
"v12.19.0"
],
"changes": [
{
"version": "v25.4.0",
"pr-url": "https://github.com/nodejs/node/pull/60864",
"description": "Allow subpath imports that start with `#/`."
}
]
},
"desc": "In addition to the \"exports\" field, there is a package \"imports\" field\nto create private mappings that only apply to import specifiers from within the\npackage itself.
Entries in the \"imports\" field must always start with # to ensure they are\ndisambiguated from external package specifiers.
For example, the imports field can be used to gain the benefits of conditional\nexports for internal modules:
\n// package.json\n{\n \"imports\": {\n \"#dep\": {\n \"node\": \"dep-node-native\",\n \"default\": \"./dep-polyfill.js\"\n }\n },\n \"dependencies\": {\n \"dep-node-native\": \"^1.0.0\"\n }\n}\n\nwhere import '#dep' does not get the resolution of the external package\ndep-node-native (including its exports in turn), and instead gets the local\nfile ./dep-polyfill.js relative to the package in other environments.
Unlike the \"exports\" field, the \"imports\" field permits mapping to external\npackages.
The resolution rules for the imports field are otherwise analogous to the\nexports field.
", "displayName": "Subpath imports" }, { "textRaw": "Subpath patterns", "name": "subpath_patterns", "type": "module", "meta": { "added": [ "v14.13.0", "v12.20.0" ], "changes": [ { "version": [ "v16.10.0", "v14.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/40041", "description": "Support pattern trailers in \"imports\" field." }, { "version": [ "v16.9.0", "v14.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/39635", "description": "Support pattern trailers." } ] }, "desc": "For packages with a small number of exports or imports, we recommend\nexplicitly listing each exports subpath entry. But for packages that have\nlarge numbers of subpaths, this might cause package.json bloat and\nmaintenance issues.
For these use cases, subpath export patterns can be used instead:
\n// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./features/*.js\": \"./src/features/*.js\"\n },\n \"imports\": {\n \"#internal/*.js\": \"./src/internal/*.js\"\n }\n}\n\n* maps expose nested subpaths as it is a string replacement syntax\nonly.
All instances of * on the right hand side will then be replaced with this\nvalue, including if it contains any / separators.
import featureX from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y.js';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z.js';\n// Loads ./src/internal/z.js\n\nThis is a direct static matching and replacement without any special handling\nfor file extensions. Including the \"*.js\" on both sides of the mapping\nrestricts the exposed package exports to only JS files.
The property of exports being statically enumerable is maintained with exports\npatterns since the individual exports for a package can be determined by\ntreating the right hand side target pattern as a ** glob against the list of\nfiles within the package. Because node_modules paths are forbidden in exports\ntargets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, null targets can be used:
// ./node_modules/es-module-package/package.json\n{\n \"exports\": {\n \"./features/*.js\": \"./src/features/*.js\",\n \"./features/private-internal/*\": null\n }\n}\n\nimport featureInternal from 'es-module-package/features/private-internal/m.js';\n// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED\n\nimport featureX from 'es-module-package/features/x.js';\n// Loads ./node_modules/es-module-package/src/features/x.js\n",
"displayName": "Subpath patterns"
},
{
"textRaw": "Conditional exports",
"name": "conditional_exports",
"type": "module",
"meta": {
"added": [
"v13.2.0",
"v12.16.0"
],
"changes": [
{
"version": [
"v13.7.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/31001",
"description": "Unflag conditional exports."
}
]
},
"desc": "Conditional exports provide a way to map to different paths depending on\ncertain conditions. They are supported for both CommonJS and ES module imports.
\nFor example, a package that wants to provide different ES module exports for\nrequire() and import can be written:
// package.json\n{\n \"exports\": {\n \"import\": \"./index-module.js\",\n \"require\": \"./index-require.cjs\"\n },\n \"type\": \"module\"\n}\n\nNode.js implements the following conditions, listed in order from most\nspecific to least specific as conditions should be defined:
\n\"node-addons\" - similar to \"node\" and matches for any Node.js environment.\nThis condition can be used to provide an entry point which uses native C++\naddons as opposed to an entry point which is more universal and doesn't rely\non native addons. This condition can be disabled via the\n--no-addons flag.\"node\" - matches for any Node.js environment. Can be a CommonJS or ES\nmodule file. In most cases explicitly calling out the Node.js platform is\nnot necessary.\"import\" - matches when the package is loaded via import or\nimport(), or via any top-level import or resolve operation by the\nECMAScript module loader. Applies regardless of the module format of the\ntarget file. Always mutually exclusive with \"require\".\"require\" - matches when the package is loaded via require(). The\nreferenced file should be loadable with require() although the condition\nmatches regardless of the module format of the target file. Expected\nformats include CommonJS, JSON, native addons, and ES modules. Always mutually\nexclusive with \"import\".\"module-sync\" - matches no matter the package is loaded via import,\nimport() or require(). The format is expected to be ES modules that does\nnot contain top-level await in its module graph - if it does,\nERR_REQUIRE_ASYNC_MODULE will be thrown when the module is require()-ed.\"default\" - the generic fallback that always matches. Can be a CommonJS\nor ES module file. This condition should always come last.Within the \"exports\" object, key order is significant. During condition\nmatching, earlier entries have higher priority and take precedence over later\nentries. The general rule is that conditions should be from most specific to\nleast specific in object order.
Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.
The \"node-addons\" condition can be used to provide an entry point which\nuses native C++ addons. However, this condition can be disabled via the\n--no-addons flag. When using \"node-addons\", it's recommended to treat\n\"default\" as an enhancement that provides a more universal entry point, e.g.\nusing WebAssembly instead of a native addon.
Conditional exports can also be extended to exports subpaths, for example:
\n{\n \"exports\": {\n \".\": \"./index.js\",\n \"./feature.js\": {\n \"node\": \"./feature-node.js\",\n \"default\": \"./feature.js\"\n }\n }\n}\n\nDefines a package where require('pkg/feature.js') and\nimport 'pkg/feature.js' could provide different implementations between\nNode.js and other JS environments.
When using environment branches, always include a \"default\" condition where\npossible. Providing a \"default\" condition ensures that any unknown JS\nenvironments are able to use this universal implementation, which helps avoid\nthese JS environments from having to pretend to be existing environments in\norder to support packages with conditional exports. For this reason, using\n\"node\" and \"default\" condition branches is usually preferable to using\n\"node\" and \"browser\" condition branches.
In addition to direct mappings, Node.js also supports nested condition objects.
\nFor example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:
\n{\n \"exports\": {\n \"node\": {\n \"import\": \"./feature-node.mjs\",\n \"require\": \"./feature-node.cjs\"\n },\n \"default\": \"./feature.mjs\"\n }\n}\n\nConditions continue to be matched in order as with flat conditions. If\na nested condition does not have any mapping it will continue checking\nthe remaining conditions of the parent condition. In this way nested\nconditions behave analogously to nested JavaScript if statements.
When running Node.js, custom user conditions can be added with the\n--conditions flag:
node --conditions=development index.js\n\nwhich would then resolve the \"development\" condition in package imports and\nexports, while resolving the existing \"node\", \"node-addons\", \"default\",\n\"import\", and \"require\" conditions as appropriate.
Any number of custom conditions can be set with repeat flags.
\nTypical conditions should only contain alphanumerical characters,\nusing \":\", \"-\", or \"=\" as separators if necessary. Anything else may run\ninto compability issues outside of node.
\nIn node, conditions have very few restrictions, but specifically these include:
\nCondition strings other than the \"import\", \"require\", \"node\", \"module-sync\",\n\"node-addons\" and \"default\" conditions\nimplemented in Node.js core are ignored by default.
Other platforms may implement other conditions and user conditions can be\nenabled in Node.js via the --conditions / -C flag.
Since custom package conditions require clear definitions to ensure correct\nusage, a list of common known package conditions and their strict definitions\nis provided below to assist with ecosystem coordination.
\n\"types\" - can be used by typing systems to resolve the typing file for\nthe given export. This condition should always be included first.\"browser\" - any web browser environment.\"development\" - can be used to define a development-only environment\nentry point, for example to provide additional debugging context such as\nbetter error messages when running in a development mode. Must always be\nmutually exclusive with \"production\".\"production\" - can be used to define a production environment entry\npoint. Must always be mutually exclusive with \"development\".For other runtimes, platform-specific condition key definitions are maintained\nby the WinterCG in the Runtime Keys proposal specification.
\nNew conditions definitions may be added to this list by creating a pull request\nto the Node.js documentation for this section. The requirements for listing\na new condition definition here are that:
\n\"types\" condition is a good example: It\ndoesn't really belong in the Runtime Keys proposal but is a good fit\nhere in the Node.js docs.The above definitions may be moved to a dedicated conditions registry in due\ncourse.
", "displayName": "Community Conditions Definitions" }, { "textRaw": "Self-referencing a package using its name", "name": "self-referencing_a_package_using_its_name", "type": "module", "meta": { "added": [ "v13.1.0", "v12.16.0" ], "changes": [ { "version": [ "v13.6.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31002", "description": "Unflag self-referencing a package using its name." } ] }, "desc": "Within a package, the values defined in the package's\npackage.json \"exports\" field can be referenced via the package's name.\nFor example, assuming the package.json is:
// package.json\n{\n \"name\": \"a-package\",\n \"exports\": {\n \".\": \"./index.mjs\",\n \"./foo.js\": \"./foo.js\"\n }\n}\n\nThen any module in that package can reference an export in the package itself:
\n// ./a-module.mjs\nimport { something } from 'a-package'; // Imports \"something\" from ./index.mjs.\n\nSelf-referencing is available only if package.json has \"exports\", and\nwill allow importing only what that \"exports\" (in the package.json)\nallows. So the code below, given the previous package, will generate a runtime\nerror:
// ./another-module.mjs\n\n// Imports \"another\" from ./m.mjs. Fails because\n// the \"package.json\" \"exports\" field\n// does not provide an export named \"./m.mjs\".\nimport { another } from 'a-package/m.mjs';\n\nSelf-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:
// ./a-module.js\nconst { something } = require('a-package/foo.js'); // Loads from ./foo.js.\n\nFinally, self-referencing also works with scoped packages. For example, this\ncode will also work:
\n// package.json\n{\n \"name\": \"@my/package\",\n \"exports\": \"./index.js\"\n}\n\n// ./index.js\nmodule.exports = 42;\n\n// ./other.js\nconsole.log(require('@my/package'));\n\n$ node other.js\n42\n",
"displayName": "Self-referencing a package using its name"
}
],
"displayName": "Package entry points"
},
{
"textRaw": "Dual CommonJS/ES module packages",
"name": "dual_commonjs/es_module_packages",
"type": "misc",
"desc": "See the package examples repository for details.
", "displayName": "Dual CommonJS/ES module packages" }, { "textRaw": "Node.js `package.json` field definitions", "name": "node.js_`package.json`_field_definitions", "type": "misc", "desc": "This section describes the fields used by the Node.js runtime. Other tools (such\nas npm) use\nadditional fields which are ignored by Node.js and not documented here.
\nThe following fields in package.json files are used in Node.js:
\"name\" - Relevant when using named imports within a package. Also used\nby package managers as the name of the package.\"main\" - The default module when loading the package, if exports is not\nspecified, and in versions of Node.js prior to the introduction of exports.\"type\" - The package type determining whether to load .js files as\nCommonJS or ES modules.\"exports\" - Package exports and conditional exports. When present,\nlimits which submodules can be loaded from within the package.\"imports\" - Package imports, for use by modules within the package\nitself.<string>{\n \"name\": \"package-name\"\n}\n\nThe \"name\" field defines your package's name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.
The \"name\" field can be used in addition to the \"exports\" field to\nself-reference a package using its name.
<string>{\n \"main\": \"./index.js\"\n}\n\nThe \"main\" field defines the entry point of a package when imported by name\nvia a node_modules lookup. Its value is a path.
When a package has an \"exports\" field, this will take precedence over the\n\"main\" field when importing the package by name.
It also defines the script that is used when the package directory is loaded\nvia require().
// This resolves to ./path/to/directory/index.js.\nrequire('./path/to/directory');\n",
"displayName": "`\"main\"`"
},
{
"textRaw": "`\"type\"`",
"name": "`\"type\"`",
"type": "module",
"meta": {
"added": [
"v12.0.0"
],
"changes": [
{
"version": [
"v13.2.0",
"v12.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/29866",
"description": "Unflag `--experimental-modules`."
}
]
},
"desc": "<string>The \"type\" field defines the module format that Node.js uses for all\n.js files that have that package.json file as their nearest parent.
Files ending with .js are loaded as ES modules when the nearest parent\npackage.json file contains a top-level field \"type\" with a value of\n\"module\".
The nearest parent package.json is defined as the first package.json found\nwhen searching in the current folder, that folder's parent, and so on up\nuntil a node_modules folder or the volume root is reached.
// package.json\n{\n \"type\": \"module\"\n}\n\n# In same folder as preceding package.json\nnode my-app.js # Runs as ES module\n\nIf the nearest parent package.json lacks a \"type\" field, or contains\n\"type\": \"commonjs\", .js files are treated as CommonJS. If the volume\nroot is reached and no package.json is found, .js files are treated as\nCommonJS.
import statements of .js files are treated as ES modules if the nearest\nparent package.json contains \"type\": \"module\".
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n\nRegardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.
<Object> | <string> | <string[]>{\n \"exports\": \"./index.js\"\n}\n\nThe \"exports\" field allows defining the entry points of a package when\nimported by name loaded either via a node_modules lookup or a\nself-reference to its own name. It is supported in Node.js 12+ as an\nalternative to the \"main\" that can support defining subpath exports\nand conditional exports while encapsulating internal unexported modules.
Conditional Exports can also be used within \"exports\" to define different\npackage entry points per environment, including whether the package is\nreferenced via require or via import.
All paths defined in the \"exports\" must be relative file URLs starting with\n./.
<Object>// package.json\n{\n \"imports\": {\n \"#dep\": {\n \"node\": \"dep-node-native\",\n \"default\": \"./dep-polyfill.js\"\n }\n },\n \"dependencies\": {\n \"dep-node-native\": \"^1.0.0\"\n }\n}\n\nEntries in the imports field must be strings starting with #.
Package imports permit mapping to external packages.
\nThis field defines subpath imports for the current package.
", "displayName": "`\"imports\"`" } ], "displayName": "Node.js `package.json` field definitions" } ], "source": "doc/api/packages.md" }, { "textRaw": "Diagnostic report", "name": "Diagnostic report", "introduced_in": "v11.8.0", "type": "misc", "meta": { "changes": [ { "version": [ "v23.3.0", "v22.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/55697", "description": "Added `--report-exclude-env` option for excluding environment variables from report generation." }, { "version": [ "v22.0.0", "v20.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/51645", "description": "Added `--report-exclude-network` option for excluding networking operations that can slow down report generation in some cases." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "Delivers a JSON-formatted diagnostic summary, written to a file.
\nThe report is intended for development, test, and production use, to capture\nand preserve information for problem determination. It includes JavaScript\nand native stack traces, heap statistics, platform information, resource\nusage etc. With the report option enabled, diagnostic reports can be triggered\non unhandled exceptions, fatal errors and user signals, in addition to\ntriggering programmatically through API calls.
\nA complete example report that was generated on an uncaught exception\nis provided below for reference.
\n{\n \"header\": {\n \"reportVersion\": 5,\n \"event\": \"exception\",\n \"trigger\": \"Exception\",\n \"filename\": \"report.20181221.005011.8974.0.001.json\",\n \"dumpEventTime\": \"2018-12-21T00:50:11Z\",\n \"dumpEventTimeStamp\": \"1545371411331\",\n \"processId\": 8974,\n \"cwd\": \"/home/nodeuser/project/node\",\n \"commandLine\": [\n \"/home/nodeuser/project/node/out/Release/node\",\n \"--report-uncaught-exception\",\n \"/home/nodeuser/project/node/test/report/test-exception.js\",\n \"child\"\n ],\n \"nodejsVersion\": \"v12.0.0-pre\",\n \"glibcVersionRuntime\": \"2.17\",\n \"glibcVersionCompiler\": \"2.17\",\n \"wordSize\": \"64 bit\",\n \"arch\": \"x64\",\n \"platform\": \"linux\",\n \"componentVersions\": {\n \"node\": \"12.0.0-pre\",\n \"v8\": \"7.1.302.28-node.5\",\n \"uv\": \"1.24.1\",\n \"zlib\": \"1.2.11\",\n \"ares\": \"1.15.0\",\n \"modules\": \"68\",\n \"nghttp2\": \"1.34.0\",\n \"napi\": \"3\",\n \"llhttp\": \"1.0.1\",\n \"openssl\": \"1.1.0j\"\n },\n \"release\": {\n \"name\": \"node\"\n },\n \"osName\": \"Linux\",\n \"osRelease\": \"3.10.0-862.el7.x86_64\",\n \"osVersion\": \"#1 SMP Wed Mar 21 18:14:51 EDT 2018\",\n \"osMachine\": \"x86_64\",\n \"cpus\": [\n {\n \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n \"speed\": 2700,\n \"user\": 88902660,\n \"nice\": 0,\n \"sys\": 50902570,\n \"idle\": 241732220,\n \"irq\": 0\n },\n {\n \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n \"speed\": 2700,\n \"user\": 88902660,\n \"nice\": 0,\n \"sys\": 50902570,\n \"idle\": 241732220,\n \"irq\": 0\n }\n ],\n \"networkInterfaces\": [\n {\n \"name\": \"en0\",\n \"internal\": false,\n \"mac\": \"13:10:de:ad:be:ef\",\n \"address\": \"10.0.0.37\",\n \"netmask\": \"255.255.255.0\",\n \"family\": \"IPv4\"\n }\n ],\n \"host\": \"test_machine\"\n },\n \"javascriptStack\": {\n \"message\": \"Error: *** test-exception.js: throwing uncaught Error\",\n \"stack\": [\n \"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)\",\n \"at Object.<anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)\",\n \"at Module._compile (internal/modules/cjs/loader.js:718:30)\",\n \"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)\",\n \"at Module.load (internal/modules/cjs/loader.js:617:32)\",\n \"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)\",\n \"at Function.Module._load (internal/modules/cjs/loader.js:552:3)\",\n \"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)\",\n \"at executeUserCode (internal/bootstrap/node.js:332:15)\"\n ]\n },\n \"nativeStack\": [\n {\n \"pc\": \"0x000055b57f07a9ef\",\n \"symbol\": \"report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local<v8::String>, std::ostream&) [./node]\"\n },\n {\n \"pc\": \"0x000055b57f07cf03\",\n \"symbol\": \"report::GetReport(v8::FunctionCallbackInfo<v8::Value> const&) [./node]\"\n },\n {\n \"pc\": \"0x000055b57f1bccfd\",\n \"symbol\": \" [./node]\"\n },\n {\n \"pc\": \"0x000055b57f1be048\",\n \"symbol\": \"v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]\"\n },\n {\n \"pc\": \"0x000055b57feeda0e\",\n \"symbol\": \" [./node]\"\n }\n ],\n \"javascriptHeap\": {\n \"totalMemory\": 5660672,\n \"executableMemory\": 524288,\n \"totalCommittedMemory\": 5488640,\n \"availableMemory\": 4341379928,\n \"totalGlobalHandlesMemory\": 8192,\n \"usedGlobalHandlesMemory\": 3136,\n \"usedMemory\": 4816432,\n \"memoryLimit\": 4345298944,\n \"mallocedMemory\": 254128,\n \"externalMemory\": 315644,\n \"peakMallocedMemory\": 98752,\n \"nativeContextCount\": 1,\n \"detachedContextCount\": 0,\n \"doesZapGarbage\": 0,\n \"heapSpaces\": {\n \"read_only_space\": {\n \"memorySize\": 524288,\n \"committedMemory\": 39208,\n \"capacity\": 515584,\n \"used\": 30504,\n \"available\": 485080\n },\n \"new_space\": {\n \"memorySize\": 2097152,\n \"committedMemory\": 2019312,\n \"capacity\": 1031168,\n \"used\": 985496,\n \"available\": 45672\n },\n \"old_space\": {\n \"memorySize\": 2273280,\n \"committedMemory\": 1769008,\n \"capacity\": 1974640,\n \"used\": 1725488,\n \"available\": 249152\n },\n \"code_space\": {\n \"memorySize\": 696320,\n \"committedMemory\": 184896,\n \"capacity\": 152128,\n \"used\": 152128,\n \"available\": 0\n },\n \"map_space\": {\n \"memorySize\": 536576,\n \"committedMemory\": 344928,\n \"capacity\": 327520,\n \"used\": 327520,\n \"available\": 0\n },\n \"large_object_space\": {\n \"memorySize\": 0,\n \"committedMemory\": 0,\n \"capacity\": 1520590336,\n \"used\": 0,\n \"available\": 1520590336\n },\n \"new_large_object_space\": {\n \"memorySize\": 0,\n \"committedMemory\": 0,\n \"capacity\": 0,\n \"used\": 0,\n \"available\": 0\n }\n }\n },\n \"resourceUsage\": {\n \"rss\": \"35766272\",\n \"free_memory\": \"1598337024\",\n \"total_memory\": \"17179869184\",\n \"available_memory\": \"1598337024\",\n \"maxRss\": \"36624662528\",\n \"constrained_memory\": \"36624662528\",\n \"userCpuSeconds\": 0.040072,\n \"kernelCpuSeconds\": 0.016029,\n \"cpuConsumptionPercent\": 5.6101,\n \"userCpuConsumptionPercent\": 4.0072,\n \"kernelCpuConsumptionPercent\": 1.6029,\n \"pageFaults\": {\n \"IORequired\": 0,\n \"IONotRequired\": 4610\n },\n \"fsActivity\": {\n \"reads\": 0,\n \"writes\": 0\n }\n },\n \"uvthreadResourceUsage\": {\n \"userCpuSeconds\": 0.039843,\n \"kernelCpuSeconds\": 0.015937,\n \"cpuConsumptionPercent\": 5.578,\n \"userCpuConsumptionPercent\": 3.9843,\n \"kernelCpuConsumptionPercent\": 1.5937,\n \"fsActivity\": {\n \"reads\": 0,\n \"writes\": 0\n }\n },\n \"libuv\": [\n {\n \"type\": \"async\",\n \"is_active\": true,\n \"is_referenced\": false,\n \"address\": \"0x0000000102910900\",\n \"details\": \"\"\n },\n {\n \"type\": \"timer\",\n \"is_active\": false,\n \"is_referenced\": false,\n \"address\": \"0x00007fff5fbfeab0\",\n \"repeat\": 0,\n \"firesInMsFromNow\": 94403548320796,\n \"expired\": true\n },\n {\n \"type\": \"check\",\n \"is_active\": true,\n \"is_referenced\": false,\n \"address\": \"0x00007fff5fbfeb48\"\n },\n {\n \"type\": \"idle\",\n \"is_active\": false,\n \"is_referenced\": true,\n \"address\": \"0x00007fff5fbfebc0\"\n },\n {\n \"type\": \"prepare\",\n \"is_active\": false,\n \"is_referenced\": false,\n \"address\": \"0x00007fff5fbfec38\"\n },\n {\n \"type\": \"check\",\n \"is_active\": false,\n \"is_referenced\": false,\n \"address\": \"0x00007fff5fbfecb0\"\n },\n {\n \"type\": \"async\",\n \"is_active\": true,\n \"is_referenced\": false,\n \"address\": \"0x000000010188f2e0\"\n },\n {\n \"type\": \"tty\",\n \"is_active\": false,\n \"is_referenced\": true,\n \"address\": \"0x000055b581db0e18\",\n \"width\": 204,\n \"height\": 55,\n \"fd\": 17,\n \"writeQueueSize\": 0,\n \"readable\": true,\n \"writable\": true\n },\n {\n \"type\": \"signal\",\n \"is_active\": true,\n \"is_referenced\": false,\n \"address\": \"0x000055b581d80010\",\n \"signum\": 28,\n \"signal\": \"SIGWINCH\"\n },\n {\n \"type\": \"tty\",\n \"is_active\": true,\n \"is_referenced\": true,\n \"address\": \"0x000055b581df59f8\",\n \"width\": 204,\n \"height\": 55,\n \"fd\": 19,\n \"writeQueueSize\": 0,\n \"readable\": true,\n \"writable\": true\n },\n {\n \"type\": \"loop\",\n \"is_active\": true,\n \"address\": \"0x000055fc7b2cb180\",\n \"loopIdleTimeSeconds\": 22644.8\n },\n {\n \"type\": \"tcp\",\n \"is_active\": true,\n \"is_referenced\": true,\n \"address\": \"0x000055e70fcb85d8\",\n \"localEndpoint\": {\n \"host\": \"localhost\",\n \"ip4\": \"127.0.0.1\",\n \"port\": 48986\n },\n \"remoteEndpoint\": {\n \"host\": \"localhost\",\n \"ip4\": \"127.0.0.1\",\n \"port\": 38573\n },\n \"sendBufferSize\": 2626560,\n \"recvBufferSize\": 131072,\n \"fd\": 24,\n \"writeQueueSize\": 0,\n \"readable\": true,\n \"writable\": true\n }\n ],\n \"workers\": [],\n \"environmentVariables\": {\n \"REMOTEHOST\": \"REMOVED\",\n \"MANPATH\": \"/opt/rh/devtoolset-3/root/usr/share/man:\",\n \"XDG_SESSION_ID\": \"66126\",\n \"HOSTNAME\": \"test_machine\",\n \"HOST\": \"test_machine\",\n \"TERM\": \"xterm-256color\",\n \"SHELL\": \"/bin/csh\",\n \"SSH_CLIENT\": \"REMOVED\",\n \"PERL5LIB\": \"/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl\",\n \"OLDPWD\": \"/home/nodeuser/project/node/src\",\n \"JAVACONFDIRS\": \"/opt/rh/devtoolset-3/root/etc/java:/etc/java\",\n \"SSH_TTY\": \"/dev/pts/0\",\n \"PCP_DIR\": \"/opt/rh/devtoolset-3/root\",\n \"GROUP\": \"normaluser\",\n \"USER\": \"nodeuser\",\n \"LD_LIBRARY_PATH\": \"/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib\",\n \"HOSTTYPE\": \"x86_64-linux\",\n \"XDG_CONFIG_DIRS\": \"/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg\",\n \"MAIL\": \"/var/spool/mail/nodeuser\",\n \"PATH\": \"/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin\",\n \"PWD\": \"/home/nodeuser/project/node\",\n \"LANG\": \"en_US.UTF-8\",\n \"PS1\": \"\\\\u@\\\\h : \\\\[\\\\e[31m\\\\]\\\\w\\\\[\\\\e[m\\\\] > \",\n \"SHLVL\": \"2\",\n \"HOME\": \"/home/nodeuser\",\n \"OSTYPE\": \"linux\",\n \"VENDOR\": \"unknown\",\n \"PYTHONPATH\": \"/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages\",\n \"MACHTYPE\": \"x86_64\",\n \"LOGNAME\": \"nodeuser\",\n \"XDG_DATA_DIRS\": \"/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share\",\n \"LESSOPEN\": \"||/usr/bin/lesspipe.sh %s\",\n \"INFOPATH\": \"/opt/rh/devtoolset-3/root/usr/share/info\",\n \"XDG_RUNTIME_DIR\": \"/run/user/50141\",\n \"_\": \"./node\"\n },\n \"userLimits\": {\n \"core_file_size_blocks\": {\n \"soft\": \"\",\n \"hard\": \"unlimited\"\n },\n \"data_seg_size_bytes\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n \"file_size_blocks\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n \"max_locked_memory_bytes\": {\n \"soft\": \"unlimited\",\n \"hard\": 65536\n },\n \"max_memory_size_bytes\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n \"open_files\": {\n \"soft\": \"unlimited\",\n \"hard\": 4096\n },\n \"stack_size_bytes\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n \"cpu_time_seconds\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n \"max_user_processes\": {\n \"soft\": \"unlimited\",\n \"hard\": 4127290\n },\n \"virtual_memory_bytes\": {\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n }\n },\n \"sharedObjects\": [\n \"/lib64/libdl.so.2\",\n \"/lib64/librt.so.1\",\n \"/lib64/libstdc++.so.6\",\n \"/lib64/libm.so.6\",\n \"/lib64/libgcc_s.so.1\",\n \"/lib64/libpthread.so.0\",\n \"/lib64/libc.so.6\",\n \"/lib64/ld-linux-x86-64.so.2\"\n ]\n}\n",
"miscs": [
{
"textRaw": "Usage",
"name": "usage",
"type": "misc",
"desc": "node --report-uncaught-exception --report-on-signal \\\n--report-on-fatalerror app.js\n\n--report-uncaught-exception Enables report to be generated on\nun-caught exceptions. Useful when inspecting JavaScript stack in conjunction\nwith native stack and other runtime environment data.
--report-on-signal Enables report to be generated upon receiving\nthe specified (or predefined) signal to the running Node.js process. (See\nbelow on how to modify the signal that triggers the report.) Default signal is\nSIGUSR2. Useful when a report needs to be triggered from another program.\nApplication monitors may leverage this feature to collect report at regular\nintervals and plot rich set of internal runtime data to their views.
Signal based report generation is not supported in Windows.
\nUnder normal circumstances, there is no need to modify the report triggering\nsignal. However, if SIGUSR2 is already used for other purposes, then this\nflag helps to change the signal for report generation and preserve the original\nmeaning of SIGUSR2 for the said purposes.
--report-on-fatalerror Enables the report to be triggered on fatal errors\n(internal errors within the Node.js runtime, such as out of memory)\nthat leads to termination of the application. Useful to inspect various\ndiagnostic data elements such as heap, stack, event loop state, resource\nconsumption etc. to reason about the fatal error.
--report-compact Write reports in a compact format, single-line JSON, more\neasily consumable by log processing systems than the default multi-line format\ndesigned for human consumption.
--report-directory Location at which the report will be\ngenerated.
--report-filename Name of the file to which the report will be\nwritten.
--report-signal Sets or resets the signal for report generation\n(not supported on Windows). Default signal is SIGUSR2.
--report-exclude-network Exclude header.networkInterfaces and disable the reverse DNS queries\nin libuv.*.(remote|local)Endpoint.host from the diagnostic report.\nBy default this is not set and the network interfaces are included.
--report-exclude-env Exclude environmentVariables from the\ndiagnostic report. By default this is not set and the environment\nvariables are included.
A report can also be triggered via an API call from a JavaScript application:
\nprocess.report.writeReport();\n\nThis function takes an optional additional argument filename, which is\nthe name of a file into which the report is written.
process.report.writeReport('./foo.json');\n\nThis function takes an optional additional argument err which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport. When using report to handle errors in a callback or an exception\nhandler, this allows the report to include the location of the original error as\nwell as where it was handled.
try {\n process.chdir('/non-existent-path');\n} catch (err) {\n process.report.writeReport(err);\n}\n// Any other code\n\nIf both filename and error object are passed to writeReport() the\nerror object must be the second parameter.
try {\n process.chdir('/non-existent-path');\n} catch (err) {\n process.report.writeReport(filename, err);\n}\n// Any other code\n\nThe content of the diagnostic report can be returned as a JavaScript Object\nvia an API call from a JavaScript application:
\nconst report = process.report.getReport();\nconsole.log(typeof report === 'object'); // true\n\n// Similar to process.report.writeReport() output\nconsole.log(JSON.stringify(report, null, 2));\n\nThis function takes an optional additional argument err, which is an Error\nobject that will be used as the context for the JavaScript stack printed in the\nreport.
const report = process.report.getReport(new Error('custom error'));\nconsole.log(typeof report === 'object'); // true\n\nThe API versions are useful when inspecting the runtime state from within\nthe application, in expectation of self-adjusting the resource consumption,\nload balancing, monitoring etc.
\nThe content of the report consists of a header section containing the event\ntype, date, time, PID, and Node.js version, sections containing JavaScript and\nnative stack traces, a section containing V8 heap information, a section\ncontaining libuv handle information, and an OS platform information section\nshowing CPU and memory usage and system limits. An example report can be\ntriggered using the Node.js REPL:
$ node\n> process.report.writeReport();\nWriting Node.js report to file: report.20181126.091102.8480.0.001.json\nNode.js report completed\n>\n\nWhen a report is written, start and end messages are issued to stderr\nand the filename of the report is returned to the caller. The default filename\nincludes the date, time, PID, and a sequence number. The sequence number helps\nin associating the report dump with the runtime state if generated multiple\ntimes for the same Node.js process.
", "displayName": "Usage" }, { "textRaw": "Report Version", "name": "report_version", "type": "misc", "desc": "Diagnostic report has an associated single-digit version number (report.header.reportVersion),\nuniquely representing the report format. The version number is bumped\nwhen new key is added or removed, or the data type of a value is changed.\nReport version definitions are consistent across LTS releases.
Replace the keys data_seg_size_kbytes, max_memory_size_kbytes, and virtual_memory_kbytes\nwith data_seg_size_bytes, max_memory_size_bytes, and virtual_memory_bytes\nrespectively in the userLimits section, as these values are given in bytes.
{\n \"userLimits\": {\n // Skip some keys ...\n \"data_seg_size_bytes\": { // replacing data_seg_size_kbytes\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n // ...\n \"max_memory_size_bytes\": { // replacing max_memory_size_kbytes\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n },\n // ...\n \"virtual_memory_bytes\": { // replacing virtual_memory_kbytes\n \"soft\": \"unlimited\",\n \"hard\": \"unlimited\"\n }\n }\n}\n",
"displayName": "Version 5"
},
{
"textRaw": "Version 4",
"name": "version_4",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v23.3.0",
"v22.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/55697",
"description": "Added `--report-exclude-env` option for excluding environment variables from report generation."
}
]
},
"desc": "New fields ipv4 and ipv6 are added to tcp and udp libuv handles endpoints. Examples:
{\n \"libuv\": [\n {\n \"type\": \"tcp\",\n \"is_active\": true,\n \"is_referenced\": true,\n \"address\": \"0x000055e70fcb85d8\",\n \"localEndpoint\": {\n \"host\": \"localhost\",\n \"ip4\": \"127.0.0.1\", // new key\n \"port\": 48986\n },\n \"remoteEndpoint\": {\n \"host\": \"localhost\",\n \"ip4\": \"127.0.0.1\", // new key\n \"port\": 38573\n },\n \"sendBufferSize\": 2626560,\n \"recvBufferSize\": 131072,\n \"fd\": 24,\n \"writeQueueSize\": 0,\n \"readable\": true,\n \"writable\": true\n },\n {\n \"type\": \"tcp\",\n \"is_active\": true,\n \"is_referenced\": true,\n \"address\": \"0x000055e70fcd68c8\",\n \"localEndpoint\": {\n \"host\": \"ip6-localhost\",\n \"ip6\": \"::1\", // new key\n \"port\": 52266\n },\n \"remoteEndpoint\": {\n \"host\": \"ip6-localhost\",\n \"ip6\": \"::1\", // new key\n \"port\": 38573\n },\n \"sendBufferSize\": 2626560,\n \"recvBufferSize\": 131072,\n \"fd\": 25,\n \"writeQueueSize\": 0,\n \"readable\": false,\n \"writable\": false\n }\n ]\n}\n",
"displayName": "Version 4"
},
{
"textRaw": "Version 3",
"name": "version_3",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v19.1.0",
"v18.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/45254",
"description": "Add more memory info."
}
]
},
"desc": "The following memory usage keys are added to the resourceUsage section.
{\n \"resourceUsage\": {\n \"rss\": \"35766272\",\n \"free_memory\": \"1598337024\",\n \"total_memory\": \"17179869184\",\n \"available_memory\": \"1598337024\",\n \"constrained_memory\": \"36624662528\"\n }\n}\n",
"displayName": "Version 3"
},
{
"textRaw": "Version 2",
"name": "version_2",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v13.9.0",
"v12.16.2"
],
"pr-url": "https://github.com/nodejs/node/pull/31386",
"description": "Workers are now included in the report."
}
]
},
"desc": "Added Worker support. Refer to Interaction with workers section for more details.
This is the first version of the diagnostic report.
", "displayName": "Version 1" } ], "displayName": "Version history" } ], "displayName": "Report Version" }, { "textRaw": "Configuration", "name": "configuration", "type": "misc", "desc": "Additional runtime configuration of report generation is available via\nthe following properties of process.report:
reportOnFatalError triggers diagnostic reporting on fatal errors when true.\nDefaults to false.
reportOnSignal triggers diagnostic reporting on signal when true. This is\nnot supported on Windows. Defaults to false.
reportOnUncaughtException triggers diagnostic reporting on uncaught exception\nwhen true. Defaults to false.
signal specifies the POSIX signal identifier that will be used\nto intercept external triggers for report generation. Defaults to\n'SIGUSR2'.
filename specifies the name of the output file in the file system.\nSpecial meaning is attached to stdout and stderr. Usage of these\nwill result in report being written to the associated standard streams.\nIn cases where standard streams are used, the value in directory is ignored.\nURLs are not supported. Defaults to a composite filename that contains\ntimestamp, PID, and sequence number.
directory specifies the file system directory where the report will be\nwritten. URLs are not supported. Defaults to the current working directory of\nthe Node.js process.
excludeNetwork excludes header.networkInterfaces from the diagnostic report.
// Trigger report only on uncaught exceptions.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnSignal = false;\nprocess.report.reportOnUncaughtException = true;\n\n// Trigger report for both internal errors as well as external signal.\nprocess.report.reportOnFatalError = true;\nprocess.report.reportOnSignal = true;\nprocess.report.reportOnUncaughtException = false;\n\n// Change the default signal to 'SIGQUIT' and enable it.\nprocess.report.reportOnFatalError = false;\nprocess.report.reportOnUncaughtException = false;\nprocess.report.reportOnSignal = true;\nprocess.report.signal = 'SIGQUIT';\n\n// Disable network interfaces reporting\nprocess.report.excludeNetwork = true;\n\nConfiguration on module initialization is also available via\nenvironment variables:
\nNODE_OPTIONS=\"--report-uncaught-exception \\\n --report-on-fatalerror --report-on-signal \\\n --report-signal=SIGUSR2 --report-filename=./report.json \\\n --report-directory=/home/nodeuser\"\n\nSpecific API documentation can be found under\nprocess API documentation section.
Worker threads can create reports in the same way that the main thread\ndoes.
Reports will include information on any Workers that are children of the current\nthread as part of the workers section, with each Worker generating a report\nin the standard report format.
The thread which is generating the report will wait for the reports from Worker\nthreads to finish. However, the latency for this will usually be low, as both\nrunning JavaScript and the event loop are interrupted to generate the report.
", "displayName": "Interaction with workers" } ], "source": "doc/api/report.md" }, { "textRaw": "Corepack", "name": "Corepack", "introduced_in": "v14.19.0", "type": "misc", "meta": { "added": [ "v16.9.0", "v14.19.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "Corepack will no longer be distributed starting with Node.js v25.
\nUsers currently depending on the bundled corepack executable from Node.js\ncan switch to using the userland-provided corepack module.
The node:assert module provides a set of assertion functions for verifying\ninvariants.
In strict assertion mode, non-strict methods behave like their corresponding\nstrict methods. For example, assert.deepEqual() will behave like\nassert.deepStrictEqual().
In strict assertion mode, error messages for objects display a diff. In legacy\nassertion mode, error messages for objects display the objects, often truncated.
\nTo use strict assertion mode:
\nimport { strict as assert } from 'node:assert';\n\nconst assert = require('node:assert').strict;\n\nimport assert from 'node:assert/strict';\n\nconst assert = require('node:assert/strict');\n\nExample error diff:
\nimport { strict as assert } from 'node:assert';\n\nassert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected ... Lines skipped\n//\n// [\n// [\n// ...\n// 2,\n// + 3\n// - '3'\n// ],\n// ...\n// 5\n// ]\n\nconst assert = require('node:assert/strict');\n\nassert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected ... Lines skipped\n//\n// [\n// [\n// ...\n// 2,\n// + 3\n// - '3'\n// ],\n// ...\n// 5\n// ]\n\nTo deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS\nenvironment variables. This will also deactivate the colors in the REPL. For\nmore on color support in terminal environments, read the tty\ngetColorDepth() documentation.
Legacy assertion mode uses the == operator in:
To use legacy assertion mode:
\nimport assert from 'node:assert';\n\nconst assert = require('node:assert');\n\nLegacy assertion mode may have surprising results, especially when using\nassert.deepEqual():
// WARNING: This does not throw an AssertionError in legacy assertion mode!\nassert.deepEqual(/a/gi, new Date());\n",
"displayName": "Legacy assertion mode"
}
],
"classes": [
{
"textRaw": "Class: `assert.AssertionError`",
"name": "assert.AssertionError",
"type": "class",
"desc": "<errors.Error>Indicates the failure of an assertion. All errors thrown by the node:assert\nmodule will be instances of the AssertionError class.
A subclass of <Error> that indicates the failure of an assertion.
All instances contain the built-in Error properties (message and name)\nand:
actual <any> Set to the actual argument for methods such as\nassert.strictEqual().expected <any> Set to the expected value for methods such as\nassert.strictEqual().generatedMessage <boolean> Indicates if the message was auto-generated\n(true) or not.code <string> Value is always ERR_ASSERTION to show that the error is an\nassertion error.operator <string> Set to the passed in operator value.import assert from 'node:assert';\n\n// Generate an AssertionError to compare the error message later:\nconst { message } = new assert.AssertionError({\n actual: 1,\n expected: 2,\n operator: 'strictEqual',\n});\n\n// Verify error output:\ntry {\n assert.strictEqual(1, 2);\n} catch (err) {\n assert(err instanceof assert.AssertionError);\n assert.strictEqual(err.message, message);\n assert.strictEqual(err.name, 'AssertionError');\n assert.strictEqual(err.actual, 1);\n assert.strictEqual(err.expected, 2);\n assert.strictEqual(err.code, 'ERR_ASSERTION');\n assert.strictEqual(err.operator, 'strictEqual');\n assert.strictEqual(err.generatedMessage, true);\n}\n\nconst assert = require('node:assert');\n\n// Generate an AssertionError to compare the error message later:\nconst { message } = new assert.AssertionError({\n actual: 1,\n expected: 2,\n operator: 'strictEqual',\n});\n\n// Verify error output:\ntry {\n assert.strictEqual(1, 2);\n} catch (err) {\n assert(err instanceof assert.AssertionError);\n assert.strictEqual(err.message, message);\n assert.strictEqual(err.name, 'AssertionError');\n assert.strictEqual(err.actual, 1);\n assert.strictEqual(err.expected, 2);\n assert.strictEqual(err.code, 'ERR_ASSERTION');\n assert.strictEqual(err.operator, 'strictEqual');\n assert.strictEqual(err.generatedMessage, true);\n}\n"
}
]
},
{
"textRaw": "Class: `assert.Assert`",
"name": "assert.Assert",
"type": "class",
"meta": {
"added": [
"v24.6.0",
"v22.19.0"
],
"changes": []
},
"desc": "The Assert class allows creating independent assertion instances with custom options.
Creates a new assertion instance. The diff option controls the verbosity of diffs in assertion error messages.
const { Assert } = require('node:assert');\nconst assertInstance = new Assert({ diff: 'full' });\nassertInstance.deepStrictEqual({ a: 1 }, { a: 2 });\n// Shows a full diff in the error message.\n\nImportant: When destructuring assertion methods from an Assert instance,\nthe methods lose their connection to the instance's configuration options (such\nas diff, strict, and skipPrototype settings).\nThe destructured methods will fall back to default behavior instead.
const myAssert = new Assert({ diff: 'full' });\n\n// This works as expected - uses 'full' diff\nmyAssert.strictEqual({ a: 1 }, { b: { c: 1 } });\n\n// This loses the 'full' diff setting - falls back to default 'simple' diff\nconst { strictEqual } = myAssert;\nstrictEqual({ a: 1 }, { b: { c: 1 } });\n\nThe skipPrototype option affects all deep equality methods:
class Foo {\n constructor(a) {\n this.a = a;\n }\n}\n\nclass Bar {\n constructor(a) {\n this.a = a;\n }\n}\n\nconst foo = new Foo(1);\nconst bar = new Bar(1);\n\n// Default behavior - fails due to different constructors\nconst assert1 = new Assert();\nassert1.deepStrictEqual(foo, bar); // AssertionError\n\n// Skip prototype comparison - passes if properties are equal\nconst assert2 = new Assert({ skipPrototype: true });\nassert2.deepStrictEqual(foo, bar); // OK\n\nWhen destructured, methods lose access to the instance's this context and revert to default assertion behavior\n(diff: 'simple', non-strict mode).\nTo maintain custom options when using destructured methods, avoid\ndestructuring and call methods directly on the instance.
An alias of assert.ok().
Strict assertion mode
\nAn alias of assert.deepStrictEqual().
Legacy assertion mode
\nTests for deep equality between the actual and expected parameters. Consider\nusing assert.deepStrictEqual() instead. assert.deepEqual() can have\nsurprising results.
Deep equality means that the enumerable \"own\" properties of child objects\nare also recursively evaluated by the following rules.
", "modules": [ { "textRaw": "Comparison details", "name": "comparison_details", "type": "module", "desc": "== operator,\nwith the exception of <NaN>. It is treated as being identical in case\nboth sides are <NaN>.<Error> names, messages, causes, and errors are always compared,\neven if these are not enumerable properties.Object properties are compared unordered.<Map> keys and <Set> items are compared unordered.[[Prototype]] of\nobjects.<Symbol> properties are not compared.<WeakMap>, <WeakSet> and <Promise> instances are not compared\nstructurally. They are only equal if they reference the same object. Any\ncomparison between different WeakMap, WeakSet, or Promise instances\nwill result in inequality, even if they contain the same content.<RegExp> lastIndex, flags, and source are always compared, even if these\nare not enumerable properties.The following example does not throw an AssertionError because the\nprimitives are compared using the == operator.
import assert from 'node:assert';\n// WARNING: This does not throw an AssertionError!\n\nassert.deepEqual('+00000000', false);\n\nconst assert = require('node:assert');\n// WARNING: This does not throw an AssertionError!\n\nassert.deepEqual('+00000000', false);\n\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare evaluated also:
\nimport assert from 'node:assert';\n\nconst obj1 = {\n a: {\n b: 1,\n },\n};\nconst obj2 = {\n a: {\n b: 2,\n },\n};\nconst obj3 = {\n a: {\n b: 1,\n },\n};\nconst obj4 = { __proto__: obj1 };\n\nassert.deepEqual(obj1, obj1);\n// OK\n\n// Values of b are different:\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n\nassert.deepEqual(obj1, obj3);\n// OK\n\n// Prototypes are ignored:\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n\nconst assert = require('node:assert');\n\nconst obj1 = {\n a: {\n b: 1,\n },\n};\nconst obj2 = {\n a: {\n b: 2,\n },\n};\nconst obj3 = {\n a: {\n b: 1,\n },\n};\nconst obj4 = { __proto__: obj1 };\n\nassert.deepEqual(obj1, obj1);\n// OK\n\n// Values of b are different:\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n\nassert.deepEqual(obj1, obj3);\n// OK\n\n// Prototypes are ignored:\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n\nIf the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message parameter is an instance of <Error> then it will be thrown instead of the AssertionError.
Tests for deep equality between the actual and expected parameters.\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare recursively evaluated also by the following rules.
Object.is().[[Prototype]] of objects are compared using\nthe === operator.<Error> names, messages, causes, and errors are always compared,\neven if these are not enumerable properties. errors is also compared.<Symbol> properties are compared as well.Object properties are compared unordered.<Map> keys and <Set> items are compared unordered.<WeakMap>, <WeakSet> and <Promise> instances are not compared\nstructurally. They are only equal if they reference the same object. Any\ncomparison between different WeakMap, WeakSet, or Promise instances\nwill result in inequality, even if they contain the same content.<RegExp> lastIndex, flags, and source are always compared, even if these\nare not enumerable properties.import assert from 'node:assert/strict';\n\n// This fails because 1 !== '1'.\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// {\n// + a: 1\n// - a: '1'\n// }\n\n// The following objects don't have own properties\nconst date = new Date();\nconst object = {};\nconst fakeDate = {};\nObject.setPrototypeOf(fakeDate, Date.prototype);\n\n// Different [[Prototype]]:\nassert.deepStrictEqual(object, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + {}\n// - Date {}\n\n// Different type tags:\nassert.deepStrictEqual(date, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 2018-04-26T00:49:08.604Z\n// - Date {}\n\nassert.deepStrictEqual(NaN, NaN);\n// OK because Object.is(NaN, NaN) is true.\n\n// Different unwrapped numbers:\nassert.deepStrictEqual(new Number(1), new Number(2));\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + [Number: 1]\n// - [Number: 2]\n\nassert.deepStrictEqual(new String('foo'), Object('foo'));\n// OK because the object and the string are identical when unwrapped.\n\nassert.deepStrictEqual(-0, -0);\n// OK\n\n// Different zeros:\nassert.deepStrictEqual(0, -0);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 0\n// - -0\n\nconst symbol1 = Symbol();\nconst symbol2 = Symbol();\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });\n// OK, because it is the same symbol on both objects.\n\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });\n// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:\n//\n// {\n// Symbol(): 1\n// }\n\nconst weakMap1 = new WeakMap();\nconst weakMap2 = new WeakMap();\nconst obj = {};\n\nweakMap1.set(obj, 'value');\nweakMap2.set(obj, 'value');\n\n// Comparing different instances fails, even with same contents\nassert.deepStrictEqual(weakMap1, weakMap2);\n// AssertionError: Values have same structure but are not reference-equal:\n//\n// WeakMap {\n// <items unknown>\n// }\n\n// Comparing the same instance to itself succeeds\nassert.deepStrictEqual(weakMap1, weakMap1);\n// OK\n\nconst weakSet1 = new WeakSet();\nconst weakSet2 = new WeakSet();\nweakSet1.add(obj);\nweakSet2.add(obj);\n\n// Comparing different instances fails, even with same contents\nassert.deepStrictEqual(weakSet1, weakSet2);\n// AssertionError: Values have same structure but are not reference-equal:\n// + actual - expected\n//\n// WeakSet {\n// <items unknown>\n// }\n\n// Comparing the same instance to itself succeeds\nassert.deepStrictEqual(weakSet1, weakSet1);\n// OK\n\nconst assert = require('node:assert/strict');\n\n// This fails because 1 !== '1'.\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// {\n// + a: 1\n// - a: '1'\n// }\n\n// The following objects don't have own properties\nconst date = new Date();\nconst object = {};\nconst fakeDate = {};\nObject.setPrototypeOf(fakeDate, Date.prototype);\n\n// Different [[Prototype]]:\nassert.deepStrictEqual(object, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + {}\n// - Date {}\n\n// Different type tags:\nassert.deepStrictEqual(date, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 2018-04-26T00:49:08.604Z\n// - Date {}\n\nassert.deepStrictEqual(NaN, NaN);\n// OK because Object.is(NaN, NaN) is true.\n\n// Different unwrapped numbers:\nassert.deepStrictEqual(new Number(1), new Number(2));\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + [Number: 1]\n// - [Number: 2]\n\nassert.deepStrictEqual(new String('foo'), Object('foo'));\n// OK because the object and the string are identical when unwrapped.\n\nassert.deepStrictEqual(-0, -0);\n// OK\n\n// Different zeros:\nassert.deepStrictEqual(0, -0);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 0\n// - -0\n\nconst symbol1 = Symbol();\nconst symbol2 = Symbol();\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });\n// OK, because it is the same symbol on both objects.\n\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });\n// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:\n//\n// {\n// Symbol(): 1\n// }\n\nconst weakMap1 = new WeakMap();\nconst weakMap2 = new WeakMap();\nconst obj = {};\n\nweakMap1.set(obj, 'value');\nweakMap2.set(obj, 'value');\n\n// Comparing different instances fails, even with same contents\nassert.deepStrictEqual(weakMap1, weakMap2);\n// AssertionError: Values have same structure but are not reference-equal:\n//\n// WeakMap {\n// <items unknown>\n// }\n\n// Comparing the same instance to itself succeeds\nassert.deepStrictEqual(weakMap1, weakMap1);\n// OK\n\nconst weakSet1 = new WeakSet();\nconst weakSet2 = new WeakSet();\nweakSet1.add(obj);\nweakSet2.add(obj);\n\n// Comparing different instances fails, even with same contents\nassert.deepStrictEqual(weakSet1, weakSet2);\n// AssertionError: Values have same structure but are not reference-equal:\n// + actual - expected\n//\n// WeakSet {\n// <items unknown>\n// }\n\n// Comparing the same instance to itself succeeds\nassert.deepStrictEqual(weakSet1, weakSet1);\n// OK\n\nIf the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message parameter is an instance of <Error> then it will be thrown instead of the AssertionError.
Expects the string input not to match the regular expression.
import assert from 'node:assert/strict';\n\nassert.doesNotMatch('I will fail', /fail/);\n// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...\n\nassert.doesNotMatch(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.doesNotMatch('I will pass', /different/);\n// OK\n\nconst assert = require('node:assert/strict');\n\nassert.doesNotMatch('I will fail', /fail/);\n// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...\n\nassert.doesNotMatch(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.doesNotMatch('I will pass', /different/);\n// OK\n\nIf the values do match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of <Error> then it will be thrown instead of the AssertionError.
Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is not rejected.
If asyncFn is a function and it throws an error synchronously,\nassert.doesNotReject() will return a rejected Promise with that error. If\nthe function does not return a promise, assert.doesNotReject() will return a\nrejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases\nthe error handler is skipped.
Using assert.doesNotReject() is actually not useful because there is little\nbenefit in catching a rejection and then rejecting it again. Instead, consider\nadding a comment next to the specific code path that should not reject and keep\nerror messages as expressive as possible.
If specified, error can be a Class, <RegExp> or a validation\nfunction. See assert.throws() for more details.
Besides the async nature to await the completion behaves identically to\nassert.doesNotThrow().
import assert from 'node:assert/strict';\n\nawait assert.doesNotReject(\n async () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError,\n);\n\nconst assert = require('node:assert/strict');\n\n(async () => {\n await assert.doesNotReject(\n async () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError,\n );\n})();\n\nimport assert from 'node:assert/strict';\n\nassert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n .then(() => {\n // ...\n });\n\nconst assert = require('node:assert/strict');\n\nassert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n .then(() => {\n // ...\n });\n"
},
{
"textRaw": "`assert.doesNotThrow(fn[, error][, message])`",
"name": "doesNotThrow",
"type": "method",
"meta": {
"added": [
"v0.1.21"
],
"changes": [
{
"version": [
"v5.11.0",
"v4.4.5"
],
"pr-url": "https://github.com/nodejs/node/pull/2407",
"description": "The `message` parameter is respected now."
},
{
"version": "v4.2.0",
"pr-url": "https://github.com/nodejs/node/pull/3276",
"description": "The `error` parameter can now be an arrow function."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function}",
"name": "fn",
"type": "Function"
},
{
"textRaw": "`error` {RegExp|Function}",
"name": "error",
"type": "RegExp|Function",
"optional": true
},
{
"textRaw": "`message` {string}",
"name": "message",
"type": "string",
"optional": true
}
]
}
],
"desc": "Asserts that the function fn does not throw an error.
Using assert.doesNotThrow() is actually not useful because there\nis no benefit in catching an error and then rethrowing it. Instead, consider\nadding a comment next to the specific code path that should not throw and keep\nerror messages as expressive as possible.
When assert.doesNotThrow() is called, it will immediately call the fn\nfunction.
If an error is thrown and it is the same type as that specified by the error\nparameter, then an AssertionError is thrown. If the error is of a\ndifferent type, or if the error parameter is undefined, the error is\npropagated back to the caller.
If specified, error can be a Class, <RegExp>, or a validation\nfunction. See assert.throws() for more details.
The following, for instance, will throw the <TypeError> because there is no\nmatching error type in the assertion:
import assert from 'node:assert/strict';\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError,\n);\n\nconst assert = require('node:assert/strict');\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError,\n);\n\nHowever, the following will result in an AssertionError with the message\n'Got unwanted exception...':
import assert from 'node:assert/strict';\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n TypeError,\n);\n\nconst assert = require('node:assert/strict');\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n TypeError,\n);\n\nIf an AssertionError is thrown and a value is provided for the message\nparameter, the value of message will be appended to the AssertionError\nmessage:
import assert from 'node:assert/strict';\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n /Wrong value/,\n 'Whoops',\n);\n// Throws: AssertionError: Got unwanted exception: Whoops\n\nconst assert = require('node:assert/strict');\n\nassert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n /Wrong value/,\n 'Whoops',\n);\n// Throws: AssertionError: Got unwanted exception: Whoops\n"
},
{
"textRaw": "`assert.equal(actual, expected[, message])`",
"name": "equal",
"type": "method",
"meta": {
"added": [
"v0.1.21"
],
"changes": [
{
"version": [
"v16.0.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38113",
"description": "In Legacy assertion mode, changed status from Deprecated to Legacy."
},
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/30766",
"description": "NaN is now treated as being identical if both sides are NaN."
}
]
},
"stability": 3,
"stabilityText": "Legacy: Use `assert.strictEqual()` instead.",
"signatures": [
{
"params": [
{
"textRaw": "`actual` {any}",
"name": "actual",
"type": "any"
},
{
"textRaw": "`expected` {any}",
"name": "expected",
"type": "any"
},
{
"textRaw": "`message` {string|Error}",
"name": "message",
"type": "string|Error",
"optional": true
}
]
}
],
"desc": "Strict assertion mode
\nAn alias of assert.strictEqual().
Legacy assertion mode
\nTests shallow, coercive equality between the actual and expected parameters\nusing the == operator. NaN is specially handled\nand treated as being identical if both sides are NaN.
import assert from 'node:assert';\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\nassert.equal(NaN, NaN);\n// OK\n\nassert.equal(1, 2);\n// AssertionError: 1 == 2\nassert.equal({ a: { b: 1 } }, { a: { b: 1 } });\n// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }\n\nconst assert = require('node:assert');\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\nassert.equal(NaN, NaN);\n// OK\n\nassert.equal(1, 2);\n// AssertionError: 1 == 2\nassert.equal({ a: { b: 1 } }, { a: { b: 1 } });\n// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }\n\nIf the values are not equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message parameter is an instance of <Error> then it will be thrown instead of the AssertionError.
Throws an AssertionError with the provided error message or a default\nerror message. If the message parameter is an instance of <Error> then\nit will be thrown instead of the AssertionError.
import assert from 'node:assert/strict';\n\nassert.fail();\n// AssertionError [ERR_ASSERTION]: Failed\n\nassert.fail('boom');\n// AssertionError [ERR_ASSERTION]: boom\n\nassert.fail(new TypeError('need array'));\n// TypeError: need array\n\nconst assert = require('node:assert/strict');\n\nassert.fail();\n// AssertionError [ERR_ASSERTION]: Failed\n\nassert.fail('boom');\n// AssertionError [ERR_ASSERTION]: boom\n\nassert.fail(new TypeError('need array'));\n// TypeError: need array\n"
},
{
"textRaw": "`assert.ifError(value)`",
"name": "ifError",
"type": "method",
"meta": {
"added": [
"v0.1.97"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18247",
"description": "Instead of throwing the original error it is now wrapped into an [`AssertionError`][] that contains the full stack trace."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18247",
"description": "Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Throws value if value is not undefined or null. This is useful when\ntesting the error argument in callbacks. The stack trace contains all frames\nfrom the error passed to ifError() including the potential new frames for\nifError() itself.
import assert from 'node:assert/strict';\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0\nassert.ifError('error');\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'\nassert.ifError(new Error());\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error\n\n// Create some random error frames.\nlet err;\n(function errorFrame() {\n err = new Error('test error');\n})();\n\n(function ifErrorFrame() {\n assert.ifError(err);\n})();\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error\n// at ifErrorFrame\n// at errorFrame\n\nconst assert = require('node:assert/strict');\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0\nassert.ifError('error');\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'\nassert.ifError(new Error());\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error\n\n// Create some random error frames.\nlet err;\n(function errorFrame() {\n err = new Error('test error');\n})();\n\n(function ifErrorFrame() {\n assert.ifError(err);\n})();\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error\n// at ifErrorFrame\n// at errorFrame\n"
},
{
"textRaw": "`assert.match(string, regexp[, message])`",
"name": "match",
"type": "method",
"meta": {
"added": [
"v13.6.0",
"v12.16.0"
],
"changes": [
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/38111",
"description": "This API is no longer experimental."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`string` {string}",
"name": "string",
"type": "string"
},
{
"textRaw": "`regexp` {RegExp}",
"name": "regexp",
"type": "RegExp"
},
{
"textRaw": "`message` {string|Error}",
"name": "message",
"type": "string|Error",
"optional": true
}
]
}
],
"desc": "Expects the string input to match the regular expression.
import assert from 'node:assert/strict';\n\nassert.match('I will fail', /pass/);\n// AssertionError [ERR_ASSERTION]: The input did not match the regular ...\n\nassert.match(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.match('I will pass', /pass/);\n// OK\n\nconst assert = require('node:assert/strict');\n\nassert.match('I will fail', /pass/);\n// AssertionError [ERR_ASSERTION]: The input did not match the regular ...\n\nassert.match(123, /pass/);\n// AssertionError [ERR_ASSERTION]: The \"string\" argument must be of type string.\n\nassert.match('I will pass', /pass/);\n// OK\n\nIf the values do not match, or if the string argument is of another type than\nstring, an AssertionError is thrown with a message property set equal\nto the value of the message parameter. If the message parameter is\nundefined, a default error message is assigned. If the message parameter is an\ninstance of <Error> then it will be thrown instead of the AssertionError.
Strict assertion mode
\nAn alias of assert.notDeepStrictEqual().
Legacy assertion mode
\nTests for any deep inequality. Opposite of assert.deepEqual().
import assert from 'node:assert';\n\nconst obj1 = {\n a: {\n b: 1,\n },\n};\nconst obj2 = {\n a: {\n b: 2,\n },\n};\nconst obj3 = {\n a: {\n b: 1,\n },\n};\nconst obj4 = { __proto__: obj1 };\n\nassert.notDeepEqual(obj1, obj1);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n// OK\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK\n\nconst assert = require('node:assert');\n\nconst obj1 = {\n a: {\n b: 1,\n },\n};\nconst obj2 = {\n a: {\n b: 2,\n },\n};\nconst obj3 = {\n a: {\n b: 1,\n },\n};\nconst obj4 = { __proto__: obj1 };\n\nassert.notDeepEqual(obj1, obj1);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n// OK\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK\n\nIf the values are deeply equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of <Error> then it will be thrown\ninstead of the AssertionError.
Tests for deep strict inequality. Opposite of assert.deepStrictEqual().
import assert from 'node:assert/strict';\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n\nconst assert = require('node:assert/strict');\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n\nIf the values are deeply and strictly equal, an AssertionError is thrown\nwith a message property set equal to the value of the message parameter. If\nthe message parameter is undefined, a default error message is assigned. If\nthe message parameter is an instance of <Error> then it will be thrown\ninstead of the AssertionError.
Strict assertion mode
\nAn alias of assert.notStrictEqual().
Legacy assertion mode
\nTests shallow, coercive inequality with the != operator. NaN is\nspecially handled and treated as being identical if both sides are NaN.
import assert from 'node:assert';\n\nassert.notEqual(1, 2);\n// OK\n\nassert.notEqual(1, 1);\n// AssertionError: 1 != 1\n\nassert.notEqual(1, '1');\n// AssertionError: 1 != '1'\n\nconst assert = require('node:assert');\n\nassert.notEqual(1, 2);\n// OK\n\nassert.notEqual(1, 1);\n// AssertionError: 1 != 1\n\nassert.notEqual(1, '1');\n// AssertionError: 1 != '1'\n\nIf the values are equal, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message parameter is an instance of <Error> then it will be thrown instead of the AssertionError.
Tests strict inequality between the actual and expected parameters as\ndetermined by Object.is().
import assert from 'node:assert/strict';\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError [ERR_ASSERTION]: Expected \"actual\" to be strictly unequal to:\n//\n// 1\n\nassert.notStrictEqual(1, '1');\n// OK\n\nconst assert = require('node:assert/strict');\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError [ERR_ASSERTION]: Expected \"actual\" to be strictly unequal to:\n//\n// 1\n\nassert.notStrictEqual(1, '1');\n// OK\n\nIf the values are strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of <Error> then it will be thrown\ninstead of the AssertionError.
Tests if value is truthy. It is equivalent to\nassert.equal(!!value, true, message).
If value is not truthy, an AssertionError is thrown with a message\nproperty set equal to the value of the message parameter. If the message\nparameter is undefined, a default error message is assigned. If the message parameter is an instance of <Error> then it will be thrown instead of the AssertionError.\nIf no arguments are passed in at all message will be set to the string:\n'No value argument passed to `assert.ok()`'.
Be aware that in the repl the error message will be different to the one\nthrown in a file! See below for further details.
import assert from 'node:assert/strict';\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\n\nassert.ok();\n// AssertionError: No value argument passed to `assert.ok()`\n\nassert.ok(false, 'it\\'s false');\n// AssertionError: it's false\n\n// In the repl:\nassert.ok(typeof 123 === 'string');\n// AssertionError: false == true\n\n// In a file (e.g. test.js):\nassert.ok(typeof 123 === 'string');\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(typeof 123 === 'string')\n\nassert.ok(false);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(false)\n\nassert.ok(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(0)\n\nconst assert = require('node:assert/strict');\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\n\nassert.ok();\n// AssertionError: No value argument passed to `assert.ok()`\n\nassert.ok(false, 'it\\'s false');\n// AssertionError: it's false\n\n// In the repl:\nassert.ok(typeof 123 === 'string');\n// AssertionError: false == true\n\n// In a file (e.g. test.js):\nassert.ok(typeof 123 === 'string');\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(typeof 123 === 'string')\n\nassert.ok(false);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(false)\n\nassert.ok(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(0)\n\nimport assert from 'node:assert/strict';\n\n// Using `assert()` works the same:\nassert(2 + 2 > 5);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert(2 + 2 > 5)\n\nconst assert = require('node:assert');\n\n// Using `assert()` works the same:\nassert(2 + 2 > 5);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert(2 + 2 > 5)\n"
},
{
"textRaw": "`assert.rejects(asyncFn[, error][, message])`",
"name": "rejects",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`asyncFn` {Function|Promise}",
"name": "asyncFn",
"type": "Function|Promise"
},
{
"textRaw": "`error` {RegExp|Function|Object|Error}",
"name": "error",
"type": "RegExp|Function|Object|Error",
"optional": true
},
{
"textRaw": "`message` {string}",
"name": "message",
"type": "string",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise}",
"name": "return",
"type": "Promise"
}
}
],
"desc": "Awaits the asyncFn promise or, if asyncFn is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is rejected.
If asyncFn is a function and it throws an error synchronously,\nassert.rejects() will return a rejected Promise with that error. If the\nfunction does not return a promise, assert.rejects() will return a rejected\nPromise with an ERR_INVALID_RETURN_VALUE error. In both cases the error\nhandler is skipped.
Besides the async nature to await the completion behaves identically to\nassert.throws().
If specified, error can be a Class, <RegExp>, a validation function,\nan object where each property will be tested for, or an instance of error where\neach property will be tested for including the non-enumerable message and\nname properties.
If specified, message will be the message provided by the AssertionError\nif the asyncFn fails to reject.
import assert from 'node:assert/strict';\n\nawait assert.rejects(\n async () => {\n throw new TypeError('Wrong value');\n },\n {\n name: 'TypeError',\n message: 'Wrong value',\n },\n);\n\nconst assert = require('node:assert/strict');\n\n(async () => {\n await assert.rejects(\n async () => {\n throw new TypeError('Wrong value');\n },\n {\n name: 'TypeError',\n message: 'Wrong value',\n },\n );\n})();\n\nimport assert from 'node:assert/strict';\n\nawait assert.rejects(\n async () => {\n throw new TypeError('Wrong value');\n },\n (err) => {\n assert.strictEqual(err.name, 'TypeError');\n assert.strictEqual(err.message, 'Wrong value');\n return true;\n },\n);\n\nconst assert = require('node:assert/strict');\n\n(async () => {\n await assert.rejects(\n async () => {\n throw new TypeError('Wrong value');\n },\n (err) => {\n assert.strictEqual(err.name, 'TypeError');\n assert.strictEqual(err.message, 'Wrong value');\n return true;\n },\n );\n})();\n\nimport assert from 'node:assert/strict';\n\nassert.rejects(\n Promise.reject(new Error('Wrong value')),\n Error,\n).then(() => {\n // ...\n});\n\nconst assert = require('node:assert/strict');\n\nassert.rejects(\n Promise.reject(new Error('Wrong value')),\n Error,\n).then(() => {\n // ...\n});\n\nerror cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Please read the\nexample in assert.throws() carefully if using a string as the second\nargument gets considered.
Tests strict equality between the actual and expected parameters as\ndetermined by Object.is().
import assert from 'node:assert/strict';\n\nassert.strictEqual(1, 2);\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n//\n// 1 !== 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual('Hello foobar', 'Hello World!');\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n// + actual - expected\n//\n// + 'Hello foobar'\n// - 'Hello World!'\n// ^\n\nconst apples = 1;\nconst oranges = 2;\nassert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);\n// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2\n\nassert.strictEqual(1, '1', new TypeError('Inputs are not identical'));\n// TypeError: Inputs are not identical\n\nconst assert = require('node:assert/strict');\n\nassert.strictEqual(1, 2);\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n//\n// 1 !== 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual('Hello foobar', 'Hello World!');\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n// + actual - expected\n//\n// + 'Hello foobar'\n// - 'Hello World!'\n// ^\n\nconst apples = 1;\nconst oranges = 2;\nassert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);\n// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2\n\nassert.strictEqual(1, '1', new TypeError('Inputs are not identical'));\n// TypeError: Inputs are not identical\n\nIf the values are not strictly equal, an AssertionError is thrown with a\nmessage property set equal to the value of the message parameter. If the\nmessage parameter is undefined, a default error message is assigned. If the\nmessage parameter is an instance of <Error> then it will be thrown\ninstead of the AssertionError.
Expects the function fn to throw an error.
If specified, error can be a Class, <RegExp>, a validation function,\na validation object where each property will be tested for strict deep equality,\nor an instance of error where each property will be tested for strict deep\nequality including the non-enumerable message and name properties. When\nusing an object, it is also possible to use a regular expression, when\nvalidating against a string property. See below for examples.
If specified, message will be appended to the message provided by the\nAssertionError if the fn call fails to throw or in case the error validation\nfails.
Custom validation object/error instance:
\nimport assert from 'node:assert/strict';\n\nconst err = new TypeError('Wrong value');\nerr.code = 404;\nerr.foo = 'bar';\nerr.info = {\n nested: true,\n baz: 'text',\n};\nerr.reg = /abc/i;\n\nassert.throws(\n () => {\n throw err;\n },\n {\n name: 'TypeError',\n message: 'Wrong value',\n info: {\n nested: true,\n baz: 'text',\n },\n // Only properties on the validation object will be tested for.\n // Using nested objects requires all properties to be present. Otherwise\n // the validation is going to fail.\n },\n);\n\n// Using regular expressions to validate error properties:\nassert.throws(\n () => {\n throw err;\n },\n {\n // The `name` and `message` properties are strings and using regular\n // expressions on those will match against the string. If they fail, an\n // error is thrown.\n name: /^TypeError$/,\n message: /Wrong/,\n foo: 'bar',\n info: {\n nested: true,\n // It is not possible to use regular expressions for nested properties!\n baz: 'text',\n },\n // The `reg` property contains a regular expression and only if the\n // validation object contains an identical regular expression, it is going\n // to pass.\n reg: /abc/i,\n },\n);\n\n// Fails due to the different `message` and `name` properties:\nassert.throws(\n () => {\n const otherErr = new Error('Not found');\n // Copy all enumerable properties from `err` to `otherErr`.\n for (const [key, value] of Object.entries(err)) {\n otherErr[key] = value;\n }\n throw otherErr;\n },\n // The error's `message` and `name` properties will also be checked when using\n // an error as validation object.\n err,\n);\n\nconst assert = require('node:assert/strict');\n\nconst err = new TypeError('Wrong value');\nerr.code = 404;\nerr.foo = 'bar';\nerr.info = {\n nested: true,\n baz: 'text',\n};\nerr.reg = /abc/i;\n\nassert.throws(\n () => {\n throw err;\n },\n {\n name: 'TypeError',\n message: 'Wrong value',\n info: {\n nested: true,\n baz: 'text',\n },\n // Only properties on the validation object will be tested for.\n // Using nested objects requires all properties to be present. Otherwise\n // the validation is going to fail.\n },\n);\n\n// Using regular expressions to validate error properties:\nassert.throws(\n () => {\n throw err;\n },\n {\n // The `name` and `message` properties are strings and using regular\n // expressions on those will match against the string. If they fail, an\n // error is thrown.\n name: /^TypeError$/,\n message: /Wrong/,\n foo: 'bar',\n info: {\n nested: true,\n // It is not possible to use regular expressions for nested properties!\n baz: 'text',\n },\n // The `reg` property contains a regular expression and only if the\n // validation object contains an identical regular expression, it is going\n // to pass.\n reg: /abc/i,\n },\n);\n\n// Fails due to the different `message` and `name` properties:\nassert.throws(\n () => {\n const otherErr = new Error('Not found');\n // Copy all enumerable properties from `err` to `otherErr`.\n for (const [key, value] of Object.entries(err)) {\n otherErr[key] = value;\n }\n throw otherErr;\n },\n // The error's `message` and `name` properties will also be checked when using\n // an error as validation object.\n err,\n);\n\nValidate instanceof using constructor:
\nimport assert from 'node:assert/strict';\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n Error,\n);\n\nconst assert = require('node:assert/strict');\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n Error,\n);\n\nValidate error message using <RegExp>:
Using a regular expression runs .toString on the error object, and will\ntherefore also include the error name.
import assert from 'node:assert/strict';\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n /^Error: Wrong value$/,\n);\n\nconst assert = require('node:assert/strict');\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n /^Error: Wrong value$/,\n);\n\nCustom error validation:
\nThe function must return true to indicate all internal validations passed.\nIt will otherwise fail with an AssertionError.
import assert from 'node:assert/strict';\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n (err) => {\n assert(err instanceof Error);\n assert(/value/.test(err));\n // Avoid returning anything from validation functions besides `true`.\n // Otherwise, it's not clear what part of the validation failed. Instead,\n // throw an error about the specific validation that failed (as done in this\n // example) and add as much helpful debugging information to that error as\n // possible.\n return true;\n },\n 'unexpected error',\n);\n\nconst assert = require('node:assert/strict');\n\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n (err) => {\n assert(err instanceof Error);\n assert(/value/.test(err));\n // Avoid returning anything from validation functions besides `true`.\n // Otherwise, it's not clear what part of the validation failed. Instead,\n // throw an error about the specific validation that failed (as done in this\n // example) and add as much helpful debugging information to that error as\n // possible.\n return true;\n },\n 'unexpected error',\n);\n\nerror cannot be a string. If a string is provided as the second\nargument, then error is assumed to be omitted and the string will be used for\nmessage instead. This can lead to easy-to-miss mistakes. Using the same\nmessage as the thrown error message is going to result in an\nERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using\na string as the second argument gets considered:
import assert from 'node:assert/strict';\n\nfunction throwingFirst() {\n throw new Error('First');\n}\n\nfunction throwingSecond() {\n throw new Error('Second');\n}\n\nfunction notThrowing() {}\n\n// The second argument is a string and the input function threw an Error.\n// The first case will not throw as it does not match for the error message\n// thrown by the input function!\nassert.throws(throwingFirst, 'Second');\n// In the next example the message has no benefit over the message from the\n// error and since it is not clear if the user intended to actually match\n// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.\nassert.throws(throwingSecond, 'Second');\n// TypeError [ERR_AMBIGUOUS_ARGUMENT]\n\n// The string is only used (as message) in case the function does not throw:\nassert.throws(notThrowing, 'Second');\n// AssertionError [ERR_ASSERTION]: Missing expected exception: Second\n\n// If it was intended to match for the error message do this instead:\n// It does not throw because the error messages match.\nassert.throws(throwingSecond, /Second$/);\n\n// If the error message does not match, an AssertionError is thrown.\nassert.throws(throwingFirst, /Second$/);\n// AssertionError [ERR_ASSERTION]\n\nconst assert = require('node:assert/strict');\n\nfunction throwingFirst() {\n throw new Error('First');\n}\n\nfunction throwingSecond() {\n throw new Error('Second');\n}\n\nfunction notThrowing() {}\n\n// The second argument is a string and the input function threw an Error.\n// The first case will not throw as it does not match for the error message\n// thrown by the input function!\nassert.throws(throwingFirst, 'Second');\n// In the next example the message has no benefit over the message from the\n// error and since it is not clear if the user intended to actually match\n// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.\nassert.throws(throwingSecond, 'Second');\n// TypeError [ERR_AMBIGUOUS_ARGUMENT]\n\n// The string is only used (as message) in case the function does not throw:\nassert.throws(notThrowing, 'Second');\n// AssertionError [ERR_ASSERTION]: Missing expected exception: Second\n\n// If it was intended to match for the error message do this instead:\n// It does not throw because the error messages match.\nassert.throws(throwingSecond, /Second$/);\n\n// If the error message does not match, an AssertionError is thrown.\nassert.throws(throwingFirst, /Second$/);\n// AssertionError [ERR_ASSERTION]\n\nDue to the confusing error-prone notation, avoid a string as the second\nargument.
" }, { "textRaw": "`assert.partialDeepStrictEqual(actual, expected[, message])`", "name": "partialDeepStrictEqual", "type": "method", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [ { "version": "v25.0.0", "pr-url": "https://github.com/nodejs/node/pull/59448", "description": "Promises are not considered equal anymore if they are not of the same instance." }, { "version": "v25.0.0", "pr-url": "https://github.com/nodejs/node/pull/57627", "description": "Invalid dates are now considered equal." }, { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57370", "description": "partialDeepStrictEqual is now Stable. Previously, it had been Experimental." } ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any}", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any}", "name": "expected", "type": "any" }, { "textRaw": "`message` {string|Error}", "name": "message", "type": "string|Error", "optional": true } ] } ], "desc": "Tests for partial deep equality between the actual and expected parameters.\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare recursively evaluated also by the following rules. \"Partial\" equality means\nthat only properties that exist on the expected parameter are going to be\ncompared.
This method always passes the same test cases as assert.deepStrictEqual(),\nbehaving as a super set of it.
Object.is().[[Prototype]] of objects are not compared.<Error> names, messages, causes, and errors are always compared,\neven if these are not enumerable properties. errors is also compared.<Symbol> properties are compared as well.Object properties are compared unordered.<Map> keys and <Set> items are compared unordered.<WeakMap>, <WeakSet> and <Promise> instances are not compared\nstructurally. They are only equal if they reference the same object. Any\ncomparison between different WeakMap, WeakSet, or Promise instances\nwill result in inequality, even if they contain the same content.<RegExp> lastIndex, flags, and source are always compared, even if these\nare not enumerable properties.import assert from 'node:assert';\n\nassert.partialDeepStrictEqual(\n { a: { b: { c: 1 } } },\n { a: { b: { c: 1 } } },\n);\n// OK\n\nassert.partialDeepStrictEqual(\n { a: 1, b: 2, c: 3 },\n { b: 2 },\n);\n// OK\n\nassert.partialDeepStrictEqual(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [4, 5, 8],\n);\n// OK\n\nassert.partialDeepStrictEqual(\n new Set([{ a: 1 }, { b: 1 }]),\n new Set([{ a: 1 }]),\n);\n// OK\n\nassert.partialDeepStrictEqual(\n new Map([['key1', 'value1'], ['key2', 'value2']]),\n new Map([['key2', 'value2']]),\n);\n// OK\n\nassert.partialDeepStrictEqual(123n, 123n);\n// OK\n\nassert.partialDeepStrictEqual(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [5, 4, 8],\n);\n// AssertionError\n\nassert.partialDeepStrictEqual(\n { a: 1 },\n { a: 1, b: 2 },\n);\n// AssertionError\n\nassert.partialDeepStrictEqual(\n { a: { b: 2 } },\n { a: { b: '2' } },\n);\n// AssertionError\n\nconst assert = require('node:assert');\n\nassert.partialDeepStrictEqual(\n { a: { b: { c: 1 } } },\n { a: { b: { c: 1 } } },\n);\n// OK\n\nassert.partialDeepStrictEqual(\n { a: 1, b: 2, c: 3 },\n { b: 2 },\n);\n// OK\n\nassert.partialDeepStrictEqual(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [4, 5, 8],\n);\n// OK\n\nassert.partialDeepStrictEqual(\n new Set([{ a: 1 }, { b: 1 }]),\n new Set([{ a: 1 }]),\n);\n// OK\n\nassert.partialDeepStrictEqual(\n new Map([['key1', 'value1'], ['key2', 'value2']]),\n new Map([['key2', 'value2']]),\n);\n// OK\n\nassert.partialDeepStrictEqual(123n, 123n);\n// OK\n\nassert.partialDeepStrictEqual(\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [5, 4, 8],\n);\n// AssertionError\n\nassert.partialDeepStrictEqual(\n { a: 1 },\n { a: 1, b: 2 },\n);\n// AssertionError\n\nassert.partialDeepStrictEqual(\n { a: { b: 2 } },\n { a: { b: '2' } },\n);\n// AssertionError\n",
"displayName": "Comparison details"
}
]
}
],
"displayName": "Assert",
"source": "doc/api/assert.md"
},
{
"textRaw": "Asynchronous context tracking",
"name": "asynchronous_context_tracking",
"introduced_in": "v16.4.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"modules": [
{
"textRaw": "Introduction",
"name": "introduction",
"type": "module",
"desc": "These classes are used to associate state and propagate it throughout\ncallbacks and promise chains.\nThey allow storing data throughout the lifetime of a web request\nor any other asynchronous duration. It is similar to thread-local storage\nin other languages.
\nThe AsyncLocalStorage and AsyncResource classes are part of the\nnode:async_hooks module:
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';\n\nconst { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');\n",
"displayName": "Introduction"
}
],
"classes": [
{
"textRaw": "Class: `AsyncLocalStorage`",
"name": "AsyncLocalStorage",
"type": "class",
"meta": {
"added": [
"v13.10.0",
"v12.17.0"
],
"changes": [
{
"version": "v16.4.0",
"pr-url": "https://github.com/nodejs/node/pull/37675",
"description": "AsyncLocalStorage is now Stable. Previously, it had been Experimental."
}
]
},
"desc": "This class creates stores that stay coherent through asynchronous operations.
\nWhile you can create your own implementation on top of the node:async_hooks\nmodule, AsyncLocalStorage should be preferred as it is a performant and memory\nsafe implementation that involves significant optimizations that are non-obvious\nto implement.
The following example uses AsyncLocalStorage to build a simple logger\nthat assigns IDs to incoming HTTP requests and includes them in messages\nlogged within each request.
import http from 'node:http';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n const id = asyncLocalStorage.getStore();\n console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n asyncLocalStorage.run(idSeq++, () => {\n logWithId('start');\n // Imagine any chain of async operations here\n setImmediate(() => {\n logWithId('finish');\n res.end();\n });\n });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n// 0: start\n// 0: finish\n// 1: start\n// 1: finish\n\nconst http = require('node:http');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst asyncLocalStorage = new AsyncLocalStorage();\n\nfunction logWithId(msg) {\n const id = asyncLocalStorage.getStore();\n console.log(`${id !== undefined ? id : '-'}:`, msg);\n}\n\nlet idSeq = 0;\nhttp.createServer((req, res) => {\n asyncLocalStorage.run(idSeq++, () => {\n logWithId('start');\n // Imagine any chain of async operations here\n setImmediate(() => {\n logWithId('finish');\n res.end();\n });\n });\n}).listen(8080);\n\nhttp.get('http://localhost:8080');\nhttp.get('http://localhost:8080');\n// Prints:\n// 0: start\n// 0: finish\n// 1: start\n// 1: finish\n\nEach instance of AsyncLocalStorage maintains an independent storage context.\nMultiple instances can safely exist simultaneously without risk of interfering\nwith each other's data.
Creates a new instance of AsyncLocalStorage. Store is only provided within a\nrun() call or after an enterWith() call.
Binds the given function to the current execution context.
" }, { "textRaw": "Static method: `AsyncLocalStorage.snapshot()`", "name": "snapshot", "type": "classMethod", "meta": { "added": [ "v19.8.0", "v18.16.0" ], "changes": [ { "version": [ "v23.11.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/57510", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Function} A new function with the signature `(fn: (...args) : R, ...args) : R`.", "name": "return", "type": "Function", "desc": "A new function with the signature `(fn: (...args) : R, ...args) : R`." } } ], "desc": "Captures the current execution context and returns a function that accepts a\nfunction as an argument. Whenever the returned function is called, it\ncalls the function passed to it within the captured context.
\nconst asyncLocalStorage = new AsyncLocalStorage();\nconst runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());\nconst result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));\nconsole.log(result); // returns 123\n\nAsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple\nasync context tracking purposes, for example:
\nclass Foo {\n #runInAsyncScope = AsyncLocalStorage.snapshot();\n\n get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }\n}\n\nconst foo = asyncLocalStorage.run(123, () => new Foo());\nconsole.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123\n"
}
],
"methods": [
{
"textRaw": "`asyncLocalStorage.disable()`",
"name": "disable",
"type": "method",
"meta": {
"added": [
"v13.10.0",
"v12.17.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": []
}
],
"desc": "Disables the instance of AsyncLocalStorage. All subsequent calls\nto asyncLocalStorage.getStore() will return undefined until\nasyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.
When calling asyncLocalStorage.disable(), all current contexts linked to the\ninstance will be exited.
Calling asyncLocalStorage.disable() is required before the\nasyncLocalStorage can be garbage collected. This does not apply to stores\nprovided by the asyncLocalStorage, as those objects are garbage collected\nalong with the corresponding async resources.
Use this method when the asyncLocalStorage is not in use anymore\nin the current process.
Returns the current store.\nIf called outside of an asynchronous context initialized by\ncalling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it\nreturns undefined.
Transitions into the context for the remainder of the current\nsynchronous execution and then persists the store through any following\nasynchronous calls.
\nExample:
\nconst store = { id: 1 };\n// Replaces previous store with the given store object\nasyncLocalStorage.enterWith(store);\nasyncLocalStorage.getStore(); // Returns the store object\nsomeAsyncOperation(() => {\n asyncLocalStorage.getStore(); // Returns the same object\n});\n\nThis transition will continue for the entire synchronous execution.\nThis means that if, for example, the context is entered within an event\nhandler subsequent event handlers will also run within that context unless\nspecifically bound to another context with an AsyncResource. That is why\nrun() should be preferred over enterWith() unless there are strong reasons\nto use the latter method.
const store = { id: 1 };\n\nemitter.on('my-event', () => {\n asyncLocalStorage.enterWith(store);\n});\nemitter.on('my-event', () => {\n asyncLocalStorage.getStore(); // Returns the same object\n});\n\nasyncLocalStorage.getStore(); // Returns undefined\nemitter.emit('my-event');\nasyncLocalStorage.getStore(); // Returns the same object\n"
},
{
"textRaw": "`asyncLocalStorage.run(store, callback[, ...args])`",
"name": "run",
"type": "method",
"meta": {
"added": [
"v13.10.0",
"v12.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`store` {any}",
"name": "store",
"type": "any"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "Runs a function synchronously within a context and returns its\nreturn value. The store is not accessible outside of the callback function.\nThe store is accessible to any asynchronous operations created within the\ncallback.
\nThe optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by run() too.\nThe stacktrace is not impacted by this call and the context is exited.
Example:
\nconst store = { id: 2 };\ntry {\n asyncLocalStorage.run(store, () => {\n asyncLocalStorage.getStore(); // Returns the store object\n setTimeout(() => {\n asyncLocalStorage.getStore(); // Returns the store object\n }, 200);\n throw new Error();\n });\n} catch (e) {\n asyncLocalStorage.getStore(); // Returns undefined\n // The error will be caught here\n}\n"
},
{
"textRaw": "`asyncLocalStorage.exit(callback[, ...args])`",
"name": "exit",
"type": "method",
"meta": {
"added": [
"v13.10.0",
"v12.17.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function"
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "Runs a function synchronously outside of a context and returns its\nreturn value. The store is not accessible within the callback function or\nthe asynchronous operations created within the callback. Any getStore()\ncall done within the callback function will always return undefined.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by exit() too.\nThe stacktrace is not impacted by this call and the context is re-entered.
Example:
\n// Within a call to run\ntry {\n asyncLocalStorage.getStore(); // Returns the store object or value\n asyncLocalStorage.exit(() => {\n asyncLocalStorage.getStore(); // Returns undefined\n throw new Error();\n });\n} catch (e) {\n asyncLocalStorage.getStore(); // Returns the same object or value\n // The error will be caught here\n}\n"
}
],
"properties": [
{
"textRaw": "Type: {string}",
"name": "name",
"type": "string",
"meta": {
"added": [
"v24.0.0"
],
"changes": []
},
"desc": "The name of the AsyncLocalStorage instance if provided.
If, within an async function, only one await call is to run within a context,\nthe following pattern should be used:
async function fn() {\n await asyncLocalStorage.run(new Map(), () => {\n asyncLocalStorage.getStore().set('key', value);\n return foo(); // The return value of foo will be awaited\n });\n}\n\nIn this example, the store is only available in the callback function and the\nfunctions called by foo. Outside of run, calling getStore will return\nundefined.
In most cases, AsyncLocalStorage works without issues. In rare situations, the\ncurrent store is lost in one of the asynchronous operations.
If your code is callback-based, it is enough to promisify it with\nutil.promisify() so it starts working with native promises.
If you need to use a callback-based API or your code assumes\na custom thenable implementation, use the AsyncResource class\nto associate the asynchronous operation with the correct execution context.\nFind the function call responsible for the context loss by logging the content\nof asyncLocalStorage.getStore() after the calls you suspect are responsible\nfor the loss. When the code logs undefined, the last callback called is\nprobably responsible for the context loss.
The class AsyncResource is designed to be extended by the embedder's async\nresources. Using this, users can easily trigger the lifetime events of their\nown resources.
The init hook will trigger when an AsyncResource is instantiated.
The following is an overview of the AsyncResource API.
import { AsyncResource, executionAsyncId } from 'node:async_hooks';\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n\nconst { AsyncResource, executionAsyncId } = require('node:async_hooks');\n\n// AsyncResource() is meant to be extended. Instantiating a\n// new AsyncResource() also triggers init. If triggerAsyncId is omitted then\n// async_hook.executionAsyncId() is used.\nconst asyncResource = new AsyncResource(\n type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },\n);\n\n// Run a function in the execution context of the resource. This will\n// * establish the context of the resource\n// * trigger the AsyncHooks before callbacks\n// * call the provided function `fn` with the supplied arguments\n// * trigger the AsyncHooks after callbacks\n// * restore the original execution context\nasyncResource.runInAsyncScope(fn, thisArg, ...args);\n\n// Call AsyncHooks destroy callbacks.\nasyncResource.emitDestroy();\n\n// Return the unique ID assigned to the AsyncResource instance.\nasyncResource.asyncId();\n\n// Return the trigger ID for the AsyncResource instance.\nasyncResource.triggerAsyncId();\n",
"signatures": [
{
"textRaw": "`new AsyncResource(type[, options])`",
"name": "AsyncResource",
"type": "ctor",
"params": [
{
"textRaw": "`type` {string} The type of async event.",
"name": "type",
"type": "string",
"desc": "The type of async event."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`triggerAsyncId` {number} The ID of the execution context that created this async event. **Default:** `executionAsyncId()`.",
"name": "triggerAsyncId",
"type": "number",
"default": "`executionAsyncId()`",
"desc": "The ID of the execution context that created this async event."
},
{
"textRaw": "`requireManualDestroy` {boolean} If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook. **Default:** `false`.",
"name": "requireManualDestroy",
"type": "boolean",
"default": "`false`",
"desc": "If set to `true`, disables `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if `emitDestroy` is called manually), unless the resource's `asyncId` is retrieved and the sensitive API's `emitDestroy` is called with it. When set to `false`, the `emitDestroy` call on garbage collection will only take place if there is at least one active `destroy` hook."
}
],
"optional": true
}
],
"desc": "Example usage:
\nclass DBQuery extends AsyncResource {\n constructor(db) {\n super('DBQuery');\n this.db = db;\n }\n\n getInfo(query, callback) {\n this.db.get(query, (err, data) => {\n this.runInAsyncScope(callback, null, err, data);\n });\n }\n\n close() {\n this.db = null;\n this.emitDestroy();\n }\n}\n"
}
],
"classMethods": [
{
"textRaw": "Static method: `AsyncResource.bind(fn[, type[, thisArg]])`",
"name": "bind",
"type": "classMethod",
"meta": {
"added": [
"v14.8.0",
"v12.19.0"
],
"changes": [
{
"version": "v20.0.0",
"pr-url": "https://github.com/nodejs/node/pull/46432",
"description": "The `asyncResource` property added to the bound function has been deprecated and will be removed in a future version."
},
{
"version": [
"v17.8.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/42177",
"description": "Changed the default when `thisArg` is undefined to use `this` from the caller."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/36782",
"description": "Added optional thisArg."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function} The function to bind to the current execution context.",
"name": "fn",
"type": "Function",
"desc": "The function to bind to the current execution context."
},
{
"textRaw": "`type` {string} An optional name to associate with the underlying `AsyncResource`.",
"name": "type",
"type": "string",
"desc": "An optional name to associate with the underlying `AsyncResource`.",
"optional": true
},
{
"textRaw": "`thisArg` {any}",
"name": "thisArg",
"type": "any",
"optional": true
}
]
}
],
"desc": "Binds the given function to the current execution context.
" } ], "methods": [ { "textRaw": "`asyncResource.bind(fn[, thisArg])`", "name": "bind", "type": "method", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": "v20.0.0", "pr-url": "https://github.com/nodejs/node/pull/46432", "description": "The `asyncResource` property added to the bound function has been deprecated and will be removed in a future version." }, { "version": [ "v17.8.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/42177", "description": "Changed the default when `thisArg` is undefined to use `this` from the caller." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36782", "description": "Added optional thisArg." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to bind to the current `AsyncResource`.", "name": "fn", "type": "Function", "desc": "The function to bind to the current `AsyncResource`." }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any", "optional": true } ] } ], "desc": "Binds the given function to execute to this AsyncResource's scope.
Call the provided function with the provided arguments in the execution context\nof the async resource. This will establish the context, trigger the AsyncHooks\nbefore callbacks, call the function, trigger the AsyncHooks after callbacks, and\nthen restore the original execution context.
" }, { "textRaw": "`asyncResource.emitDestroy()`", "name": "emitDestroy", "type": "method", "signatures": [ { "params": [], "return": { "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", "name": "return", "type": "AsyncResource", "desc": "A reference to `asyncResource`." } } ], "desc": "Call all destroy hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This must be manually called. If\nthe resource is left to be collected by the GC then the destroy hooks will\nnever be called.
The following example shows how to use the AsyncResource class to properly\nprovide async tracking for a Worker pool. Other resource pools, such as\ndatabase connection pools, can follow a similar model.
Assuming that the task is adding two numbers, using a file named\ntask_processor.js with the following content:
import { parentPort } from 'node:worker_threads';\nparentPort.on('message', (task) => {\n parentPort.postMessage(task.a + task.b);\n});\n\nconst { parentPort } = require('node:worker_threads');\nparentPort.on('message', (task) => {\n parentPort.postMessage(task.a + task.b);\n});\n\na Worker pool around it could use the following structure:
\nimport { AsyncResource } from 'node:async_hooks';\nimport { EventEmitter } from 'node:events';\nimport { Worker } from 'node:worker_threads';\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n constructor(callback) {\n super('WorkerPoolTaskInfo');\n this.callback = callback;\n }\n\n done(err, result) {\n this.runInAsyncScope(this.callback, null, err, result);\n this.emitDestroy(); // `TaskInfo`s are used only once.\n }\n}\n\nexport default class WorkerPool extends EventEmitter {\n constructor(numThreads) {\n super();\n this.numThreads = numThreads;\n this.workers = [];\n this.freeWorkers = [];\n this.tasks = [];\n\n for (let i = 0; i < numThreads; i++)\n this.addNewWorker();\n\n // Any time the kWorkerFreedEvent is emitted, dispatch\n // the next task pending in the queue, if any.\n this.on(kWorkerFreedEvent, () => {\n if (this.tasks.length > 0) {\n const { task, callback } = this.tasks.shift();\n this.runTask(task, callback);\n }\n });\n }\n\n addNewWorker() {\n const worker = new Worker(new URL('task_processor.js', import.meta.url));\n worker.on('message', (result) => {\n // In case of success: Call the callback that was passed to `runTask`,\n // remove the `TaskInfo` associated with the Worker, and mark it as free\n // again.\n worker[kTaskInfo].done(null, result);\n worker[kTaskInfo] = null;\n this.freeWorkers.push(worker);\n this.emit(kWorkerFreedEvent);\n });\n worker.on('error', (err) => {\n // In case of an uncaught exception: Call the callback that was passed to\n // `runTask` with the error.\n if (worker[kTaskInfo])\n worker[kTaskInfo].done(err, null);\n else\n this.emit('error', err);\n // Remove the worker from the list and start a new Worker to replace the\n // current one.\n this.workers.splice(this.workers.indexOf(worker), 1);\n this.addNewWorker();\n });\n this.workers.push(worker);\n this.freeWorkers.push(worker);\n this.emit(kWorkerFreedEvent);\n }\n\n runTask(task, callback) {\n if (this.freeWorkers.length === 0) {\n // No free threads, wait until a worker thread becomes free.\n this.tasks.push({ task, callback });\n return;\n }\n\n const worker = this.freeWorkers.pop();\n worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n worker.postMessage(task);\n }\n\n close() {\n for (const worker of this.workers) worker.terminate();\n }\n}\n\nconst { AsyncResource } = require('node:async_hooks');\nconst { EventEmitter } = require('node:events');\nconst path = require('node:path');\nconst { Worker } = require('node:worker_threads');\n\nconst kTaskInfo = Symbol('kTaskInfo');\nconst kWorkerFreedEvent = Symbol('kWorkerFreedEvent');\n\nclass WorkerPoolTaskInfo extends AsyncResource {\n constructor(callback) {\n super('WorkerPoolTaskInfo');\n this.callback = callback;\n }\n\n done(err, result) {\n this.runInAsyncScope(this.callback, null, err, result);\n this.emitDestroy(); // `TaskInfo`s are used only once.\n }\n}\n\nclass WorkerPool extends EventEmitter {\n constructor(numThreads) {\n super();\n this.numThreads = numThreads;\n this.workers = [];\n this.freeWorkers = [];\n this.tasks = [];\n\n for (let i = 0; i < numThreads; i++)\n this.addNewWorker();\n\n // Any time the kWorkerFreedEvent is emitted, dispatch\n // the next task pending in the queue, if any.\n this.on(kWorkerFreedEvent, () => {\n if (this.tasks.length > 0) {\n const { task, callback } = this.tasks.shift();\n this.runTask(task, callback);\n }\n });\n }\n\n addNewWorker() {\n const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));\n worker.on('message', (result) => {\n // In case of success: Call the callback that was passed to `runTask`,\n // remove the `TaskInfo` associated with the Worker, and mark it as free\n // again.\n worker[kTaskInfo].done(null, result);\n worker[kTaskInfo] = null;\n this.freeWorkers.push(worker);\n this.emit(kWorkerFreedEvent);\n });\n worker.on('error', (err) => {\n // In case of an uncaught exception: Call the callback that was passed to\n // `runTask` with the error.\n if (worker[kTaskInfo])\n worker[kTaskInfo].done(err, null);\n else\n this.emit('error', err);\n // Remove the worker from the list and start a new Worker to replace the\n // current one.\n this.workers.splice(this.workers.indexOf(worker), 1);\n this.addNewWorker();\n });\n this.workers.push(worker);\n this.freeWorkers.push(worker);\n this.emit(kWorkerFreedEvent);\n }\n\n runTask(task, callback) {\n if (this.freeWorkers.length === 0) {\n // No free threads, wait until a worker thread becomes free.\n this.tasks.push({ task, callback });\n return;\n }\n\n const worker = this.freeWorkers.pop();\n worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);\n worker.postMessage(task);\n }\n\n close() {\n for (const worker of this.workers) worker.terminate();\n }\n}\n\nmodule.exports = WorkerPool;\n\nWithout the explicit tracking added by the WorkerPoolTaskInfo objects,\nit would appear that the callbacks are associated with the individual Worker\nobjects. However, the creation of the Workers is not associated with the\ncreation of the tasks and does not provide information about when tasks\nwere scheduled.
This pool could be used as follows:
\nimport WorkerPool from './worker_pool.js';\nimport os from 'node:os';\n\nconst pool = new WorkerPool(os.availableParallelism());\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n pool.runTask({ a: 42, b: 100 }, (err, result) => {\n console.log(i, err, result);\n if (++finished === 10)\n pool.close();\n });\n}\n\nconst WorkerPool = require('./worker_pool.js');\nconst os = require('node:os');\n\nconst pool = new WorkerPool(os.availableParallelism());\n\nlet finished = 0;\nfor (let i = 0; i < 10; i++) {\n pool.runTask({ a: 42, b: 100 }, (err, result) => {\n console.log(i, err, result);\n if (++finished === 10)\n pool.close();\n });\n}\n",
"displayName": "Using `AsyncResource` for a `Worker` thread pool"
},
{
"textRaw": "Integrating `AsyncResource` with `EventEmitter`",
"name": "integrating_`asyncresource`_with_`eventemitter`",
"type": "module",
"desc": "Event listeners triggered by an EventEmitter may be run in a different\nexecution context than the one that was active when eventEmitter.on() was\ncalled.
The following example shows how to use the AsyncResource class to properly\nassociate an event listener with the correct execution context. The same\napproach can be applied to a Stream or a similar event-driven class.
import { createServer } from 'node:http';\nimport { AsyncResource, executionAsyncId } from 'node:async_hooks';\n\nconst server = createServer((req, res) => {\n req.on('close', AsyncResource.bind(() => {\n // Execution context is bound to the current outer scope.\n }));\n req.on('close', () => {\n // Execution context is bound to the scope that caused 'close' to emit.\n });\n res.end();\n}).listen(3000);\n\nconst { createServer } = require('node:http');\nconst { AsyncResource, executionAsyncId } = require('node:async_hooks');\n\nconst server = createServer((req, res) => {\n req.on('close', AsyncResource.bind(() => {\n // Execution context is bound to the current outer scope.\n }));\n req.on('close', () => {\n // Execution context is bound to the scope that caused 'close' to emit.\n });\n res.end();\n}).listen(3000);\n",
"displayName": "Integrating `AsyncResource` with `EventEmitter`"
}
]
}
],
"displayName": "Asynchronous context tracking",
"source": "doc/api/async_context.md"
},
{
"textRaw": "Async hooks",
"name": "async_hooks",
"introduced_in": "v8.1.0",
"type": "module",
"stability": 1,
"stabilityText": "Experimental. Please migrate away from this API, if you can. We do not recommend using the `createHook`, `AsyncHook`, and `executionAsyncResource` APIs as they have usability issues, safety risks, and performance implications. Async context tracking use cases are better served by the stable `AsyncLocalStorage` API. If you have a use case for `createHook`, `AsyncHook`, or `executionAsyncResource` beyond the context tracking need solved by `AsyncLocalStorage` or diagnostics data currently provided by Diagnostics Channel, please open an issue at https://github.com/nodejs/node/issues describing your use case so we can create a more purpose-focused API.",
"desc": "We strongly discourage the use of the async_hooks API.\nOther APIs that can cover most of its use cases include:
AsyncLocalStorage tracks async contextprocess.getActiveResourcesInfo() tracks active resourcesThe node:async_hooks module provides an API to track asynchronous resources.\nIt can be accessed using:
import async_hooks from 'node:async_hooks';\n\nconst async_hooks = require('node:async_hooks');\n",
"modules": [
{
"textRaw": "Terminology",
"name": "terminology",
"type": "module",
"desc": "An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, such as the 'connection'\nevent in net.createServer(), or just a single time like in fs.open().\nA resource can also be closed before the callback is called. AsyncHook does\nnot explicitly distinguish between these different cases but will represent them\nas the abstract concept that is a resource.
If Workers are used, each thread has an independent async_hooks\ninterface, and each thread will use a new set of async IDs.
Following is a simple overview of the public API.
\nimport async_hooks from 'node:async_hooks';\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n\nconst async_hooks = require('node:async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n",
"displayName": "Overview"
},
{
"textRaw": "Promise execution tracking",
"name": "promise_execution_tracking",
"type": "module",
"desc": "By default, promise executions are not assigned asyncIds due to the relatively\nexpensive nature of the promise introspection API provided by\nV8. This means that programs using promises or async/await will not get\ncorrect execution and trigger ids for promise callback contexts by default.
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';\n\nPromise.resolve(1729).then(() => {\n console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n\nconst { executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\nPromise.resolve(1729).then(() => {\n console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n\nObserve that the then() callback claims to have executed in the context of the\nouter scope even though there was an asynchronous hop involved. Also,\nthe triggerAsyncId value is 0, which means that we are missing context about\nthe resource that caused (triggered) the then() callback to be executed.
Installing async hooks via async_hooks.createHook enables promise execution\ntracking:
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n\nconst { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n\nIn this example, adding any actual hook function enabled the tracking of\npromises. There are two promises in the example above; the promise created by\nPromise.resolve() and the promise returned by the call to then(). In the\nexample above, the first promise got the asyncId 6 and the latter got\nasyncId 7. During the execution of the then() callback, we are executing\nin the context of promise with asyncId 7. This promise was triggered by\nasync resource 6.
Another subtlety with promises is that before and after callbacks are run\nonly on chained promises. That means promises not created by then()/catch()\nwill not have the before and after callbacks fired on them. For more details\nsee the details of the V8 PromiseHooks API.
Tracking promise execution can cause a significant performance overhead.\nTo opt out of promise tracking, set trackPromises to false:
const { createHook } = require('node:async_hooks');\nconst { writeSync } = require('node:fs');\ncreateHook({\n init(asyncId, type, triggerAsyncId, resource) {\n // This init hook does not get called when trackPromises is set to false.\n writeSync(1, `init hook triggered for ${type}\\n`);\n },\n trackPromises: false, // Do not track promises.\n}).enable();\nPromise.resolve(1729);\n\nimport { createHook } from 'node:async_hooks';\nimport { writeSync } from 'node:fs';\n\ncreateHook({\n init(asyncId, type, triggerAsyncId, resource) {\n // This init hook does not get called when trackPromises is set to false.\n writeSync(1, `init hook triggered for ${type}\\n`);\n },\n trackPromises: false, // Do not track promises.\n}).enable();\nPromise.resolve(1729);\n",
"displayName": "Disabling promise execution tracking"
}
],
"displayName": "Promise execution tracking"
},
{
"textRaw": "JavaScript embedder API",
"name": "javascript_embedder_api",
"type": "module",
"desc": "Library developers that handle their own asynchronous resources performing tasks\nlike I/O, connection pooling, or managing callback queues may use the\nAsyncResource JavaScript API so that all the appropriate callbacks are called.
The documentation for this class has moved AsyncResource.
Registers functions to be called for different lifetime events of each async\noperation.
\nThe callbacks init()/before()/after()/destroy() are called for the\nrespective asynchronous event during a resource's lifetime.
All callbacks are optional. For example, if only resource cleanup needs to\nbe tracked, then only the destroy callback needs to be passed. The\nspecifics of all functions that can be passed to callbacks is in the\nHook Callbacks section.
import { createHook } from 'node:async_hooks';\n\nconst asyncHook = createHook({\n init(asyncId, type, triggerAsyncId, resource) { },\n destroy(asyncId) { },\n});\n\nconst async_hooks = require('node:async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n init(asyncId, type, triggerAsyncId, resource) { },\n destroy(asyncId) { },\n});\n\nThe callbacks will be inherited via the prototype chain:
\nclass MyAsyncCallbacks {\n init(asyncId, type, triggerAsyncId, resource) { }\n destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n before(asyncId) { }\n after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());\n\nBecause promises are asynchronous resources whose lifecycle is tracked\nvia the async hooks mechanism, the init(), before(), after(), and\ndestroy() callbacks must not be async functions that return promises.
If any AsyncHook callbacks throw, the application will print the stack trace\nand exit. The exit path does follow that of an uncaught exception, but\nall 'uncaughtException' listeners are removed, thus forcing the process to\nexit. The 'exit' callbacks will still be called unless the application is run\nwith --abort-on-uncaught-exception, in which case a stack trace will be\nprinted and the application exits, leaving a core file.
The reason for this error handling behavior is that these callbacks are running\nat potentially volatile points in an object's lifetime, for example during\nclass construction and destruction. Because of this, it is deemed necessary to\nbring down the process quickly in order to prevent an unintentional abort in the\nfuture. This is subject to change in the future if a comprehensive analysis is\nperformed to ensure an exception can follow the normal control flow without\nunintentional side effects.
", "displayName": "Error handling" }, { "textRaw": "Printing in `AsyncHook` callbacks", "name": "printing_in_`asynchook`_callbacks", "type": "module", "desc": "Because printing to the console is an asynchronous operation, console.log()\nwill cause AsyncHook callbacks to be called. Using console.log() or\nsimilar asynchronous operations inside an AsyncHook callback function will\ncause an infinite recursion. An easy solution to this when debugging is to use a\nsynchronous logging operation such as fs.writeFileSync(file, msg, flag).\nThis will print to the file and will not invoke AsyncHook recursively because\nit is synchronous.
import { writeFileSync } from 'node:fs';\nimport { format } from 'node:util';\n\nfunction debug(...args) {\n // Use a function like this one when debugging inside an AsyncHook callback\n writeFileSync('log.out', `${format(...args)}\\n`, { flag: 'a' });\n}\n\nconst fs = require('node:fs');\nconst util = require('node:util');\n\nfunction debug(...args) {\n // Use a function like this one when debugging inside an AsyncHook callback\n fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}\n\nIf an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by AsyncHook itself. The logging should then be skipped when\nit was the logging itself that caused the AsyncHook callback to be called. By\ndoing this, the otherwise infinite recursion is broken.
The class AsyncHook exposes an interface for tracking lifetime events\nof asynchronous operations.
Enable the callbacks for a given AsyncHook instance. If no callbacks are\nprovided, enabling is a no-op.
The AsyncHook instance is disabled by default. If the AsyncHook instance\nshould be enabled immediately after creation, the following pattern can be used.
import { createHook } from 'node:async_hooks';\n\nconst hook = createHook(callbacks).enable();\n\nconst async_hooks = require('node:async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n"
},
{
"textRaw": "`asyncHook.disable()`",
"name": "disable",
"type": "method",
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.",
"name": "return",
"type": "AsyncHook",
"desc": "A reference to `asyncHook`."
}
}
],
"desc": "Disable the callbacks for a given AsyncHook instance from the global pool of\nAsyncHook callbacks to be executed. Once a hook has been disabled it will not\nbe called again until enabled.
For API consistency disable() also returns the AsyncHook instance.
Resource objects returned by executionAsyncResource() are most often internal\nNode.js handle objects with undocumented APIs. Using any functions or properties\non the object is likely to crash your application and should be avoided.
Using executionAsyncResource() in the top-level execution context will\nreturn an empty object as there is no handle or request object to use,\nbut having an object representing the top-level can be helpful.
import { open } from 'node:fs';\nimport { executionAsyncId, executionAsyncResource } from 'node:async_hooks';\n\nconsole.log(executionAsyncId(), executionAsyncResource()); // 1 {}\nopen(new URL(import.meta.url), 'r', (err, fd) => {\n console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap\n});\n\nconst { open } = require('node:fs');\nconst { executionAsyncId, executionAsyncResource } = require('node:async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource()); // 1 {}\nopen(__filename, 'r', (err, fd) => {\n console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap\n});\n\nThis can be used to implement continuation local storage without the\nuse of a tracking Map to store the metadata:
import { createServer } from 'node:http';\nimport {\n executionAsyncId,\n executionAsyncResource,\n createHook,\n} from 'node:async_hooks';\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n init(asyncId, type, triggerAsyncId, resource) {\n const cr = executionAsyncResource();\n if (cr) {\n resource[sym] = cr[sym];\n }\n },\n}).enable();\n\nconst server = createServer((req, res) => {\n executionAsyncResource()[sym] = { state: req.url };\n setTimeout(function() {\n res.end(JSON.stringify(executionAsyncResource()[sym]));\n }, 100);\n}).listen(3000);\n\nconst { createServer } = require('node:http');\nconst {\n executionAsyncId,\n executionAsyncResource,\n createHook,\n} = require('node:async_hooks');\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n init(asyncId, type, triggerAsyncId, resource) {\n const cr = executionAsyncResource();\n if (cr) {\n resource[sym] = cr[sym];\n }\n },\n}).enable();\n\nconst server = createServer((req, res) => {\n executionAsyncResource()[sym] = { state: req.url };\n setTimeout(function() {\n res.end(JSON.stringify(executionAsyncResource()[sym]));\n }, 100);\n}).listen(3000);\n"
},
{
"textRaw": "`async_hooks.executionAsyncId()`",
"name": "executionAsyncId",
"type": "method",
"meta": {
"added": [
"v8.1.0"
],
"changes": [
{
"version": "v8.2.0",
"pr-url": "https://github.com/nodejs/node/pull/13490",
"description": "Renamed from `currentId`."
}
]
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {number} The `asyncId` of the current execution context. Useful to track when something calls.",
"name": "return",
"type": "number",
"desc": "The `asyncId` of the current execution context. Useful to track when something calls."
}
}
],
"desc": "import { executionAsyncId } from 'node:async_hooks';\nimport fs from 'node:fs';\n\nconsole.log(executionAsyncId()); // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n console.log(executionAsyncId()); // 6 - open()\n});\n\nconst async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\n\nconsole.log(async_hooks.executionAsyncId()); // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n console.log(async_hooks.executionAsyncId()); // 6 - open()\n});\n\nThe ID returned from executionAsyncId() is related to execution timing, not\ncausality (which is covered by triggerAsyncId()):
const server = net.createServer((conn) => {\n // Returns the ID of the server, not of the new connection, because the\n // callback runs in the execution scope of the server's MakeCallback().\n async_hooks.executionAsyncId();\n\n}).listen(port, () => {\n // Returns the ID of a TickObject (process.nextTick()) because all\n // callbacks passed to .listen() are wrapped in a nextTick().\n async_hooks.executionAsyncId();\n});\n\nPromise contexts may not get precise executionAsyncIds by default.\nSee the section on promise execution tracking.
const server = net.createServer((conn) => {\n // The resource that caused (or triggered) this callback to be called\n // was that of the new connection. Thus the return value of triggerAsyncId()\n // is the asyncId of \"conn\".\n async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n // the callback itself exists because the call to the server's .listen()\n // was made. So the return value would be the ID of the server.\n async_hooks.triggerAsyncId();\n});\n\nPromise contexts may not get valid triggerAsyncIds by default. See\nthe section on promise execution tracking.
Key events in the lifetime of asynchronous events have been categorized into\nfour areas: instantiation, before/after the callback is called, and when the\ninstance is destroyed.
", "methods": [ { "textRaw": "`init(asyncId, type, triggerAsyncId, resource)`", "name": "init", "type": "method", "signatures": [ { "params": [ { "textRaw": "`asyncId` {number} A unique ID for the async resource.", "name": "asyncId", "type": "number", "desc": "A unique ID for the async resource." }, { "textRaw": "`type` {string} The type of the async resource.", "name": "type", "type": "string", "desc": "The type of the async resource." }, { "textRaw": "`triggerAsyncId` {number} The unique ID of the async resource in whose execution context this async resource was created.", "name": "triggerAsyncId", "type": "number", "desc": "The unique ID of the async resource in whose execution context this async resource was created." }, { "textRaw": "`resource` {Object} Reference to the resource representing the async operation, needs to be released during _destroy_.", "name": "resource", "type": "Object", "desc": "Reference to the resource representing the async operation, needs to be released during _destroy_." } ] } ], "desc": "Called when a class is constructed that has the possibility to emit an\nasynchronous event. This does not mean the instance must call\nbefore/after before destroy is called, only that the possibility\nexists.
This behavior can be observed by doing something like opening a resource then\nclosing it before the resource can be used. The following snippet demonstrates\nthis.
\nimport { createServer } from 'node:net';\n\ncreateServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n\nrequire('node:net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n\nEvery new resource is assigned an ID that is unique within the scope of the\ncurrent Node.js instance.
", "modules": [ { "textRaw": "`type`", "name": "`type`", "type": "module", "desc": "The type is a string identifying the type of resource that caused\ninit to be called. Generally, it will correspond to the name of the\nresource's constructor.
The type of resources created by Node.js itself can change in any Node.js\nrelease. Valid values include TLSWRAP,\nTCPWRAP, TCPSERVERWRAP, GETADDRINFOREQWRAP, FSREQCALLBACK,\nMicrotask, and Timeout. Inspect the source code of the Node.js version used\nto get the full list.
Furthermore users of AsyncResource create async resources independent\nof Node.js itself.
There is also the PROMISE resource type, which is used to track Promise\ninstances and asynchronous work scheduled by them. The Promises are only\ntracked when trackPromises option is set to true.
Users are able to define their own type when using the public embedder API.
It is possible to have type name collisions. Embedders are encouraged to use\nunique prefixes, such as the npm package name, to prevent collisions when\nlistening to the hooks.
", "displayName": "`type`" }, { "textRaw": "`triggerAsyncId`", "name": "`triggerasyncid`", "type": "module", "desc": "triggerAsyncId is the asyncId of the resource that caused (or \"triggered\")\nthe new resource to initialize and that caused init to call. This is different\nfrom async_hooks.executionAsyncId() that only shows when a resource was\ncreated, while triggerAsyncId shows why a resource was created.
The following is a simple demonstration of triggerAsyncId:
import { createHook, executionAsyncId } from 'node:async_hooks';\nimport { stdout } from 'node:process';\nimport net from 'node:net';\nimport fs from 'node:fs';\n\ncreateHook({\n init(asyncId, type, triggerAsyncId) {\n const eid = executionAsyncId();\n fs.writeSync(\n stdout.fd,\n `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);\n\nconst { createHook, executionAsyncId } = require('node:async_hooks');\nconst { stdout } = require('node:process');\nconst net = require('node:net');\nconst fs = require('node:fs');\n\ncreateHook({\n init(asyncId, type, triggerAsyncId) {\n const eid = executionAsyncId();\n fs.writeSync(\n stdout.fd,\n `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);\n\nOutput when hitting the server with nc localhost 8080:
TCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0\n\nThe TCPSERVERWRAP is the server which receives the connections.
The TCPWRAP is the new connection from the client. When a new\nconnection is made, the TCPWrap instance is immediately constructed. This\nhappens outside of any JavaScript stack. (An executionAsyncId() of 0 means\nthat it is being executed from C++ with no JavaScript stack above it.) With only\nthat information, it would be impossible to link resources together in\nterms of what caused them to be created, so triggerAsyncId is given the task\nof propagating what resource is responsible for the new resource's existence.
resource is an object that represents the actual async resource that has\nbeen initialized. The API to access the object may be specified by the\ncreator of the resource. Resources created by Node.js itself are internal\nand may change at any time. Therefore no API is specified for these.
In some cases the resource object is reused for performance reasons, it is\nthus not safe to use it as a key in a WeakMap or add properties to it.
The context tracking use case is covered by the stable API AsyncLocalStorage.\nThis example only illustrates async hooks operation but AsyncLocalStorage\nfits better to this use case.
The following is an example with additional information about the calls to\ninit between the before and after calls, specifically what the\ncallback to listen() will look like. The output formatting is slightly more\nelaborate to make calling context easier to see.
import async_hooks from 'node:async_hooks';\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport { stdout } from 'node:process';\nconst { fd } = stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n init(asyncId, type, triggerAsyncId) {\n const eid = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(indent);\n fs.writeSync(\n fd,\n `${indentStr}${type}(${asyncId}):` +\n ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n },\n before(asyncId) {\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}before: ${asyncId}\\n`);\n indent += 2;\n },\n after(asyncId) {\n indent -= 2;\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}after: ${asyncId}\\n`);\n },\n destroy(asyncId) {\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\\n`);\n },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n // Let's wait 10ms before logging the server started.\n setTimeout(() => {\n console.log('>>>', async_hooks.executionAsyncId());\n }, 10);\n});\n\nconst async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\nconst net = require('node:net');\nconst { fd } = process.stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n init(asyncId, type, triggerAsyncId) {\n const eid = async_hooks.executionAsyncId();\n const indentStr = ' '.repeat(indent);\n fs.writeSync(\n fd,\n `${indentStr}${type}(${asyncId}):` +\n ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n },\n before(asyncId) {\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}before: ${asyncId}\\n`);\n indent += 2;\n },\n after(asyncId) {\n indent -= 2;\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}after: ${asyncId}\\n`);\n },\n destroy(asyncId) {\n const indentStr = ' '.repeat(indent);\n fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\\n`);\n },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n // Let's wait 10ms before logging the server started.\n setTimeout(() => {\n console.log('>>>', async_hooks.executionAsyncId());\n }, 10);\n});\n\nOutput from only starting the server:
\nTCPSERVERWRAP(5): trigger: 1 execution: 1\nTickObject(6): trigger: 5 execution: 1\nbefore: 6\n Timeout(7): trigger: 6 execution: 6\nafter: 6\ndestroy: 6\nbefore: 7\n>>> 7\n TickObject(8): trigger: 7 execution: 7\nafter: 7\nbefore: 8\nafter: 8\n\nAs illustrated in the example, executionAsyncId() and execution each specify\nthe value of the current execution context; which is delineated by calls to\nbefore and after.
Only using execution to graph resource allocation results in the following:
root(1)\n ^\n |\nTickObject(6)\n ^\n |\n Timeout(7)\n\nThe TCPSERVERWRAP is not part of this graph, even though it was the reason for\nconsole.log() being called. This is because binding to a port without a host\nname is a synchronous operation, but to maintain a completely asynchronous\nAPI the user's callback is placed in a process.nextTick(). Which is why\nTickObject is present in the output and is a 'parent' for .listen()\ncallback.
The graph only shows when a resource was created, not why, so to track\nthe why use triggerAsyncId. Which can be represented with the following\ngraph:
bootstrap(1)\n |\n ˅\nTCPSERVERWRAP(5)\n |\n ˅\n TickObject(6)\n |\n ˅\n Timeout(7)\n",
"displayName": "Asynchronous context example"
}
]
},
{
"textRaw": "`before(asyncId)`",
"name": "before",
"type": "method",
"signatures": [
{
"params": [
{
"textRaw": "`asyncId` {number}",
"name": "asyncId",
"type": "number"
}
]
}
],
"desc": "When an asynchronous operation is initiated (such as a TCP server receiving a\nnew connection) or completes (such as writing data to disk) a callback is\ncalled to notify the user. The before callback is called just before said\ncallback is executed. asyncId is the unique identifier assigned to the\nresource about to execute the callback.
The before callback will be called 0 to N times. The before callback\nwill typically be called 0 times if the asynchronous operation was cancelled\nor, for example, if no connections are received by a TCP server. Persistent\nasynchronous resources like a TCP server will typically call the before\ncallback multiple times, while other operations like fs.open() will call\nit only once.
Called immediately after the callback specified in before is completed.
If an uncaught exception occurs during execution of the callback, then after\nwill run after the 'uncaughtException' event is emitted or a domain's\nhandler runs.
Called after the resource corresponding to asyncId is destroyed. It is also\ncalled asynchronously from the embedder API emitDestroy().
Some resources depend on garbage collection for cleanup, so if a reference is\nmade to the resource object passed to init it is possible that destroy\nwill never be called, causing a memory leak in the application. If the resource\ndoes not depend on garbage collection, then this will not be an issue.
Using the destroy hook results in additional overhead because it enables\ntracking of Promise instances via the garbage collector.
Called when the resolve function passed to the Promise constructor is\ninvoked (either directly or through other means of resolving a promise).
resolve() does not do any observable synchronous work.
The Promise is not necessarily fulfilled or rejected at this point if the\nPromise was resolved by assuming the state of another Promise.
new Promise((resolve) => resolve(true)).then((a) => {});\n\ncalls the following callbacks:
\ninit for PROMISE with id 5, trigger id: 1\n promise resolve 5 # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5 # the Promise returned by then()\n before 6 # the then() callback is entered\n promise resolve 6 # the then() callback resolves the promise by returning\n after 6\n"
}
],
"displayName": "Hook callbacks"
}
],
"properties": [
{
"textRaw": "Returns: A map of provider types to the corresponding numeric id. This map contains all the event types that might be emitted by the `async_hooks.init()` event.",
"name": "asyncWrapProviders",
"type": "property",
"meta": {
"added": [
"v17.2.0",
"v16.14.0"
],
"changes": []
},
"desc": "This feature suppresses the deprecated usage of process.binding('async_wrap').Providers.\nSee: DEP0111
The documentation for this class has moved AsyncLocalStorage.
Buffer objects are used to represent a fixed-length sequence of bytes. Many\nNode.js APIs support Buffers.
The Buffer class is a subclass of JavaScript's <Uint8Array> class and\nextends it with methods that cover additional use cases. Node.js APIs accept\nplain <Uint8Array>s wherever Buffers are supported as well.
While the Buffer class is available within the global scope, it is still\nrecommended to explicitly reference it via an import or require statement.
import { Buffer } from 'node:buffer';\n\n// Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10,\n// filled with bytes which all have the value `1`.\nconst buf2 = Buffer.alloc(10, 1);\n\n// Creates an uninitialized buffer of length 10.\n// This is faster than calling Buffer.alloc() but the returned\n// Buffer instance might contain old data that needs to be\n// overwritten using fill(), write(), or other functions that fill the Buffer's\n// contents.\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing the bytes [1, 2, 3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries\n// are all truncated using `(value & 255)` to fit into the range 0–255.\nconst buf5 = Buffer.from([257, 257.5, -255, '1']);\n\n// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':\n// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)\n// [116, 195, 169, 115, 116] (in decimal notation)\nconst buf6 = Buffer.from('tést');\n\n// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].\nconst buf7 = Buffer.from('tést', 'latin1');\n\nconst { Buffer } = require('node:buffer');\n\n// Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10,\n// filled with bytes which all have the value `1`.\nconst buf2 = Buffer.alloc(10, 1);\n\n// Creates an uninitialized buffer of length 10.\n// This is faster than calling Buffer.alloc() but the returned\n// Buffer instance might contain old data that needs to be\n// overwritten using fill(), write(), or other functions that fill the Buffer's\n// contents.\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing the bytes [1, 2, 3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries\n// are all truncated using `(value & 255)` to fit into the range 0–255.\nconst buf5 = Buffer.from([257, 257.5, -255, '1']);\n\n// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':\n// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)\n// [116, 195, 169, 115, 116] (in decimal notation)\nconst buf6 = Buffer.from('tést');\n\n// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].\nconst buf7 = Buffer.from('tést', 'latin1');\n",
"modules": [
{
"textRaw": "Buffers and character encodings",
"name": "buffers_and_character_encodings",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v15.7.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36952",
"description": "Introduced `base64url` encoding."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7111",
"description": "Introduced `latin1` as an alias for `binary`."
},
{
"version": "v5.0.0",
"pr-url": "https://github.com/nodejs/node/pull/2859",
"description": "Removed the deprecated `raw` and `raws` encodings."
}
]
},
"desc": "When converting between Buffers and strings, a character encoding may be\nspecified. If no character encoding is specified, UTF-8 will be used as the\ndefault.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('hello world', 'utf8');\n\nconsole.log(buf.toString('hex'));\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('base64'));\n// Prints: aGVsbG8gd29ybGQ=\n\nconsole.log(Buffer.from('fhqwhgads', 'utf8'));\n// Prints: <Buffer 66 68 71 77 68 67 61 64 73>\nconsole.log(Buffer.from('fhqwhgads', 'utf16le'));\n// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('hello world', 'utf8');\n\nconsole.log(buf.toString('hex'));\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('base64'));\n// Prints: aGVsbG8gd29ybGQ=\n\nconsole.log(Buffer.from('fhqwhgads', 'utf8'));\n// Prints: <Buffer 66 68 71 77 68 67 61 64 73>\nconsole.log(Buffer.from('fhqwhgads', 'utf16le'));\n// Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00>\n\nNode.js buffers accept all case variations of encoding strings that they\nreceive. For example, UTF-8 can be specified as 'utf8', 'UTF8', or 'uTf8'.
The character encodings currently supported by Node.js are the following:
\n'utf8' (alias: 'utf-8'): Multi-byte encoded Unicode characters. Many web\npages and other document formats use UTF-8. This is the default character\nencoding. When decoding a Buffer into a string that does not exclusively\ncontain valid UTF-8 data, the Unicode replacement character U+FFFD � will be\nused to represent those errors.
'utf16le' (alias: 'utf-16le'): Multi-byte encoded Unicode characters.\nUnlike 'utf8', each character in the string will be encoded using either 2\nor 4 bytes. Node.js only supports the little-endian variant of\nUTF-16.
'latin1': Latin-1 stands for ISO-8859-1. This character encoding only\nsupports the Unicode characters from U+0000 to U+00FF. Each character is\nencoded using a single byte. Characters that do not fit into that range are\ntruncated and will be mapped to characters in that range.
Converting a Buffer into a string using one of the above is referred to as\ndecoding, and converting a string into a Buffer is referred to as encoding.
Node.js also supports the following binary-to-text encodings. For\nbinary-to-text encodings, the naming convention is reversed: Converting a\nBuffer into a string is typically referred to as encoding, and converting a\nstring into a Buffer as decoding.
'base64': Base64 encoding. When creating a Buffer from a string,\nthis encoding will also correctly accept \"URL and Filename Safe Alphabet\" as\nspecified in RFC 4648, Section 5. Whitespace characters such as spaces,\ntabs, and new lines contained within the base64-encoded string are ignored.
'base64url': base64url encoding as specified in\nRFC 4648, Section 5. When creating a Buffer from a string, this\nencoding will also correctly accept regular base64-encoded strings. When\nencoding a Buffer to a string, this encoding will omit padding.
'hex': Encode each byte as two hexadecimal characters. Data truncation\nmay occur when decoding strings that do not exclusively consist of an even\nnumber of hexadecimal characters. See below for an example.
The following legacy character encodings are also supported:
\n'ascii': For 7-bit ASCII data only. When encoding a string into a\nBuffer, this is equivalent to using 'latin1'. When decoding a Buffer\ninto a string, using this encoding will additionally unset the highest bit of\neach byte before decoding as 'latin1'.\nGenerally, there should be no reason to use this encoding, as 'utf8'\n(or, if the data is known to always be ASCII-only, 'latin1') will be a\nbetter choice when encoding or decoding ASCII-only text. It is only provided\nfor legacy compatibility.
'binary': Alias for 'latin1'.\nThe name of this encoding can be very misleading, as all of the\nencodings listed here convert between strings and binary data. For converting\nbetween strings and Buffers, typically 'utf8' is the right choice.
'ucs2', 'ucs-2': Aliases of 'utf16le'. UCS-2 used to refer to a variant\nof UTF-16 that did not support characters that had code points larger than\nU+FFFF. In Node.js, these code points are always supported.
import { Buffer } from 'node:buffer';\n\nBuffer.from('1ag123', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7', 'hex');\n// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').\n\nBuffer.from('1634', 'hex');\n// Prints <Buffer 16 34>, all data represented.\n\nconst { Buffer } = require('node:buffer');\n\nBuffer.from('1ag123', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7', 'hex');\n// Prints <Buffer 1a>, data truncated when data ends in single digit ('7').\n\nBuffer.from('1634', 'hex');\n// Prints <Buffer 16 34>, all data represented.\n\nModern Web browsers follow the WHATWG Encoding Standard which aliases\nboth 'latin1' and 'ISO-8859-1' to 'win-1252'. This means that while doing\nsomething like http.get(), if the returned charset is one of those listed in\nthe WHATWG specification it is possible that the server actually returned\n'win-1252'-encoded data, and using 'latin1' encoding may incorrectly decode\nthe characters.
Buffer instances are also JavaScript <Uint8Array> and <TypedArray>\ninstances. All <TypedArray> methods and properties are available on Buffers. There are,\nhowever, subtle incompatibilities between the Buffer API and the\n<TypedArray> API.
In particular:
\nTypedArray.prototype.slice() creates a copy of part of the TypedArray,\nBuffer.prototype.slice() creates a view over the existing Buffer\nwithout copying. This behavior can be surprising, and only exists for legacy\ncompatibility. TypedArray.prototype.subarray() can be used to achieve\nthe behavior of Buffer.prototype.slice() on both Buffers\nand other TypedArrays and should be preferred.buf.toString() is incompatible with its TypedArray equivalent.buf.indexOf(), support additional arguments.There are two ways to create new <TypedArray> instances from a Buffer:
Buffer to a <TypedArray> constructor will copy the Buffer's\ncontents, interpreted as an array of integers, and not as a byte sequence\nof the target type.import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4]);\nconst uint32array = new Uint32Array(buf);\n\nconsole.log(uint32array);\n\n// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3, 4]);\nconst uint32array = new Uint32Array(buf);\n\nconsole.log(uint32array);\n\n// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]\n\nBuffer's underlying <ArrayBuffer> will create a\n<TypedArray> that shares its memory with the Buffer.import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('hello', 'utf16le');\nconst uint16array = new Uint16Array(\n buf.buffer,\n buf.byteOffset,\n buf.length / Uint16Array.BYTES_PER_ELEMENT);\n\nconsole.log(uint16array);\n\n// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('hello', 'utf16le');\nconst uint16array = new Uint16Array(\n buf.buffer,\n buf.byteOffset,\n buf.length / Uint16Array.BYTES_PER_ELEMENT);\n\nconsole.log(uint16array);\n\n// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]\n\nIt is possible to create a new Buffer that shares the same allocated\nmemory as a <TypedArray> instance by using the TypedArray object's\n.buffer property in the same way. Buffer.from()\nbehaves like new Uint8Array() in this context.
import { Buffer } from 'node:buffer';\n\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Copies the contents of `arr`.\nconst buf1 = Buffer.from(arr);\n\n// Shares memory with `arr`.\nconst buf2 = Buffer.from(arr.buffer);\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 a0 0f>\n\narr[1] = 6000;\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 70 17>\n\nconst { Buffer } = require('node:buffer');\n\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Copies the contents of `arr`.\nconst buf1 = Buffer.from(arr);\n\n// Shares memory with `arr`.\nconst buf2 = Buffer.from(arr.buffer);\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 a0 0f>\n\narr[1] = 6000;\n\nconsole.log(buf1);\n// Prints: <Buffer 88 a0>\nconsole.log(buf2);\n// Prints: <Buffer 88 13 70 17>\n\nWhen creating a Buffer using a <TypedArray>'s .buffer, it is\npossible to use only a portion of the underlying <ArrayBuffer> by passing in byteOffset and length parameters.
import { Buffer } from 'node:buffer';\n\nconst arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n\nconst { Buffer } = require('node:buffer');\n\nconst arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n\nThe Buffer.from() and TypedArray.from() have different signatures and\nimplementations. Specifically, the <TypedArray> variants accept a second\nargument that is a mapping function that is invoked on every element of the\ntyped array:
The Buffer.from() method, however, does not support the use of a mapping\nfunction:
Buffer.from(array)Buffer.from(buffer)Buffer.from(arrayBuffer[, byteOffset[, length]])Buffer.from(string[, encoding])All methods on the Buffer prototype are callable with a Uint8Array instance.
const { toString, write } = Buffer.prototype;\n\nconst uint8array = new Uint8Array(5);\n\nwrite.call(uint8array, 'hello', 0, 5, 'utf8'); // 5\n// <Uint8Array 68 65 6c 6c 6f>\n\ntoString.call(uint8array, 'utf8'); // 'hello'\n",
"displayName": "Buffer methods are callable with `Uint8Array` instances"
}
],
"displayName": "Buffers and TypedArrays"
},
{
"textRaw": "Buffers and iteration",
"name": "buffers_and_iteration",
"type": "module",
"desc": "Buffer instances can be iterated over using for..of syntax:
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3]);\n\nfor (const b of buf) {\n console.log(b);\n}\n// Prints:\n// 1\n// 2\n// 3\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3]);\n\nfor (const b of buf) {\n console.log(b);\n}\n// Prints:\n// 1\n// 2\n// 3\n\nAdditionally, the buf.values(), buf.keys(), and\nbuf.entries() methods can be used to create iterators.
While, the Buffer object is available as a global, there are additional\nBuffer-related APIs that are available only via the node:buffer module\naccessed using require('node:buffer').
Decodes a string of Base64-encoded data into bytes, and encodes those bytes\ninto a string using Latin-1 (ISO-8859-1).
\nThe 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\nand should never be used in new code, because they use strings to represent\nbinary data and predate the introduction of typed arrays in JavaScript.\nFor code running using Node.js APIs, converting between base64-encoded strings\nand binary data should be performed using Buffer.from(str, 'base64') and\nbuf.toString('base64').
An automated migration is available (source:
\nnpx codemod@latest @nodejs/buffer-atob-btoa\n"
},
{
"textRaw": "`buffer.btoa(data)`",
"name": "btoa",
"type": "method",
"meta": {
"added": [
"v15.13.0",
"v14.17.0"
],
"changes": []
},
"stability": 3,
"stabilityText": "Legacy. Use `buf.toString('base64')` instead.",
"signatures": [
{
"params": [
{
"textRaw": "`data` {any} An ASCII (Latin1) string.",
"name": "data",
"type": "any",
"desc": "An ASCII (Latin1) string."
}
]
}
],
"desc": "Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes\ninto a string using Base64.
\nThe 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\nand should never be used in new code, because they use strings to represent\nbinary data and predate the introduction of typed arrays in JavaScript.\nFor code running using Node.js APIs, converting between base64-encoded strings\nand binary data should be performed using Buffer.from(str, 'base64') and\nbuf.toString('base64').
An automated migration is available (source:
\nnpx codemod@latest @nodejs/buffer-atob-btoa\n"
},
{
"textRaw": "`buffer.isAscii(input)`",
"name": "isAscii",
"type": "method",
"meta": {
"added": [
"v19.6.0",
"v18.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`input` {Buffer|ArrayBuffer|TypedArray} The input to validate.",
"name": "input",
"type": "Buffer|ArrayBuffer|TypedArray",
"desc": "The input to validate."
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "This function returns true if input contains only valid ASCII-encoded data,\nincluding the case in which input is empty.
Throws if the input is a detached array buffer.
This function returns true if input contains only valid UTF-8-encoded data,\nincluding the case in which input is empty.
Throws if the input is a detached array buffer.
Resolves a 'blob:nodedata:...' an associated <Blob> object registered using\na prior call to URL.createObjectURL().
Re-encodes the given Buffer or Uint8Array instance from one character\nencoding to another. Returns a new Buffer instance.
Throws if the fromEnc or toEnc specify invalid character encodings or if\nconversion from fromEnc to toEnc is not permitted.
Encodings supported by buffer.transcode() are: 'ascii', 'utf8',\n'utf16le', 'ucs2', 'latin1', and 'binary'.
The transcoding process will use substitution characters if a given byte\nsequence cannot be adequately represented in the target encoding. For instance:
\nimport { Buffer, transcode } from 'node:buffer';\n\nconst newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n\nconst { Buffer, transcode } = require('node:buffer');\n\nconst newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n\nBecause the Euro (€) sign is not representable in US-ASCII, it is replaced\nwith ? in the transcoded Buffer.
Returns the maximum number of bytes that will be returned when\nbuf.inspect() is called. This can be overridden by user modules. See\nutil.inspect() for more details on buf.inspect() behavior.
An alias for buffer.constants.MAX_LENGTH.
An alias for buffer.constants.MAX_STRING_LENGTH.
On 32-bit architectures, this value is equal to 231 - 1 (about 2\nGiB).
\nOn 64-bit architectures, this value is equal to Number.MAX_SAFE_INTEGER\n(253 - 1, about 8 PiB).
It reflects v8::Uint8Array::kMaxLength under the hood.
This value is also available as buffer.kMaxLength.
Represents the largest length that a string primitive can have, counted\nin UTF-16 code units.
This value may depend on the JS engine that is being used.
", "shortDesc": "The largest length allowed for a single `string` instance." } ], "displayName": "Buffer constants" } ], "displayName": "`node:buffer` module APIs" }, { "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", "type": "module", "desc": "In versions of Node.js prior to 6.0.0, Buffer instances were created using the\nBuffer constructor function, which allocates the returned Buffer\ndifferently based on what arguments are provided:
Buffer() (e.g. new Buffer(10))\nallocates a new Buffer object of the specified size. Prior to Node.js 8.0.0,\nthe memory allocated for such Buffer instances is not initialized and\ncan contain sensitive data. Such Buffer instances must be subsequently\ninitialized by using either buf.fill(0) or by writing to the\nentire Buffer before reading data from the Buffer.\nWhile this behavior is intentional to improve performance,\ndevelopment experience has demonstrated that a more explicit distinction is\nrequired between creating a fast-but-uninitialized Buffer versus creating a\nslower-but-safer Buffer. Since Node.js 8.0.0, Buffer(num) and new Buffer(num) return a Buffer with initialized memory.Buffer as the first argument copies the\npassed object's data into the Buffer.<ArrayBuffer> or a <SharedArrayBuffer> returns a Buffer\nthat shares allocated memory with the given array buffer.Because the behavior of new Buffer() is different depending on the type of the\nfirst argument, security and reliability issues can be inadvertently introduced\ninto applications when argument validation or Buffer initialization is not\nperformed.
For example, if an attacker can cause an application to receive a number where\na string is expected, the application may call new Buffer(100)\ninstead of new Buffer(\"100\"), leading it to allocate a 100 byte buffer instead\nof allocating a 3 byte buffer with content \"100\". This is commonly possible\nusing JSON API calls. Since JSON distinguishes between numeric and string types,\nit allows injection of numbers where a naively written application that does not\nvalidate its input sufficiently might expect to always receive a string.\nBefore Node.js 8.0.0, the 100 byte buffer might contain\narbitrary pre-existing in-memory data, so may be used to expose in-memory\nsecrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot\noccur because the data is zero-filled. However, other attacks are still\npossible, such as causing very large buffers to be allocated by the server,\nleading to performance degradation or crashing on memory exhaustion.
To make the creation of Buffer instances more reliable and less error-prone,\nthe various forms of the new Buffer() constructor have been deprecated\nand replaced by separate Buffer.from(), Buffer.alloc(), and\nBuffer.allocUnsafe() methods.
Developers should migrate all existing uses of the new Buffer() constructors\nto one of these new APIs.
Buffer.from(array) returns a new Buffer that contains a copy of the\nprovided octets.Buffer.from(arrayBuffer[, byteOffset[, length]])\nreturns a new Buffer that shares the same allocated memory as the given\n<ArrayBuffer>.Buffer.from(buffer) returns a new Buffer that contains a copy of the\ncontents of the given Buffer.Buffer.from(string[, encoding]) returns a new\nBuffer that contains a copy of the provided string.Buffer.alloc(size[, fill[, encoding]]) returns a new\ninitialized Buffer of the specified size. This method is slower than\nBuffer.allocUnsafe(size) but guarantees that newly\ncreated Buffer instances never contain old data that is potentially\nsensitive. A TypeError will be thrown if size is not a number.Buffer.allocUnsafe(size) and\nBuffer.allocUnsafeSlow(size) each return a\nnew uninitialized Buffer of the specified size. Because the Buffer is\nuninitialized, the allocated segment of memory might contain old data that is\npotentially sensitive.Buffer instances returned by Buffer.allocUnsafe(), Buffer.from(string),\nBuffer.concat() and Buffer.from(array) may be allocated off a shared\ninternal memory pool if size is less than or equal to half Buffer.poolSize.\nInstances returned by Buffer.allocUnsafeSlow() never use the shared internal\nmemory pool.
Node.js can be started using the --zero-fill-buffers command-line option to\ncause all newly-allocated Buffer instances to be zero-filled upon creation by\ndefault. Without the option, buffers created with Buffer.allocUnsafe() and\nBuffer.allocUnsafeSlow() are not zero-filled. Use of this flag can have a\nmeasurable negative impact on performance. Use the --zero-fill-buffers option\nonly when necessary to enforce that newly allocated Buffer instances cannot\ncontain old data that is potentially sensitive.
$ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n",
"displayName": "The `--zero-fill-buffers` command-line option"
},
{
"textRaw": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?",
"name": "what_makes_`buffer.allocunsafe()`_and_`buffer.allocunsafeslow()`_\"unsafe\"?",
"type": "module",
"desc": "When calling Buffer.allocUnsafe() and Buffer.allocUnsafeSlow(), the\nsegment of allocated memory is uninitialized (it is not zeroed-out). While\nthis design makes the allocation of memory quite fast, the allocated segment of\nmemory might contain old data that is potentially sensitive. Using a Buffer\ncreated by Buffer.allocUnsafe() without completely overwriting the\nmemory can allow this old data to be leaked when the Buffer memory is read.
While there are clear performance advantages to using\nBuffer.allocUnsafe(), extra care must be taken in order to avoid\nintroducing security vulnerabilities into an application.
A <Blob> encapsulates immutable, raw data that can be safely shared across\nmultiple worker threads.
Creates a new Blob object containing a concatenation of the given sources.
<ArrayBuffer>, <TypedArray>, <DataView>, and <Buffer> sources are copied into\nthe 'Blob' and can therefore be safely modified after the 'Blob' is created.
String sources are encoded as UTF-8 byte sequences and copied into the Blob.\nUnmatched surrogate pairs within each string part will be replaced by Unicode\nU+FFFD replacement characters.
" } ], "methods": [ { "textRaw": "`blob.arrayBuffer()`", "name": "arrayBuffer", "type": "method", "meta": { "added": [ "v15.7.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" } } ], "desc": "Returns a promise that fulfills with an <ArrayBuffer> containing a copy of\nthe Blob data.
The blob.bytes() method returns the byte of the Blob object as a Promise<Uint8Array>.
const blob = new Blob(['hello']);\nblob.bytes().then((bytes) => {\n console.log(bytes); // Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]\n});\n"
},
{
"textRaw": "`blob.slice([start[, end[, type]]])`",
"name": "slice",
"type": "method",
"meta": {
"added": [
"v15.7.0",
"v14.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`start` {number} The starting index.",
"name": "start",
"type": "number",
"desc": "The starting index.",
"optional": true
},
{
"textRaw": "`end` {number} The ending index.",
"name": "end",
"type": "number",
"desc": "The ending index.",
"optional": true
},
{
"textRaw": "`type` {string} The content-type for the new `Blob`",
"name": "type",
"type": "string",
"desc": "The content-type for the new `Blob`",
"optional": true
}
]
}
],
"desc": "Creates and returns a new Blob containing a subset of this Blob objects\ndata. The original Blob is not altered.
Returns a new ReadableStream that allows the content of the Blob to be read.
Returns a promise that fulfills with the contents of the Blob decoded as a\nUTF-8 string.
The total size of the Blob in bytes.
The content-type of the Blob.
Once a <Blob> object is created, it can be sent via MessagePort to multiple\ndestinations without transferring or immediately copying the data. The data\ncontained by the Blob is copied only when the arrayBuffer() or text()\nmethods are called.
import { Blob } from 'node:buffer';\nimport { setTimeout as delay } from 'node:timers/promises';\n\nconst blob = new Blob(['hello there']);\n\nconst mc1 = new MessageChannel();\nconst mc2 = new MessageChannel();\n\nmc1.port1.onmessage = async ({ data }) => {\n console.log(await data.arrayBuffer());\n mc1.port1.close();\n};\n\nmc2.port1.onmessage = async ({ data }) => {\n await delay(1000);\n console.log(await data.arrayBuffer());\n mc2.port1.close();\n};\n\nmc1.port2.postMessage(blob);\nmc2.port2.postMessage(blob);\n\n// The Blob is still usable after posting.\nblob.text().then(console.log);\n\nconst { Blob } = require('node:buffer');\nconst { setTimeout: delay } = require('node:timers/promises');\n\nconst blob = new Blob(['hello there']);\n\nconst mc1 = new MessageChannel();\nconst mc2 = new MessageChannel();\n\nmc1.port1.onmessage = async ({ data }) => {\n console.log(await data.arrayBuffer());\n mc1.port1.close();\n};\n\nmc2.port1.onmessage = async ({ data }) => {\n await delay(1000);\n console.log(await data.arrayBuffer());\n mc2.port1.close();\n};\n\nmc1.port2.postMessage(blob);\nmc2.port2.postMessage(blob);\n\n// The Blob is still usable after posting.\nblob.text().then(console.log);\n",
"displayName": "`Blob` objects and `MessageChannel`"
}
]
},
{
"textRaw": "Class: `Buffer`",
"name": "Buffer",
"type": "class",
"desc": "The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.
Allocates a new Buffer of size bytes. If fill is undefined, the\nBuffer will be zero-filled.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n\nIf size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE\nis thrown.
If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill).
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n\nIf both fill and encoding are specified, the allocated Buffer will be\ninitialized by calling buf.fill(fill, encoding).
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\nconsole.log(buf);\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\nconsole.log(buf);\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\n\nCalling Buffer.alloc() can be measurably slower than the alternative\nBuffer.allocUnsafe() but ensures that the newly created Buffer instance\ncontents will never contain sensitive data from previous allocations, including\ndata that might not have been allocated for Buffers.
A TypeError will be thrown if size is not a number.
Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE\nis thrown.
The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use Buffer.alloc() instead to initialize\nBuffer instances with zeroes.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(10);\n\nconsole.log(buf);\n// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\n\nbuf.fill(0);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(10);\n\nconsole.log(buf);\n// Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\n\nbuf.fill(0);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\n\nA TypeError will be thrown if size is not a number.
The Buffer module pre-allocates an internal Buffer instance of\nsize Buffer.poolSize that is used as a pool for the fast allocation of new\nBuffer instances created using Buffer.allocUnsafe(), Buffer.from(array),\nBuffer.from(string), and Buffer.concat() only when size is less than\nBuffer.poolSize >>> 1 (floor of Buffer.poolSize divided by two).
Use of this pre-allocated internal memory pool is a key difference between\ncalling Buffer.alloc(size, fill) vs. Buffer.allocUnsafe(size).fill(fill).\nSpecifically, Buffer.alloc(size, fill) will never use the internal Buffer\npool, while Buffer.allocUnsafe(size).fill(fill) will use the internal\nBuffer pool if size is less than or equal to half Buffer.poolSize. The\ndifference is subtle but can be important when an application requires the\nadditional performance that Buffer.allocUnsafe() provides.
Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_OUT_OF_RANGE\nis thrown. A zero-length Buffer is created if size is 0.
The underlying memory for Buffer instances created in this way is not\ninitialized. The contents of the newly created Buffer are unknown and\nmay contain sensitive data. Use buf.fill(0) to initialize\nsuch Buffer instances with zeroes.
When using Buffer.allocUnsafe() to allocate new Buffer instances,\nallocations less than Buffer.poolSize >>> 1 (4KiB when default poolSize is used) are sliced\nfrom a single pre-allocated Buffer. This allows applications to avoid the\ngarbage collection overhead of creating many individually allocated Buffer\ninstances. This approach improves both performance and memory usage by\neliminating the need to track and clean up as many individual ArrayBuffer objects.
However, in the case where a developer may need to retain a small chunk of\nmemory from a pool for an indeterminate amount of time, it may be appropriate\nto create an un-pooled Buffer instance using Buffer.allocUnsafeSlow() and\nthen copying out the relevant bits.
import { Buffer } from 'node:buffer';\n\n// Need to keep around a few small chunks of memory.\nconst store = [];\n\nsocket.on('readable', () => {\n let data;\n while (null !== (data = readable.read())) {\n // Allocate for retained data.\n const sb = Buffer.allocUnsafeSlow(10);\n\n // Copy the data into the new allocation.\n data.copy(sb, 0, 0, 10);\n\n store.push(sb);\n }\n});\n\nconst { Buffer } = require('node:buffer');\n\n// Need to keep around a few small chunks of memory.\nconst store = [];\n\nsocket.on('readable', () => {\n let data;\n while (null !== (data = readable.read())) {\n // Allocate for retained data.\n const sb = Buffer.allocUnsafeSlow(10);\n\n // Copy the data into the new allocation.\n data.copy(sb, 0, 0, 10);\n\n store.push(sb);\n }\n});\n\nA TypeError will be thrown if size is not a number.
Returns the byte length of a string when encoded using encoding.\nThis is not the same as String.prototype.length, which does not account\nfor the encoding that is used to convert the string into bytes.
For 'base64', 'base64url', and 'hex', this function assumes valid input.\nFor strings that contain non-base64/hex-encoded data (e.g. whitespace), the\nreturn value might be greater than the length of a Buffer created from the\nstring.
import { Buffer } from 'node:buffer';\n\nconst str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(`${str}: ${str.length} characters, ` +\n `${Buffer.byteLength(str, 'utf8')} bytes`);\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\n\nconst { Buffer } = require('node:buffer');\n\nconst str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(`${str}: ${str.length} characters, ` +\n `${Buffer.byteLength(str, 'utf8')} bytes`);\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\n\nWhen string is a <Buffer> | <DataView> | <TypedArray> | <ArrayBuffer> | <SharedArrayBuffer>,\nthe byte length as reported by .byteLength is returned.
Compares buf1 to buf2, typically for the purpose of sorting arrays of\nBuffer instances. This is equivalent to calling\nbuf1.compare(buf2).
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\nconsole.log(arr.sort(Buffer.compare));\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1].)\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\nconsole.log(arr.sort(Buffer.compare));\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1].)\n"
},
{
"textRaw": "Static method: `Buffer.concat(list[, totalLength])`",
"name": "concat",
"type": "classMethod",
"meta": {
"added": [
"v0.7.11"
],
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10236",
"description": "The elements of `list` can now be `Uint8Array`s."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`list` {Buffer[]|Uint8Array[]} List of `Buffer` or {Uint8Array} instances to concatenate.",
"name": "list",
"type": "Buffer[]|Uint8Array[]",
"desc": "List of `Buffer` or {Uint8Array} instances to concatenate."
},
{
"textRaw": "`totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated.",
"name": "totalLength",
"type": "integer",
"desc": "Total length of the `Buffer` instances in `list` when concatenated.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Returns a new Buffer which is the result of concatenating all the Buffer\ninstances in the list together.
If the list has no items, or if the totalLength is 0, then a new zero-length\nBuffer is returned.
If totalLength is not provided, it is calculated from the Buffer instances\nin list by adding their lengths.
If totalLength is provided, it must be an unsigned integer. If the\ncombined length of the Buffers in list exceeds totalLength, the result is\ntruncated to totalLength. If the combined length of the Buffers in list is\nless than totalLength, the remaining space is filled with zeros.
import { Buffer } from 'node:buffer';\n\n// Create a single `Buffer` from a list of three `Buffer` instances.\n\nconst buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\nconsole.log(totalLength);\n// Prints: 42\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\nconsole.log(bufA);\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA.length);\n// Prints: 42\n\nconst { Buffer } = require('node:buffer');\n\n// Create a single `Buffer` from a list of three `Buffer` instances.\n\nconst buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\nconsole.log(totalLength);\n// Prints: 42\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\nconsole.log(bufA);\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA.length);\n// Prints: 42\n\nBuffer.concat() may also use the internal Buffer pool like\nBuffer.allocUnsafe() does.
Copies the underlying memory of view into a new Buffer.
const u16 = new Uint16Array([0, 0xffff]);\nconst buf = Buffer.copyBytesFrom(u16, 1, 1);\nu16[1] = 0;\nconsole.log(buf.length); // 2\nconsole.log(buf[0]); // 255\nconsole.log(buf[1]); // 255\n"
},
{
"textRaw": "Static method: `Buffer.from(array)`",
"name": "from",
"type": "classMethod",
"meta": {
"added": [
"v5.10.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`array` {integer[]}",
"name": "array",
"type": "integer[]"
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Allocates a new Buffer using an array of bytes in the range 0 – 255.\nArray entries outside that range will be truncated to fit into it.
import { Buffer } from 'node:buffer';\n\n// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.\nconst buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n\nconst { Buffer } = require('node:buffer');\n\n// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.\nconst buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n\nIf array is an Array-like object (that is, one with a length property of\ntype number), it is treated as if it is an array, unless it is a Buffer or\na Uint8Array. This means all other TypedArray variants get treated as an\nArray. To create a Buffer from the bytes backing a TypedArray, use\nBuffer.copyBytesFrom().
A TypeError will be thrown if array is not an Array or another type\nappropriate for Buffer.from() variants.
Buffer.from(array) and Buffer.from(string) may also use the internal\nBuffer pool like Buffer.allocUnsafe() does.
This creates a view of the <ArrayBuffer> without copying the underlying\nmemory. For example, when passed a reference to the .buffer property of a\n<TypedArray> instance, the newly created Buffer will share the same\nallocated memory as the <TypedArray>'s underlying ArrayBuffer.
import { Buffer } from 'node:buffer';\n\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`.\nconst buf = Buffer.from(arr.buffer);\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 a0 0f>\n\n// Changing the original Uint16Array changes the Buffer also.\narr[1] = 6000;\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 70 17>\n\nconst { Buffer } = require('node:buffer');\n\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`.\nconst buf = Buffer.from(arr.buffer);\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 a0 0f>\n\n// Changing the original Uint16Array changes the Buffer also.\narr[1] = 6000;\n\nconsole.log(buf);\n// Prints: <Buffer 88 13 70 17>\n\nThe optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.
import { Buffer } from 'node:buffer';\n\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n\nconst { Buffer } = require('node:buffer');\n\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n\nA TypeError will be thrown if arrayBuffer is not an <ArrayBuffer> or a\n<SharedArrayBuffer> or another type appropriate for Buffer.from()\nvariants.
It is important to remember that a backing ArrayBuffer can cover a range\nof memory that extends beyond the bounds of a TypedArray view. A new\nBuffer created using the buffer property of a TypedArray may extend\nbeyond the range of the TypedArray:
import { Buffer } from 'node:buffer';\n\nconst arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements\nconst arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements\nconsole.log(arrA.buffer === arrB.buffer); // true\n\nconst buf = Buffer.from(arrB.buffer);\nconsole.log(buf);\n// Prints: <Buffer 63 64 65 66>\n\nconst { Buffer } = require('node:buffer');\n\nconst arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements\nconst arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements\nconsole.log(arrA.buffer === arrB.buffer); // true\n\nconst buf = Buffer.from(arrB.buffer);\nconsole.log(buf);\n// Prints: <Buffer 63 64 65 66>\n"
},
{
"textRaw": "Static method: `Buffer.from(buffer)`",
"name": "from",
"type": "classMethod",
"meta": {
"added": [
"v5.10.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`buffer` {Buffer|Uint8Array} An existing `Buffer` or {Uint8Array} from which to copy data.",
"name": "buffer",
"type": "Buffer|Uint8Array",
"desc": "An existing `Buffer` or {Uint8Array} from which to copy data."
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Copies the passed buffer data onto a new Buffer instance.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\nconsole.log(buf1.toString());\n// Prints: auffer\nconsole.log(buf2.toString());\n// Prints: buffer\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\nconsole.log(buf1.toString());\n// Prints: auffer\nconsole.log(buf2.toString());\n// Prints: buffer\n\nA TypeError will be thrown if buffer is not a Buffer or another type\nappropriate for Buffer.from() variants.
For objects whose valueOf() function returns a value not strictly equal to\nobject, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from(new String('this is a test'));\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from(new String('this is a test'));\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n\nFor objects that support Symbol.toPrimitive, returns\nBuffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).
import { Buffer } from 'node:buffer';\n\nclass Foo {\n [Symbol.toPrimitive]() {\n return 'this is a test';\n }\n}\n\nconst buf = Buffer.from(new Foo(), 'utf8');\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n\nconst { Buffer } = require('node:buffer');\n\nclass Foo {\n [Symbol.toPrimitive]() {\n return 'this is a test';\n }\n}\n\nconst buf = Buffer.from(new Foo(), 'utf8');\n// Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>\n\nA TypeError will be thrown if object does not have the mentioned methods or\nis not of another type appropriate for Buffer.from() variants.
Creates a new Buffer containing string. The encoding parameter identifies\nthe character encoding to be used when converting string into bytes.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from('this is a tést');\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\nconsole.log(buf1.toString());\n// Prints: this is a tést\nconsole.log(buf2.toString());\n// Prints: this is a tést\nconsole.log(buf1.toString('latin1'));\n// Prints: this is a tést\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from('this is a tést');\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\nconsole.log(buf1.toString());\n// Prints: this is a tést\nconsole.log(buf2.toString());\n// Prints: this is a tést\nconsole.log(buf1.toString('latin1'));\n// Prints: this is a tést\n\nA TypeError will be thrown if string is not a string or another type\nappropriate for Buffer.from() variants.
Buffer.from(string) may also use the internal Buffer pool like\nBuffer.allocUnsafe() does.
Returns true if obj is a Buffer, false otherwise.
import { Buffer } from 'node:buffer';\n\nBuffer.isBuffer(Buffer.alloc(10)); // true\nBuffer.isBuffer(Buffer.from('foo')); // true\nBuffer.isBuffer('a string'); // false\nBuffer.isBuffer([]); // false\nBuffer.isBuffer(new Uint8Array(1024)); // false\n\nconst { Buffer } = require('node:buffer');\n\nBuffer.isBuffer(Buffer.alloc(10)); // true\nBuffer.isBuffer(Buffer.from('foo')); // true\nBuffer.isBuffer('a string'); // false\nBuffer.isBuffer([]); // false\nBuffer.isBuffer(new Uint8Array(1024)); // false\n"
},
{
"textRaw": "Static method: `Buffer.isEncoding(encoding)`",
"name": "isEncoding",
"type": "classMethod",
"meta": {
"added": [
"v0.9.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`encoding` {string} A character encoding name to check.",
"name": "encoding",
"type": "string",
"desc": "A character encoding name to check."
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if encoding is the name of a supported character encoding,\nor false otherwise.
import { Buffer } from 'node:buffer';\n\nconsole.log(Buffer.isEncoding('utf8'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('hex'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('utf/8'));\n// Prints: false\n\nconsole.log(Buffer.isEncoding(''));\n// Prints: false\n\nconst { Buffer } = require('node:buffer');\n\nconsole.log(Buffer.isEncoding('utf8'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('hex'));\n// Prints: true\n\nconsole.log(Buffer.isEncoding('utf/8'));\n// Prints: false\n\nconsole.log(Buffer.isEncoding(''));\n// Prints: false\n"
}
],
"properties": [
{
"textRaw": "Type: {integer} **Default:** `8192`",
"name": "poolSize",
"type": "integer",
"meta": {
"added": [
"v0.11.3"
],
"changes": []
},
"default": "`8192`",
"desc": "This is the size (in bytes) of pre-allocated internal Buffer instances used\nfor pooling. This value may be modified.
The index operator [index] can be used to get and set the octet at position\nindex in buf. The values refer to individual bytes, so the legal value\nrange is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).
This operator is inherited from Uint8Array, so its behavior on out-of-bounds\naccess is the same as Uint8Array. In other words, buf[index] returns\nundefined when index is negative or greater or equal to buf.length, and\nbuf[index] = value does not modify the buffer if index is negative or\n>= buf.length.
import { Buffer } from 'node:buffer';\n\n// Copy an ASCII string into a `Buffer` one byte at a time.\n// (This only works for ASCII-only strings. In general, one should use\n// `Buffer.from()` to perform this conversion.)\n\nconst str = 'Node.js';\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf.toString('utf8'));\n// Prints: Node.js\n\nconst { Buffer } = require('node:buffer');\n\n// Copy an ASCII string into a `Buffer` one byte at a time.\n// (This only works for ASCII-only strings. In general, one should use\n// `Buffer.from()` to perform this conversion.)\n\nconst str = 'Node.js';\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf.toString('utf8'));\n// Prints: Node.js\n"
},
{
"textRaw": "Type: {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer` object is created.",
"name": "buffer",
"type": "ArrayBuffer",
"desc": "This ArrayBuffer is not guaranteed to correspond exactly to the original\nBuffer. See the notes on buf.byteOffset for details.
import { Buffer } from 'node:buffer';\n\nconst arrayBuffer = new ArrayBuffer(16);\nconst buffer = Buffer.from(arrayBuffer);\n\nconsole.log(buffer.buffer === arrayBuffer);\n// Prints: true\n\nconst { Buffer } = require('node:buffer');\n\nconst arrayBuffer = new ArrayBuffer(16);\nconst buffer = Buffer.from(arrayBuffer);\n\nconsole.log(buffer.buffer === arrayBuffer);\n// Prints: true\n",
"shortDesc": "The underlying `ArrayBuffer` object based on which this `Buffer` object is created."
},
{
"textRaw": "Type: {integer} The `byteOffset` of the `Buffer`'s underlying `ArrayBuffer` object.",
"name": "byteOffset",
"type": "integer",
"desc": "When setting byteOffset in Buffer.from(ArrayBuffer, byteOffset, length),\nor sometimes when allocating a Buffer smaller than Buffer.poolSize, the\nbuffer does not start from a zero offset on the underlying ArrayBuffer.
This can cause problems when accessing the underlying ArrayBuffer directly\nusing buf.buffer, as other parts of the ArrayBuffer may be unrelated\nto the Buffer object itself.
A common issue when creating a TypedArray object that shares its memory with\na Buffer is that in this case one needs to specify the byteOffset correctly:
import { Buffer } from 'node:buffer';\n\n// Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n// When casting the Node.js Buffer to an Int8Array, use the byteOffset\n// to refer only to the part of `nodeBuffer.buffer` that contains the memory\n// for `nodeBuffer`.\nnew Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);\n\nconst { Buffer } = require('node:buffer');\n\n// Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n// When casting the Node.js Buffer to an Int8Array, use the byteOffset\n// to refer only to the part of `nodeBuffer.buffer` that contains the memory\n// for `nodeBuffer`.\nnew Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);\n",
"shortDesc": "The `byteOffset` of the `Buffer`'s underlying `ArrayBuffer` object."
},
{
"textRaw": "Type: {integer}",
"name": "length",
"type": "integer",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"desc": "Returns the number of bytes in buf.
import { Buffer } from 'node:buffer';\n\n// Create a `Buffer` and write a shorter string to it using UTF-8.\n\nconst buf = Buffer.alloc(1234);\n\nconsole.log(buf.length);\n// Prints: 1234\n\nbuf.write('some string', 0, 'utf8');\n\nconsole.log(buf.length);\n// Prints: 1234\n\nconst { Buffer } = require('node:buffer');\n\n// Create a `Buffer` and write a shorter string to it using UTF-8.\n\nconst buf = Buffer.alloc(1234);\n\nconsole.log(buf.length);\n// Prints: 1234\n\nbuf.write('some string', 0, 'utf8');\n\nconsole.log(buf.length);\n// Prints: 1234\n"
},
{
"textRaw": "`buf.parent`",
"name": "parent",
"type": "property",
"meta": {
"changes": [],
"deprecated": [
"v8.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use `buf.buffer` instead.",
"desc": "The buf.parent property is a deprecated alias for buf.buffer.
Compares buf with target and returns a number indicating whether buf\ncomes before, after, or is the same as target in sort order.\nComparison is based on the actual sequence of bytes in each Buffer.
0 is returned if target is the same as buf1 is returned if target should come before buf when sorted.-1 is returned if target should come after buf when sorted.import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.compare(buf1));\n// Prints: 0\nconsole.log(buf1.compare(buf2));\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n// Prints: -1\nconsole.log(buf2.compare(buf1));\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n// Prints: 1\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2].)\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.compare(buf1));\n// Prints: 0\nconsole.log(buf1.compare(buf2));\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n// Prints: -1\nconsole.log(buf2.compare(buf1));\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n// Prints: 1\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2].)\n\nThe optional targetStart, targetEnd, sourceStart, and sourceEnd\narguments can be used to limit the comparison to specific ranges within target\nand buf respectively.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);\n\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n// Prints: 0\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n// Prints: -1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n// Prints: 1\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);\n\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n// Prints: 0\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n// Prints: -1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n// Prints: 1\n\nERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0,\ntargetEnd > target.byteLength, or sourceEnd > source.byteLength.
Copies data from a region of buf to a region in target, even if the target\nmemory region overlaps with buf.
TypedArray.prototype.set() performs the same operation, and is available\nfor all TypedArrays, including Node.js Buffers, although it takes\ndifferent function arguments.
import { Buffer } from 'node:buffer';\n\n// Create two `Buffer` instances.\nconst buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\n// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.\nbuf1.copy(buf2, 8, 16, 20);\n// This is equivalent to:\n// buf2.set(buf1.subarray(16, 20), 8);\n\nconsole.log(buf2.toString('ascii', 0, 25));\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\n\nconst { Buffer } = require('node:buffer');\n\n// Create two `Buffer` instances.\nconst buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\n// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.\nbuf1.copy(buf2, 8, 16, 20);\n// This is equivalent to:\n// buf2.set(buf1.subarray(16, 20), 8);\n\nconsole.log(buf2.toString('ascii', 0, 25));\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\n\nimport { Buffer } from 'node:buffer';\n\n// Create a `Buffer` and copy data from one region to an overlapping region\n// within the same `Buffer`.\n\nconst buf = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf[i] = i + 97;\n}\n\nbuf.copy(buf, 0, 4, 10);\n\nconsole.log(buf.toString());\n// Prints: efghijghijklmnopqrstuvwxyz\n\nconst { Buffer } = require('node:buffer');\n\n// Create a `Buffer` and copy data from one region to an overlapping region\n// within the same `Buffer`.\n\nconst buf = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf[i] = i + 97;\n}\n\nbuf.copy(buf, 0, 4, 10);\n\nconsole.log(buf.toString());\n// Prints: efghijghijklmnopqrstuvwxyz\n"
},
{
"textRaw": "`buf.entries()`",
"name": "entries",
"type": "method",
"meta": {
"added": [
"v1.1.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Iterator}",
"name": "return",
"type": "Iterator"
}
}
],
"desc": "Creates and returns an iterator of [index, byte] pairs from the contents\nof buf.
import { Buffer } from 'node:buffer';\n\n// Log the entire contents of a `Buffer`.\n\nconst buf = Buffer.from('buffer');\n\nfor (const pair of buf.entries()) {\n console.log(pair);\n}\n// Prints:\n// [0, 98]\n// [1, 117]\n// [2, 102]\n// [3, 102]\n// [4, 101]\n// [5, 114]\n\nconst { Buffer } = require('node:buffer');\n\n// Log the entire contents of a `Buffer`.\n\nconst buf = Buffer.from('buffer');\n\nfor (const pair of buf.entries()) {\n console.log(pair);\n}\n// Prints:\n// [0, 98]\n// [1, 117]\n// [2, 102]\n// [3, 102]\n// [4, 101]\n// [5, 114]\n"
},
{
"textRaw": "`buf.equals(otherBuffer)`",
"name": "equals",
"type": "method",
"meta": {
"added": [
"v0.11.13"
],
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10236",
"description": "The arguments can now be `Uint8Array`s."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`otherBuffer` {Buffer|Uint8Array} A `Buffer` or {Uint8Array} with which to compare `buf`.",
"name": "otherBuffer",
"type": "Buffer|Uint8Array",
"desc": "A `Buffer` or {Uint8Array} with which to compare `buf`."
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if both buf and otherBuffer have exactly the same bytes,\nfalse otherwise. Equivalent to\nbuf.compare(otherBuffer) === 0.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.equals(buf2));\n// Prints: true\nconsole.log(buf1.equals(buf3));\n// Prints: false\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.equals(buf2));\n// Prints: true\nconsole.log(buf1.equals(buf3));\n// Prints: false\n"
},
{
"textRaw": "`buf.fill(value[, offset[, end]][, encoding])`",
"name": "fill",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/22969",
"description": "Throws `ERR_OUT_OF_RANGE` instead of `ERR_INDEX_OUT_OF_RANGE`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18790",
"description": "Negative `end` values throw an `ERR_INDEX_OUT_OF_RANGE` error."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18129",
"description": "Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/17427",
"description": "Specifying an invalid string for `value` triggers a thrown exception."
},
{
"version": "v5.7.0",
"pr-url": "https://github.com/nodejs/node/pull/4935",
"description": "The `encoding` parameter is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`.",
"name": "value",
"type": "string|Buffer|Uint8Array|integer",
"desc": "The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to fill `buf`.",
"optional": true
},
{
"textRaw": "`end` {integer} Where to stop filling `buf` (not inclusive). **Default:** `buf.length`.",
"name": "end",
"type": "integer",
"default": "`buf.length`",
"desc": "Where to stop filling `buf` (not inclusive).",
"optional": true
},
{
"textRaw": "`encoding` {string} The encoding for `value` if `value` is a string. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "The encoding for `value` if `value` is a string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf`.",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`."
}
}
],
"desc": "Fills buf with the specified value. If the offset and end are not given,\nthe entire buf will be filled:
import { Buffer } from 'node:buffer';\n\n// Fill a `Buffer` with the ASCII character 'h'.\n\nconst b = Buffer.allocUnsafe(50).fill('h');\n\nconsole.log(b.toString());\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n\n// Fill a buffer with empty string\nconst c = Buffer.allocUnsafe(5).fill('');\n\nconsole.log(c.fill(''));\n// Prints: <Buffer 00 00 00 00 00>\n\nconst { Buffer } = require('node:buffer');\n\n// Fill a `Buffer` with the ASCII character 'h'.\n\nconst b = Buffer.allocUnsafe(50).fill('h');\n\nconsole.log(b.toString());\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\n\n// Fill a buffer with empty string\nconst c = Buffer.allocUnsafe(5).fill('');\n\nconsole.log(c.fill(''));\n// Prints: <Buffer 00 00 00 00 00>\n\nvalue is coerced to a uint32 value if it is not a string, Buffer, or\ninteger. If the resulting integer is greater than 255 (decimal), buf will be\nfilled with value & 255.
If the final write of a fill() operation falls on a multi-byte character,\nthen only the bytes of that character that fit into buf are written:
import { Buffer } from 'node:buffer';\n\n// Fill a `Buffer` with character that takes up two bytes in UTF-8.\n\nconsole.log(Buffer.allocUnsafe(5).fill('\\u0222'));\n// Prints: <Buffer c8 a2 c8 a2 c8>\n\nconst { Buffer } = require('node:buffer');\n\n// Fill a `Buffer` with character that takes up two bytes in UTF-8.\n\nconsole.log(Buffer.allocUnsafe(5).fill('\\u0222'));\n// Prints: <Buffer c8 a2 c8 a2 c8>\n\nIf value contains invalid characters, it is truncated; if no valid\nfill data remains, an exception is thrown:
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(5);\n\nconsole.log(buf.fill('a'));\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf.fill('aazz', 'hex'));\n// Prints: <Buffer aa aa aa aa aa>\nconsole.log(buf.fill('zz', 'hex'));\n// Throws an exception.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(5);\n\nconsole.log(buf.fill('a'));\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf.fill('aazz', 'hex'));\n// Prints: <Buffer aa aa aa aa aa>\nconsole.log(buf.fill('zz', 'hex'));\n// Throws an exception.\n"
},
{
"textRaw": "`buf.includes(value[, byteOffset][, encoding])`",
"name": "includes",
"type": "method",
"meta": {
"added": [
"v5.3.0"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.",
"name": "value",
"type": "string|Buffer|Uint8Array|integer",
"desc": "What to search for."
},
{
"textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.",
"name": "byteOffset",
"type": "integer",
"default": "`0`",
"desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.",
"optional": true
},
{
"textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "If `value` is a string, this is its encoding.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if `value` was found in `buf`, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if `value` was found in `buf`, `false` otherwise."
}
}
],
"desc": "Equivalent to buf.indexOf() !== -1.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.includes('this'));\n// Prints: true\nconsole.log(buf.includes('is'));\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n// Prints: true\nconsole.log(buf.includes(97));\n// Prints: true (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: true\nconsole.log(buf.includes('this', 4));\n// Prints: false\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.includes('this'));\n// Prints: true\nconsole.log(buf.includes('is'));\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n// Prints: true\nconsole.log(buf.includes(97));\n// Prints: true (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: true\nconsole.log(buf.includes('this', 4));\n// Prints: false\n"
},
{
"textRaw": "`buf.indexOf(value[, byteOffset][, encoding])`",
"name": "indexOf",
"type": "method",
"meta": {
"added": [
"v1.5.0"
],
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10236",
"description": "The `value` can now be a `Uint8Array`."
},
{
"version": [
"v5.7.0",
"v4.4.0"
],
"pr-url": "https://github.com/nodejs/node/pull/4803",
"description": "When `encoding` is being passed, the `byteOffset` parameter is no longer required."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.",
"name": "value",
"type": "string|Buffer|Uint8Array|integer",
"desc": "What to search for."
},
{
"textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `0`.",
"name": "byteOffset",
"type": "integer",
"default": "`0`",
"desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.",
"optional": true
},
{
"textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.",
"name": "return",
"type": "integer",
"desc": "The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`."
}
}
],
"desc": "If value is:
value is interpreted according to the character encoding in\nencoding.Buffer or <Uint8Array>, value will be used in its entirety.\nTo compare a partial Buffer, use buf.subarray.value will be interpreted as an unsigned 8-bit integer\nvalue between 0 and 255.import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.indexOf('this'));\n// Prints: 0\nconsole.log(buf.indexOf('is'));\n// Prints: 2\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n// Prints: 8\nconsole.log(buf.indexOf(97));\n// Prints: 8 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: 8\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'utf16le'));\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'utf16le'));\n// Prints: 6\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('this is a buffer');\n\nconsole.log(buf.indexOf('this'));\n// Prints: 0\nconsole.log(buf.indexOf('is'));\n// Prints: 2\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n// Prints: 8\nconsole.log(buf.indexOf(97));\n// Prints: 8 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n// Prints: 8\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'utf16le'));\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'utf16le'));\n// Prints: 6\n\nIf value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.
If byteOffset is not a number, it will be coerced to a number. If the result\nof coercion is NaN or 0, then the entire buffer will be searched. This\nbehavior matches String.prototype.indexOf().
import { Buffer } from 'node:buffer';\n\nconst b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.indexOf(99.9));\nconsole.log(b.indexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN or 0.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.indexOf('b', undefined));\nconsole.log(b.indexOf('b', {}));\nconsole.log(b.indexOf('b', null));\nconsole.log(b.indexOf('b', []));\n\nconst { Buffer } = require('node:buffer');\n\nconst b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.indexOf(99.9));\nconsole.log(b.indexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN or 0.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.indexOf('b', undefined));\nconsole.log(b.indexOf('b', {}));\nconsole.log(b.indexOf('b', null));\nconsole.log(b.indexOf('b', []));\n\nIf value is an empty string or empty Buffer and byteOffset is less\nthan buf.length, byteOffset will be returned. If value is empty and\nbyteOffset is at least buf.length, buf.length will be returned.
Creates and returns an iterator of buf keys (indexes).
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('buffer');\n\nfor (const key of buf.keys()) {\n console.log(key);\n}\n// Prints:\n// 0\n// 1\n// 2\n// 3\n// 4\n// 5\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('buffer');\n\nfor (const key of buf.keys()) {\n console.log(key);\n}\n// Prints:\n// 0\n// 1\n// 2\n// 3\n// 4\n// 5\n"
},
{
"textRaw": "`buf.lastIndexOf(value[, byteOffset][, encoding])`",
"name": "lastIndexOf",
"type": "method",
"meta": {
"added": [
"v6.0.0"
],
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10236",
"description": "The `value` can now be a `Uint8Array`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {string|Buffer|Uint8Array|integer} What to search for.",
"name": "value",
"type": "string|Buffer|Uint8Array|integer",
"desc": "What to search for."
},
{
"textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. **Default:** `buf.length - 1`.",
"name": "byteOffset",
"type": "integer",
"default": "`buf.length - 1`",
"desc": "Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.",
"optional": true
},
{
"textRaw": "`encoding` {string} If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.",
"name": "return",
"type": "integer",
"desc": "The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`."
}
}
],
"desc": "Identical to buf.indexOf(), except the last occurrence of value is found\nrather than the first occurrence.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('this buffer is a buffer');\n\nconsole.log(buf.lastIndexOf('this'));\n// Prints: 0\nconsole.log(buf.lastIndexOf('buffer'));\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n// Prints: 17\nconsole.log(buf.lastIndexOf(97));\n// Prints: 15 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 5));\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 4));\n// Prints: -1\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'utf16le'));\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'utf16le'));\n// Prints: 4\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('this buffer is a buffer');\n\nconsole.log(buf.lastIndexOf('this'));\n// Prints: 0\nconsole.log(buf.lastIndexOf('buffer'));\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n// Prints: 17\nconsole.log(buf.lastIndexOf(97));\n// Prints: 15 (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 5));\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 4));\n// Prints: -1\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'utf16le');\n\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'utf16le'));\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'utf16le'));\n// Prints: 4\n\nIf value is not a string, number, or Buffer, this method will throw a\nTypeError. If value is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.
If byteOffset is not a number, it will be coerced to a number. Any arguments\nthat coerce to NaN, like {} or undefined, will search the whole buffer.\nThis behavior matches String.prototype.lastIndexOf().
import { Buffer } from 'node:buffer';\n\nconst b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.lastIndexOf(99.9));\nconsole.log(b.lastIndexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.lastIndexOf('b', undefined));\nconsole.log(b.lastIndexOf('b', {}));\n\n// Passing a byteOffset that coerces to 0.\n// Prints: -1, equivalent to passing 0.\nconsole.log(b.lastIndexOf('b', null));\nconsole.log(b.lastIndexOf('b', []));\n\nconst { Buffer } = require('node:buffer');\n\nconst b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte.\n// Prints: 2, equivalent to searching for 99 or 'c'.\nconsole.log(b.lastIndexOf(99.9));\nconsole.log(b.lastIndexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN.\n// Prints: 1, searching the whole buffer.\nconsole.log(b.lastIndexOf('b', undefined));\nconsole.log(b.lastIndexOf('b', {}));\n\n// Passing a byteOffset that coerces to 0.\n// Prints: -1, equivalent to passing 0.\nconsole.log(b.lastIndexOf('b', null));\nconsole.log(b.lastIndexOf('b', []));\n\nIf value is an empty string or empty Buffer, byteOffset will be returned.
Reads a signed, big-endian 64-bit integer from buf at the specified offset.
Integers read from a Buffer are interpreted as two's complement signed\nvalues.
Reads a signed, little-endian 64-bit integer from buf at the specified\noffset.
Integers read from a Buffer are interpreted as two's complement signed\nvalues.
Reads an unsigned, big-endian 64-bit integer from buf at the specified\noffset.
This function is also available under the readBigUint64BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64BE(0));\n// Prints: 4294967295n\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64BE(0));\n// Prints: 4294967295n\n"
},
{
"textRaw": "`buf.readBigUInt64LE([offset])`",
"name": "readBigUInt64LE",
"type": "method",
"meta": {
"added": [
"v12.0.0",
"v10.20.0"
],
"changes": [
{
"version": [
"v14.10.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34960",
"description": "This function is also available as `buf.readBigUint64LE()`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {bigint}",
"name": "return",
"type": "bigint"
}
}
],
"desc": "Reads an unsigned, little-endian 64-bit integer from buf at the specified\noffset.
This function is also available under the readBigUint64LE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64LE(0));\n// Prints: 18446744069414584320n\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64LE(0));\n// Prints: 18446744069414584320n\n"
},
{
"textRaw": "`buf.readDoubleBE([offset])`",
"name": "readDoubleBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {number}",
"name": "return",
"type": "number"
}
}
],
"desc": "Reads a 64-bit, big-endian double from buf at the specified offset.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleBE(0));\n// Prints: 8.20788039913184e-304\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleBE(0));\n// Prints: 8.20788039913184e-304\n"
},
{
"textRaw": "`buf.readDoubleLE([offset])`",
"name": "readDoubleLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {number}",
"name": "return",
"type": "number"
}
}
],
"desc": "Reads a 64-bit, little-endian double from buf at the specified offset.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleLE(0));\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE(1));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\nconsole.log(buf.readDoubleLE(0));\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE(1));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readFloatBE([offset])`",
"name": "readFloatBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {number}",
"name": "return",
"type": "number"
}
}
],
"desc": "Reads a 32-bit, big-endian float from buf at the specified offset.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatBE(0));\n// Prints: 2.387939260590663e-38\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatBE(0));\n// Prints: 2.387939260590663e-38\n"
},
{
"textRaw": "`buf.readFloatLE([offset])`",
"name": "readFloatLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {number}",
"name": "return",
"type": "number"
}
}
],
"desc": "Reads a 32-bit, little-endian float from buf at the specified offset.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatLE(0));\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE(1));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatLE(0));\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE(1));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readInt8([offset])`",
"name": "readInt8",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads a signed 8-bit integer from buf at the specified offset.
Integers read from a Buffer are interpreted as two's complement signed values.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([-1, 5]);\n\nconsole.log(buf.readInt8(0));\n// Prints: -1\nconsole.log(buf.readInt8(1));\n// Prints: 5\nconsole.log(buf.readInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([-1, 5]);\n\nconsole.log(buf.readInt8(0));\n// Prints: -1\nconsole.log(buf.readInt8(1));\n// Prints: 5\nconsole.log(buf.readInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readInt16BE([offset])`",
"name": "readInt16BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads a signed, big-endian 16-bit integer from buf at the specified offset.
Integers read from a Buffer are interpreted as two's complement signed values.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n"
},
{
"textRaw": "`buf.readInt16LE([offset])`",
"name": "readInt16LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads a signed, little-endian 16-bit integer from buf at the specified\noffset.
Integers read from a Buffer are interpreted as two's complement signed values.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16LE(0));\n// Prints: 1280\nconsole.log(buf.readInt16LE(1));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16LE(0));\n// Prints: 1280\nconsole.log(buf.readInt16LE(1));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readInt32BE([offset])`",
"name": "readInt32BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads a signed, big-endian 32-bit integer from buf at the specified offset.
Integers read from a Buffer are interpreted as two's complement signed values.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n"
},
{
"textRaw": "`buf.readInt32LE([offset])`",
"name": "readInt32LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads a signed, little-endian 32-bit integer from buf at the specified\noffset.
Integers read from a Buffer are interpreted as two's complement signed values.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32LE(0));\n// Prints: 83886080\nconsole.log(buf.readInt32LE(1));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32LE(0));\n// Prints: 83886080\nconsole.log(buf.readInt32LE(1));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readIntBE(offset, byteLength)`",
"name": "readIntBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a big-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\nconsole.log(buf.readIntBE(1, 0).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\nconsole.log(buf.readIntBE(1, 0).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readIntLE(offset, byteLength)`",
"name": "readIntLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a little-endian, two's complement signed value\nsupporting up to 48 bits of accuracy.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntLE(0, 6).toString(16));\n// Prints: -546f87a9cbee\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readIntLE(0, 6).toString(16));\n// Prints: -546f87a9cbee\n"
},
{
"textRaw": "`buf.readUInt8([offset])`",
"name": "readUInt8",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUint8()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads an unsigned 8-bit integer from buf at the specified offset.
This function is also available under the readUint8 alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([1, -2]);\n\nconsole.log(buf.readUInt8(0));\n// Prints: 1\nconsole.log(buf.readUInt8(1));\n// Prints: 254\nconsole.log(buf.readUInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([1, -2]);\n\nconsole.log(buf.readUInt8(0));\n// Prints: 1\nconsole.log(buf.readUInt8(1));\n// Prints: 254\nconsole.log(buf.readUInt8(2));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readUInt16BE([offset])`",
"name": "readUInt16BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUint16BE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads an unsigned, big-endian 16-bit integer from buf at the specified\noffset.
This function is also available under the readUint16BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16BE(0).toString(16));\n// Prints: 1234\nconsole.log(buf.readUInt16BE(1).toString(16));\n// Prints: 3456\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16BE(0).toString(16));\n// Prints: 1234\nconsole.log(buf.readUInt16BE(1).toString(16));\n// Prints: 3456\n"
},
{
"textRaw": "`buf.readUInt16LE([offset])`",
"name": "readUInt16LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUint16LE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads an unsigned, little-endian 16-bit integer from buf at the specified\noffset.
This function is also available under the readUint16LE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16LE(0).toString(16));\n// Prints: 3412\nconsole.log(buf.readUInt16LE(1).toString(16));\n// Prints: 5634\nconsole.log(buf.readUInt16LE(2).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\nconsole.log(buf.readUInt16LE(0).toString(16));\n// Prints: 3412\nconsole.log(buf.readUInt16LE(1).toString(16));\n// Prints: 5634\nconsole.log(buf.readUInt16LE(2).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readUInt32BE([offset])`",
"name": "readUInt32BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUint32BE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads an unsigned, big-endian 32-bit integer from buf at the specified\noffset.
This function is also available under the readUint32BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32BE(0).toString(16));\n// Prints: 12345678\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32BE(0).toString(16));\n// Prints: 12345678\n"
},
{
"textRaw": "`buf.readUInt32LE([offset])`",
"name": "readUInt32LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUint32LE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads an unsigned, little-endian 32-bit integer from buf at the specified\noffset.
This function is also available under the readUint32LE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32LE(0).toString(16));\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(1).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32LE(0).toString(16));\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(1).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readUIntBE(offset, byteLength)`",
"name": "readUIntBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
},
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUintBE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned big-endian integer supporting\nup to 48 bits of accuracy.
This function is also available under the readUintBE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n// Throws ERR_OUT_OF_RANGE.\n"
},
{
"textRaw": "`buf.readUIntLE(offset, byteLength)`",
"name": "readUIntLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
},
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.readUintLE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to read. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to read. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned, little-endian integer supporting\nup to 48 bits of accuracy.
This function is also available under the readUintLE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n// Prints: ab9078563412\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n// Prints: ab9078563412\n"
},
{
"textRaw": "`buf.subarray([start[, end]])`",
"name": "subarray",
"type": "method",
"meta": {
"added": [
"v3.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.",
"name": "start",
"type": "integer",
"default": "`0`",
"desc": "Where the new `Buffer` will start.",
"optional": true
},
{
"textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** `buf.length`.",
"name": "end",
"type": "integer",
"default": "`buf.length`",
"desc": "Where the new `Buffer` will end (not inclusive).",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indexes.
Specifying end greater than buf.length will return the same result as\nthat of end equal to buf.length.
This method is inherited from TypedArray.prototype.subarray().
Modifying the new Buffer slice will modify the memory in the original Buffer\nbecause the allocated memory of the two objects overlap.
import { Buffer } from 'node:buffer';\n\n// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte\n// from the original `Buffer`.\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\nconst buf2 = buf1.subarray(0, 3);\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: abc\n\nbuf1[0] = 33;\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: !bc\n\nconst { Buffer } = require('node:buffer');\n\n// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte\n// from the original `Buffer`.\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\nconst buf2 = buf1.subarray(0, 3);\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: abc\n\nbuf1[0] = 33;\n\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n// Prints: !bc\n\nSpecifying negative indexes causes the slice to be generated relative to the\nend of buf rather than the beginning.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('buffer');\n\nconsole.log(buf.subarray(-6, -1).toString());\n// Prints: buffe\n// (Equivalent to buf.subarray(0, 5).)\n\nconsole.log(buf.subarray(-6, -2).toString());\n// Prints: buff\n// (Equivalent to buf.subarray(0, 4).)\n\nconsole.log(buf.subarray(-5, -2).toString());\n// Prints: uff\n// (Equivalent to buf.subarray(1, 4).)\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('buffer');\n\nconsole.log(buf.subarray(-6, -1).toString());\n// Prints: buffe\n// (Equivalent to buf.subarray(0, 5).)\n\nconsole.log(buf.subarray(-6, -2).toString());\n// Prints: buff\n// (Equivalent to buf.subarray(0, 4).)\n\nconsole.log(buf.subarray(-5, -2).toString());\n// Prints: uff\n// (Equivalent to buf.subarray(1, 4).)\n"
},
{
"textRaw": "`buf.slice([start[, end]])`",
"name": "slice",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": [
{
"version": [
"v17.5.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41596",
"description": "The buf.slice() method has been deprecated."
},
{
"version": [
"v7.1.0",
"v6.9.2"
],
"pr-url": "https://github.com/nodejs/node/pull/9341",
"description": "Coercing the offsets to integers now handles values outside the 32-bit integer range properly."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/9101",
"description": "All offsets are now coerced to integers before doing any calculations with them."
}
]
},
"stability": 0,
"stabilityText": "Deprecated: Use `buf.subarray` instead.",
"signatures": [
{
"params": [
{
"textRaw": "`start` {integer} Where the new `Buffer` will start. **Default:** `0`.",
"name": "start",
"type": "integer",
"default": "`0`",
"desc": "Where the new `Buffer` will start.",
"optional": true
},
{
"textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** `buf.length`.",
"name": "end",
"type": "integer",
"default": "`buf.length`",
"desc": "Where the new `Buffer` will end (not inclusive).",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indexes.
This method is not compatible with the Uint8Array.prototype.slice(),\nwhich is a superclass of Buffer. To copy the slice, use\nUint8Array.prototype.slice().
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('buffer');\n\nconst copiedBuf = Uint8Array.prototype.slice.call(buf);\ncopiedBuf[0]++;\nconsole.log(copiedBuf.toString());\n// Prints: cuffer\n\nconsole.log(buf.toString());\n// Prints: buffer\n\n// With buf.slice(), the original buffer is modified.\nconst notReallyCopiedBuf = buf.slice();\nnotReallyCopiedBuf[0]++;\nconsole.log(notReallyCopiedBuf.toString());\n// Prints: cuffer\nconsole.log(buf.toString());\n// Also prints: cuffer (!)\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('buffer');\n\nconst copiedBuf = Uint8Array.prototype.slice.call(buf);\ncopiedBuf[0]++;\nconsole.log(copiedBuf.toString());\n// Prints: cuffer\n\nconsole.log(buf.toString());\n// Prints: buffer\n\n// With buf.slice(), the original buffer is modified.\nconst notReallyCopiedBuf = buf.slice();\nnotReallyCopiedBuf[0]++;\nconsole.log(notReallyCopiedBuf.toString());\n// Prints: cuffer\nconsole.log(buf.toString());\n// Also prints: cuffer (!)\n"
},
{
"textRaw": "`buf.swap16()`",
"name": "swap16",
"type": "method",
"meta": {
"added": [
"v5.10.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf`.",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`."
}
}
],
"desc": "Interprets buf as an array of unsigned 16-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 2.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap16();\n\nconsole.log(buf1);\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap16();\n// Throws ERR_INVALID_BUFFER_SIZE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap16();\n\nconsole.log(buf1);\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap16();\n// Throws ERR_INVALID_BUFFER_SIZE.\n\nOne convenient use of buf.swap16() is to perform a fast in-place conversion\nbetween UTF-16 little-endian and UTF-16 big-endian:
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('This is little-endian UTF-16', 'utf16le');\nbuf.swap16(); // Convert to big-endian UTF-16 text.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('This is little-endian UTF-16', 'utf16le');\nbuf.swap16(); // Convert to big-endian UTF-16 text.\n"
},
{
"textRaw": "`buf.swap32()`",
"name": "swap32",
"type": "method",
"meta": {
"added": [
"v5.10.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf`.",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`."
}
}
],
"desc": "Interprets buf as an array of unsigned 32-bit integers and swaps the\nbyte order in-place. Throws ERR_INVALID_BUFFER_SIZE if buf.length\nis not a multiple of 4.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap32();\n\nconsole.log(buf1);\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap32();\n// Throws ERR_INVALID_BUFFER_SIZE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap32();\n\nconsole.log(buf1);\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap32();\n// Throws ERR_INVALID_BUFFER_SIZE.\n"
},
{
"textRaw": "`buf.swap64()`",
"name": "swap64",
"type": "method",
"meta": {
"added": [
"v6.3.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf`.",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`."
}
}
],
"desc": "Interprets buf as an array of 64-bit numbers and swaps byte order in-place.\nThrows ERR_INVALID_BUFFER_SIZE if buf.length is not a multiple of 8.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap64();\n\nconsole.log(buf1);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap64();\n// Throws ERR_INVALID_BUFFER_SIZE.\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\nconsole.log(buf1);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nbuf1.swap64();\n\nconsole.log(buf1);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\nbuf2.swap64();\n// Throws ERR_INVALID_BUFFER_SIZE.\n"
},
{
"textRaw": "`buf.toJSON()`",
"name": "toJSON",
"type": "method",
"meta": {
"added": [
"v0.9.2"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a JSON representation of buf. JSON.stringify() implicitly calls\nthis function when stringifying a Buffer instance.
Buffer.from() accepts objects in the format returned from this method.\nIn particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\nconsole.log(json);\n// Prints: {\"type\":\"Buffer\",\"data\":[1,2,3,4,5]}\n\nconst copy = JSON.parse(json, (key, value) => {\n return value && value.type === 'Buffer' ?\n Buffer.from(value) :\n value;\n});\n\nconsole.log(copy);\n// Prints: <Buffer 01 02 03 04 05>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\nconsole.log(json);\n// Prints: {\"type\":\"Buffer\",\"data\":[1,2,3,4,5]}\n\nconst copy = JSON.parse(json, (key, value) => {\n return value && value.type === 'Buffer' ?\n Buffer.from(value) :\n value;\n});\n\nconsole.log(copy);\n// Prints: <Buffer 01 02 03 04 05>\n"
},
{
"textRaw": "`buf.toString([encoding[, start[, end]]])`",
"name": "toString",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`encoding` {string} The character encoding to use. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "The character encoding to use.",
"optional": true
},
{
"textRaw": "`start` {integer} The byte offset to start decoding at. **Default:** `0`.",
"name": "start",
"type": "integer",
"default": "`0`",
"desc": "The byte offset to start decoding at.",
"optional": true
},
{
"textRaw": "`end` {integer} The byte offset to stop decoding at (not inclusive). **Default:** `buf.length`.",
"name": "end",
"type": "integer",
"default": "`buf.length`",
"desc": "The byte offset to stop decoding at (not inclusive).",
"optional": true
}
],
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
}
}
],
"desc": "Decodes buf to a string according to the specified character encoding in\nencoding. start and end may be passed to decode only a subset of buf.
If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8,\nthen each invalid byte is replaced with the replacement character U+FFFD.
The maximum length of a string instance (in UTF-16 code units) is available\nas buffer.constants.MAX_STRING_LENGTH.
import { Buffer } from 'node:buffer';\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\nconsole.log(buf1.toString('utf8'));\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('utf8', 0, 5));\n// Prints: abcde\n\nconst buf2 = Buffer.from('tést');\n\nconsole.log(buf2.toString('hex'));\n// Prints: 74c3a97374\nconsole.log(buf2.toString('utf8', 0, 3));\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n// Prints: té\n\nconst { Buffer } = require('node:buffer');\n\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0; i < 26; i++) {\n // 97 is the decimal ASCII value for 'a'.\n buf1[i] = i + 97;\n}\n\nconsole.log(buf1.toString('utf8'));\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('utf8', 0, 5));\n// Prints: abcde\n\nconst buf2 = Buffer.from('tést');\n\nconsole.log(buf2.toString('hex'));\n// Prints: 74c3a97374\nconsole.log(buf2.toString('utf8', 0, 3));\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n// Prints: té\n"
},
{
"textRaw": "`buf.values()`",
"name": "values",
"type": "method",
"meta": {
"added": [
"v1.1.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Iterator}",
"name": "return",
"type": "Iterator"
}
}
],
"desc": "Creates and returns an iterator for buf values (bytes). This function is\ncalled automatically when a Buffer is used in a for..of statement.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.from('buffer');\n\nfor (const value of buf.values()) {\n console.log(value);\n}\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\n\nfor (const value of buf) {\n console.log(value);\n}\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.from('buffer');\n\nfor (const value of buf.values()) {\n console.log(value);\n}\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\n\nfor (const value of buf) {\n console.log(value);\n}\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\n"
},
{
"textRaw": "`buf.write(string[, offset[, length]][, encoding])`",
"name": "write",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/56578",
"description": "supports Uint8Array as `this` value."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`string` {string} String to write to `buf`.",
"name": "string",
"type": "string",
"desc": "String to write to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write `string`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write `string`.",
"optional": true
},
{
"textRaw": "`length` {integer} Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). **Default:** `buf.length - offset`.",
"name": "length",
"type": "integer",
"default": "`buf.length - offset`",
"desc": "Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`).",
"optional": true
},
{
"textRaw": "`encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "The character encoding of `string`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} Number of bytes written.",
"name": "return",
"type": "integer",
"desc": "Number of bytes written."
}
}
],
"desc": "Writes string to buf at offset according to the character encoding in\nencoding. The length parameter is the number of bytes to write. If buf did\nnot contain enough space to fit the entire string, only part of string will be\nwritten. However, partially encoded characters will not be written.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.alloc(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n// Prints: 12 bytes: ½ + ¼ = ¾\n\nconst buffer = Buffer.alloc(10);\n\nconst length = buffer.write('abcd', 8);\n\nconsole.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);\n// Prints: 2 bytes : ab\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n// Prints: 12 bytes: ½ + ¼ = ¾\n\nconst buffer = Buffer.alloc(10);\n\nconst length = buffer.write('abcd', 8);\n\nconsole.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);\n// Prints: 2 bytes : ab\n"
},
{
"textRaw": "`buf.writeBigInt64BE(value[, offset])`",
"name": "writeBigInt64BE",
"type": "method",
"meta": {
"added": [
"v12.0.0",
"v10.20.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {bigint} Number to be written to `buf`.",
"name": "value",
"type": "bigint",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian.
value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64BE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64BE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\n"
},
{
"textRaw": "`buf.writeBigInt64LE(value[, offset])`",
"name": "writeBigInt64LE",
"type": "method",
"meta": {
"added": [
"v12.0.0",
"v10.20.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {bigint} Number to be written to `buf`.",
"name": "value",
"type": "bigint",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian.
value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64LE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigInt64LE(0x0102030405060708n, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\n"
},
{
"textRaw": "`buf.writeBigUInt64BE(value[, offset])`",
"name": "writeBigUInt64BE",
"type": "method",
"meta": {
"added": [
"v12.0.0",
"v10.20.0"
],
"changes": [
{
"version": [
"v14.10.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34960",
"description": "This function is also available as `buf.writeBigUint64BE()`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {bigint} Number to be written to `buf`.",
"name": "value",
"type": "bigint",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian.
This function is also available under the writeBigUint64BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64BE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de ca fa fe ca ce fa de>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64BE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de ca fa fe ca ce fa de>\n"
},
{
"textRaw": "`buf.writeBigUInt64LE(value[, offset])`",
"name": "writeBigUInt64LE",
"type": "method",
"meta": {
"added": [
"v12.0.0",
"v10.20.0"
],
"changes": [
{
"version": [
"v14.10.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34960",
"description": "This function is also available as `buf.writeBigUint64LE()`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {bigint} Number to be written to `buf`.",
"name": "value",
"type": "bigint",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64LE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de fa ce ca fe fa ca de>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeBigUInt64LE(0xdecafafecacefaden, 0);\n\nconsole.log(buf);\n// Prints: <Buffer de fa ce ca fe fa ca de>\n\nThis function is also available under the writeBigUint64LE alias.
Writes value to buf at the specified offset as big-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 40 5e dd 2f 1a 9f be 77>\n"
},
{
"textRaw": "`buf.writeDoubleLE(value[, offset])`",
"name": "writeDoubleLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {number} Number to be written to `buf`.",
"name": "value",
"type": "number",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. The value\nmust be a JavaScript number. Behavior is undefined when value is anything\nother than a JavaScript number.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleLE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleLE(123.456, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>\n"
},
{
"textRaw": "`buf.writeFloatBE(value[, offset])`",
"name": "writeFloatBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {number} Number to be written to `buf`.",
"name": "value",
"type": "number",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian. Behavior is\nundefined when value is anything other than a JavaScript number.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 4f 4a fe bb>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 4f 4a fe bb>\n"
},
{
"textRaw": "`buf.writeFloatLE(value[, offset])`",
"name": "writeFloatLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {number} Number to be written to `buf`.",
"name": "value",
"type": "number",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. Behavior is\nundefined when value is anything other than a JavaScript number.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer bb fe 4a 4f>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer bb fe 4a 4f>\n"
},
{
"textRaw": "`buf.writeInt8(value[, offset])`",
"name": "writeInt8",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset. value must be a valid\nsigned 8-bit integer. Behavior is undefined when value is anything other than\na signed 8-bit integer.
value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\nconsole.log(buf);\n// Prints: <Buffer 02 fe>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\nconsole.log(buf);\n// Prints: <Buffer 02 fe>\n"
},
{
"textRaw": "`buf.writeInt16BE(value[, offset])`",
"name": "writeInt16BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.
The value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16BE(0x0102, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16BE(0x0102, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02>\n"
},
{
"textRaw": "`buf.writeInt16LE(value[, offset])`",
"name": "writeInt16LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 16-bit integer. Behavior is undefined when value is\nanything other than a signed 16-bit integer.
The value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16LE(0x0304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 04 03>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16LE(0x0304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 04 03>\n"
},
{
"textRaw": "`buf.writeInt32BE(value[, offset])`",
"name": "writeInt32BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.
The value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32BE(0x01020304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32BE(0x01020304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04>\n"
},
{
"textRaw": "`buf.writeInt32LE(value[, offset])`",
"name": "writeInt32LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. The value\nmust be a valid signed 32-bit integer. Behavior is undefined when value is\nanything other than a signed 32-bit integer.
The value is interpreted and written as a two's complement signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32LE(0x05060708, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32LE(0x05060708, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05>\n"
},
{
"textRaw": "`buf.writeIntBE(value, offset, byteLength)`",
"name": "writeIntBE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when\nvalue is anything other than a signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n"
},
{
"textRaw": "`buf.writeIntLE(value, offset, byteLength)`",
"name": "writeIntLE",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than a signed integer.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n"
},
{
"textRaw": "`buf.writeUInt8(value[, offset])`",
"name": "writeUInt8",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUint8()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset. value must be a\nvalid unsigned 8-bit integer. Behavior is undefined when value is anything\nother than an unsigned 8-bit integer.
This function is also available under the writeUint8 alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n// Prints: <Buffer 03 04 23 42>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n// Prints: <Buffer 03 04 23 42>\n"
},
{
"textRaw": "`buf.writeUInt16BE(value[, offset])`",
"name": "writeUInt16BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUint16BE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value\nis anything other than an unsigned 16-bit integer.
This function is also available under the writeUint16BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer de ad be ef>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer de ad be ef>\n"
},
{
"textRaw": "`buf.writeUInt16LE(value[, offset])`",
"name": "writeUInt16LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUint16LE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 16-bit integer. Behavior is undefined when value is\nanything other than an unsigned 16-bit integer.
This function is also available under the writeUint16LE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer ad de ef be>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n// Prints: <Buffer ad de ef be>\n"
},
{
"textRaw": "`buf.writeUInt32BE(value[, offset])`",
"name": "writeUInt32BE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUint32BE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as big-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value\nis anything other than an unsigned 32-bit integer.
This function is also available under the writeUint32BE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer fe ed fa ce>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer fe ed fa ce>\n"
},
{
"textRaw": "`buf.writeUInt32LE(value[, offset])`",
"name": "writeUInt32LE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUint32LE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.",
"name": "offset",
"type": "integer",
"default": "`0`",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes value to buf at the specified offset as little-endian. The value\nmust be a valid unsigned 32-bit integer. Behavior is undefined when value is\nanything other than an unsigned 32-bit integer.
This function is also available under the writeUint32LE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer ce fa ed fe>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer ce fa ed fe>\n"
},
{
"textRaw": "`buf.writeUIntBE(value, offset, byteLength)`",
"name": "writeUIntBE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUintBE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes byteLength bytes of value to buf at the specified offset\nas big-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.
This function is also available under the writeUintBE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer 12 34 56 78 90 ab>\n"
},
{
"textRaw": "`buf.writeUIntLE(value, offset, byteLength)`",
"name": "writeUIntLE",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": [
"v14.9.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/34729",
"description": "This function is also available as `buf.writeUintLE()`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18395",
"description": "Removed `noAssert` and no implicit coercion of the offset and `byteLength` to `uint32` anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {integer} Number to be written to `buf`.",
"name": "value",
"type": "integer",
"desc": "Number to be written to `buf`."
},
{
"textRaw": "`offset` {integer} Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.",
"name": "offset",
"type": "integer",
"desc": "Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`."
},
{
"textRaw": "`byteLength` {integer} Number of bytes to write. Must satisfy `0 < byteLength <= 6`.",
"name": "byteLength",
"type": "integer",
"desc": "Number of bytes to write. Must satisfy `0 < byteLength <= 6`."
}
],
"return": {
"textRaw": "Returns: {integer} `offset` plus the number of bytes written.",
"name": "return",
"type": "integer",
"desc": "`offset` plus the number of bytes written."
}
}
],
"desc": "Writes byteLength bytes of value to buf at the specified offset\nas little-endian. Supports up to 48 bits of accuracy. Behavior is undefined\nwhen value is anything other than an unsigned integer.
This function is also available under the writeUintLE alias.
import { Buffer } from 'node:buffer';\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\nconsole.log(buf);\n// Prints: <Buffer ab 90 78 56 34 12>\n"
}
],
"signatures": [
{
"textRaw": "`new Buffer(array)`",
"name": "Buffer",
"type": "ctor",
"meta": {
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/19524",
"description": "Calling this constructor emits a deprecation warning when run from code outside the `node_modules` directory."
},
{
"version": "v7.2.1",
"pr-url": "https://github.com/nodejs/node/pull/9529",
"description": "Calling this constructor no longer emits a deprecation warning."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/8169",
"description": "Calling this constructor emits a deprecation warning now."
}
],
"deprecated": [
"v6.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use `Buffer.from(array)` instead.",
"params": [
{
"textRaw": "`array` {integer[]} An array of bytes to copy from.",
"name": "array",
"type": "integer[]",
"desc": "An array of bytes to copy from."
}
],
"desc": "See Buffer.from(array).
See\nBuffer.from(arrayBuffer[, byteOffset[, length]]).
See Buffer.from(buffer).
See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the\nconstructor is equivalent to Buffer.alloc().
See Buffer.from(string[, encoding]).
<Blob>A <File> provides information about files.
The name of the File.
The last modified date of the File.
Node.js provides a number of C++ APIs that can be used to execute JavaScript\nin a Node.js environment from other C++ software.
\nThe documentation for these APIs can be found in src/node.h in the Node.js\nsource tree. In addition to the APIs exposed by Node.js, some required concepts\nare provided by the V8 embedder API.
\nBecause using Node.js as an embedded library is different from writing code\nthat is executed by Node.js, breaking changes do not follow typical Node.js\ndeprecation policy and may occur on each semver-major release without prior\nwarning.
", "modules": [ { "textRaw": "Example embedding application", "name": "example_embedding_application", "type": "module", "desc": "The following sections will provide an overview over how to use these APIs\nto create an application from scratch that will perform the equivalent of\nnode -e <code>, i.e. that will take a piece of JavaScript and run it in\na Node.js-specific environment.
The full code can be found in the Node.js source tree.
", "modules": [ { "textRaw": "Setting up a per-process state", "name": "setting_up_a_per-process_state", "type": "module", "desc": "Node.js requires some per-process state management in order to run:
\nv8::Platform instance.The following example shows how these can be set up. Some class names are from\nthe node and v8 C++ namespaces, respectively.
int main(int argc, char** argv) {\n argv = uv_setup_args(argc, argv);\n std::vector<std::string> args(argv, argv + argc);\n // Parse Node.js CLI options, and print any errors that have occurred while\n // trying to parse them.\n std::unique_ptr<node::InitializationResult> result =\n node::InitializeOncePerProcess(args, {\n node::ProcessInitializationFlags::kNoInitializeV8,\n node::ProcessInitializationFlags::kNoInitializeNodeV8Platform\n });\n\n for (const std::string& error : result->errors())\n fprintf(stderr, \"%s: %s\\n\", args[0].c_str(), error.c_str());\n if (result->early_return() != 0) {\n return result->exit_code();\n }\n\n // Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way\n // to create a v8::Platform instance that Node.js can use when creating\n // Worker threads. When no `MultiIsolatePlatform` instance is present,\n // Worker threads are disabled.\n std::unique_ptr<MultiIsolatePlatform> platform =\n MultiIsolatePlatform::Create(4);\n V8::InitializePlatform(platform.get());\n V8::Initialize();\n\n // See below for the contents of this function.\n int ret = RunNodeInstance(\n platform.get(), result->args(), result->exec_args());\n\n V8::Dispose();\n V8::DisposePlatform();\n\n node::TearDownOncePerProcess();\n return ret;\n}\n",
"displayName": "Setting up a per-process state"
},
{
"textRaw": "Setting up a per-instance state",
"name": "setting_up_a_per-instance_state",
"type": "module",
"meta": {
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35597",
"description": "The `CommonEnvironmentSetup` and `SpinEventLoop` utilities were added."
}
]
},
"desc": "Node.js has a concept of a “Node.js instance”, that is commonly being referred\nto as node::Environment. Each node::Environment is associated with:
v8::Isolate, i.e. one JS Engine instance,uv_loop_t, i.e. one event loop,v8::Contexts, but exactly one main v8::Context, andnode::IsolateData instance that contains information that could be\nshared by multiple node::Environments. The embedder should make sure\nthat node::IsolateData is shared only among node::Environments that\nuse the same v8::Isolate, Node.js does not perform this check.In order to set up a v8::Isolate, an v8::ArrayBuffer::Allocator needs\nto be provided. One possible choice is the default Node.js allocator, which\ncan be created through node::ArrayBufferAllocator::Create(). Using the Node.js\nallocator allows minor performance optimizations when addons use the Node.js\nC++ Buffer API, and is required in order to track ArrayBuffer memory in\nprocess.memoryUsage().
Additionally, each v8::Isolate that is used for a Node.js instance needs to\nbe registered and unregistered with the MultiIsolatePlatform instance, if one\nis being used, in order for the platform to know which event loop to use\nfor tasks scheduled by the v8::Isolate.
The node::NewIsolate() helper function creates a v8::Isolate,\nsets it up with some Node.js-specific hooks (e.g. the Node.js error handler),\nand registers it with the platform automatically.
int RunNodeInstance(MultiIsolatePlatform* platform,\n const std::vector<std::string>& args,\n const std::vector<std::string>& exec_args) {\n int exit_code = 0;\n\n // Setup up a libuv event loop, v8::Isolate, and Node.js Environment.\n std::vector<std::string> errors;\n std::unique_ptr<CommonEnvironmentSetup> setup =\n CommonEnvironmentSetup::Create(platform, &errors, args, exec_args);\n if (!setup) {\n for (const std::string& err : errors)\n fprintf(stderr, \"%s: %s\\n\", args[0].c_str(), err.c_str());\n return 1;\n }\n\n Isolate* isolate = setup->isolate();\n Environment* env = setup->env();\n\n {\n Locker locker(isolate);\n Isolate::Scope isolate_scope(isolate);\n HandleScope handle_scope(isolate);\n // The v8::Context needs to be entered when node::CreateEnvironment() and\n // node::LoadEnvironment() are being called.\n Context::Scope context_scope(setup->context());\n\n // Set up the Node.js instance for execution, and run code inside of it.\n // There is also a variant that takes a callback and provides it with\n // the `require` and `process` objects, so that it can manually compile\n // and run scripts as needed.\n // The `require` function inside this script does *not* access the file\n // system, and can only load built-in Node.js modules.\n // `module.createRequire()` is being used to create one that is able to\n // load files from the disk, and uses the standard CommonJS file loader\n // instead of the internal-only `require` function.\n MaybeLocal<Value> loadenv_ret = node::LoadEnvironment(\n env,\n \"const publicRequire =\"\n \" require('node:module').createRequire(process.cwd() + '/');\"\n \"globalThis.require = publicRequire;\"\n \"require('node:vm').runInThisContext(process.argv[1]);\");\n\n if (loadenv_ret.IsEmpty()) // There has been a JS exception.\n return 1;\n\n exit_code = node::SpinEventLoop(env).FromMaybe(1);\n\n // node::Stop() can be used to explicitly stop the event loop and keep\n // further JavaScript from running. It can be called from any thread,\n // and will act like worker.terminate() if called from another thread.\n node::Stop(env);\n }\n\n return exit_code;\n}\n",
"displayName": "Setting up a per-instance state"
}
],
"displayName": "Example embedding application"
}
],
"displayName": "C++ embedder API",
"source": "doc/api/embedding.md"
},
{
"textRaw": "Child process",
"name": "child_process",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:child_process module provides the ability to spawn subprocesses in\na manner that is similar, but not identical, to popen(3). This capability\nis primarily provided by the child_process.spawn() function:
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n\nimport { spawn } from 'node:child_process';\nimport { once } from 'node:events';\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nconst [code] = await once(ls, 'close');\nconsole.log(`child process exited with code ${code}`);\n\nBy default, pipes for stdin, stdout, and stderr are established between\nthe parent Node.js process and the spawned subprocess. These pipes have\nlimited (and platform-specific) capacity. If the subprocess writes to\nstdout in excess of that limit without the output being captured, the\nsubprocess blocks, waiting for the pipe buffer to accept more data. This is\nidentical to the behavior of pipes in the shell. Use the { stdio: 'ignore' }\noption if the output will not be consumed.
The command lookup is performed using the options.env.PATH environment\nvariable if env is in the options object. Otherwise, process.env.PATH is\nused. If options.env is set without PATH, lookup on Unix is performed\non a default search path search of /usr/bin:/bin (see your operating system's\nmanual for execvpe/execvp), on Windows the current processes environment\nvariable PATH is used.
On Windows, environment variables are case-insensitive. Node.js\nlexicographically sorts the env keys and uses the first one that\ncase-insensitively matches. Only first (in lexicographic order) entry will be\npassed to the subprocess. This might lead to issues on Windows when passing\nobjects to the env option that have multiple variants of the same key, such as\nPATH and Path.
The child_process.spawn() method spawns the child process asynchronously,\nwithout blocking the Node.js event loop. The child_process.spawnSync()\nfunction provides equivalent functionality in a synchronous manner that blocks\nthe event loop until the spawned process either exits or is terminated.
For convenience, the node:child_process module provides a handful of\nsynchronous and asynchronous alternatives to child_process.spawn() and\nchild_process.spawnSync(). Each of these alternatives are implemented on\ntop of child_process.spawn() or child_process.spawnSync().
child_process.exec(): spawns a shell and runs a command within that\nshell, passing the stdout and stderr to a callback function when\ncomplete.child_process.execFile(): similar to child_process.exec() except\nthat it spawns the command directly without first spawning a shell by\ndefault.child_process.fork(): spawns a new Node.js process and invokes a\nspecified module with an IPC communication channel established that allows\nsending messages between parent and child.child_process.execSync(): a synchronous version of\nchild_process.exec() that will block the Node.js event loop.child_process.execFileSync(): a synchronous version of\nchild_process.execFile() that will block the Node.js event loop.For certain use cases, such as automating shell scripts, the\nsynchronous counterparts may be more convenient. In many cases, however,\nthe synchronous methods can have significant impact on performance due to\nstalling the event loop while spawned processes complete.
", "modules": [ { "textRaw": "Asynchronous process creation", "name": "asynchronous_process_creation", "type": "module", "desc": "The child_process.spawn(), child_process.fork(), child_process.exec(),\nand child_process.execFile() methods all follow the idiomatic asynchronous\nprogramming pattern typical of other Node.js APIs.
Each of the methods returns a ChildProcess instance. These objects\nimplement the Node.js EventEmitter API, allowing the parent process to\nregister listener functions that are called when certain events occur during\nthe life cycle of the child process.
The child_process.exec() and child_process.execFile() methods\nadditionally allow for an optional callback function to be specified that is\ninvoked when the child process terminates.
The importance of the distinction between child_process.exec() and\nchild_process.execFile() can vary based on platform. On Unix-type\noperating systems (Unix, Linux, macOS) child_process.execFile() can be\nmore efficient because it does not spawn a shell by default. On Windows,\nhowever, .bat and .cmd files are not executable on their own without a\nterminal, and therefore cannot be launched using child_process.execFile().\nWhen running on Windows, .bat and .cmd files can be invoked by:
child_process.spawn() with the shell option set, orchild_process.exec(), orcmd.exe and passing the .bat or .cmd file as an argument\n(which is what the shell option and child_process.exec() do).In any case, if the script filename contains spaces, it needs to be quoted.
\nconst { exec, spawn } = require('node:child_process');\n\n// 1. child_process.spawn() with the shell option set\nconst myBat = spawn('my.bat', { shell: true });\n\n// 2. child_process.exec()\nexec('my.bat', (err, stdout, stderr) => { /* ... */ });\n\n// 3. spawning cmd.exe and passing the .bat or .cmd file as an argument\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\n// If the script filename contains spaces, it needs to be quoted\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => { /* ... */ });\n\nimport { exec, spawn } from 'node:child_process';\n\n// 1. child_process.spawn() with the shell option set\nconst myBat = spawn('my.bat', { shell: true });\n\n// 2. child_process.exec()\nexec('my.bat', (err, stdout, stderr) => { /* ... */ });\n\n// 3. spawning cmd.exe and passing the .bat or .cmd file as an argument\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\n// If the script filename contains spaces, it needs to be quoted\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => { /* ... */ });\n",
"displayName": "Spawning `.bat` and `.cmd` files on Windows"
}
],
"methods": [
{
"textRaw": "`child_process.exec(command[, options][, callback])`",
"name": "exec",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": "v15.4.0",
"pr-url": "https://github.com/nodejs/node/pull/36308",
"description": "AbortSignal support was added."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`command` {string} The command to run, with space-separated arguments.",
"name": "command",
"type": "string",
"desc": "The command to run, with space-separated arguments."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process. **Default:** `process.cwd()`.",
"name": "cwd",
"type": "string|URL",
"default": "`process.cwd()`",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
},
{
"textRaw": "`shell` {string} Shell to execute the command with. See Shell requirements and Default Windows shell. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.",
"name": "shell",
"type": "string",
"default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows",
"desc": "Shell to execute the command with. See Shell requirements and Default Windows shell."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
},
{
"textRaw": "`timeout` {number} **Default:** `0`",
"name": "timeout",
"type": "number",
"default": "`0`"
},
{
"textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode. **Default:** `1024 * 1024`.",
"name": "maxBuffer",
"type": "number",
"default": "`1024 * 1024`",
"desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode."
},
{
"textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`"
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see `setuid(2)`)."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see `setgid(2)`)."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function} called with the output when process terminates.",
"name": "callback",
"type": "Function",
"desc": "called with the output when process terminates.",
"options": [
{
"textRaw": "`error` {Error}",
"name": "error",
"type": "Error"
},
{
"textRaw": "`stdout` {string|Buffer}",
"name": "stdout",
"type": "string|Buffer"
},
{
"textRaw": "`stderr` {string|Buffer}",
"name": "stderr",
"type": "string|Buffer"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
}
}
],
"desc": "Spawns a shell then executes the command within that shell, buffering any\ngenerated output. The command string passed to the exec function is processed\ndirectly by the shell and special characters (vary based on\nshell)\nneed to be dealt with accordingly:
const { exec } = require('node:child_process');\n\nexec('\"/path/to/test file/test.sh\" arg1 arg2');\n// Double quotes are used so that the space in the path is not interpreted as\n// a delimiter of multiple arguments.\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n// The $HOME variable is escaped in the first instance, but not in the second.\n\nimport { exec } from 'node:child_process';\n\nexec('\"/path/to/test file/test.sh\" arg1 arg2');\n// Double quotes are used so that the space in the path is not interpreted as\n// a delimiter of multiple arguments.\n\nexec('echo \"The \\\\$HOME variable is $HOME\"');\n// The $HOME variable is escaped in the first instance, but not in the second.\n\nNever pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.
\nIf a callback function is provided, it is called with the arguments\n(error, stdout, stderr). On success, error will be null. On error,\nerror will be an instance of Error. The error.code property will be\nthe exit code of the process. By convention, any exit code other than 0\nindicates an error. error.signal will be the signal that terminated the\nprocess.
The stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.
const { exec } = require('node:child_process');\nexec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {\n if (error) {\n console.error(`exec error: ${error}`);\n return;\n }\n console.log(`stdout: ${stdout}`);\n console.error(`stderr: ${stderr}`);\n});\n\nimport { exec } from 'node:child_process';\nexec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {\n if (error) {\n console.error(`exec error: ${error}`);\n return;\n }\n console.log(`stdout: ${stdout}`);\n console.error(`stderr: ${stderr}`);\n});\n\nIf timeout is greater than 0, the parent process will send the signal\nidentified by the killSignal property (the default is 'SIGTERM') if the\nchild process runs longer than timeout milliseconds.
Unlike the exec(3) POSIX system call, child_process.exec() does not replace\nthe existing process and uses a shell to execute the command.
If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.
const util = require('node:util');\nconst exec = util.promisify(require('node:child_process').exec);\n\nasync function lsExample() {\n const { stdout, stderr } = await exec('ls');\n console.log('stdout:', stdout);\n console.error('stderr:', stderr);\n}\nlsExample();\n\nimport { promisify } from 'node:util';\nimport child_process from 'node:child_process';\nconst exec = promisify(child_process.exec);\n\nasync function lsExample() {\n const { stdout, stderr } = await exec('ls');\n console.log('stdout:', stdout);\n console.error('stderr:', stderr);\n}\nlsExample();\n\nIf the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .kill() on the child process except\nthe error passed to the callback will be an AbortError:
const { exec } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = exec('grep ssh', { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n\nimport { exec } from 'node:child_process';\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = exec('grep ssh', { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n"
},
{
"textRaw": "`child_process.execFile(file[, args][, options][, callback])`",
"name": "execFile",
"type": "method",
"meta": {
"added": [
"v0.1.91"
],
"changes": [
{
"version": [
"v23.11.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57389",
"description": "Passing `args` when `shell` is set to `true` is deprecated."
},
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.4.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36308",
"description": "AbortSignal support was added."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`file` {string} The name or path of the executable file to run.",
"name": "file",
"type": "string",
"desc": "The name or path of the executable file to run."
},
{
"textRaw": "`args` {string[]} List of string arguments.",
"name": "args",
"type": "string[]",
"desc": "List of string arguments.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
},
{
"textRaw": "`timeout` {number} **Default:** `0`",
"name": "timeout",
"type": "number",
"default": "`0`"
},
{
"textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode. **Default:** `1024 * 1024`.",
"name": "maxBuffer",
"type": "number",
"default": "`1024 * 1024`",
"desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode."
},
{
"textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'`",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`"
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see `setuid(2)`)."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see `setgid(2)`)."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix."
},
{
"textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. **Default:** `false` (no shell).",
"name": "shell",
"type": "boolean|string",
"default": "`false` (no shell)",
"desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function} Called with the output when process terminates.",
"name": "callback",
"type": "Function",
"desc": "Called with the output when process terminates.",
"options": [
{
"textRaw": "`error` {Error}",
"name": "error",
"type": "Error"
},
{
"textRaw": "`stdout` {string|Buffer}",
"name": "stdout",
"type": "string|Buffer"
},
{
"textRaw": "`stderr` {string|Buffer}",
"name": "stderr",
"type": "string|Buffer"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
}
}
],
"desc": "The child_process.execFile() function is similar to child_process.exec()\nexcept that it does not spawn a shell by default. Rather, the specified\nexecutable file is spawned directly as a new process making it slightly more\nefficient than child_process.exec().
The same options as child_process.exec() are supported. Since a shell is\nnot spawned, behaviors such as I/O redirection and file globbing are not\nsupported.
const { execFile } = require('node:child_process');\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n if (error) {\n throw error;\n }\n console.log(stdout);\n});\n\nimport { execFile } from 'node:child_process';\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n if (error) {\n throw error;\n }\n console.log(stdout);\n});\n\nThe stdout and stderr arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding is 'buffer', or an unrecognized character\nencoding, Buffer objects will be passed to the callback instead.
If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with stdout and stderr properties. The returned\nChildProcess instance is attached to the Promise as a child property. In\ncase of an error (including any error resulting in an exit code other than 0), a\nrejected promise is returned, with the same error object given in the\ncallback, but with two additional properties stdout and stderr.
const util = require('node:util');\nconst execFile = util.promisify(require('node:child_process').execFile);\nasync function getVersion() {\n const { stdout } = await execFile('node', ['--version']);\n console.log(stdout);\n}\ngetVersion();\n\nimport { promisify } from 'node:util';\nimport child_process from 'node:child_process';\nconst execFile = promisify(child_process.execFile);\nasync function getVersion() {\n const { stdout } = await execFile('node', ['--version']);\n console.log(stdout);\n}\ngetVersion();\n\nIf the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .kill() on the child process except\nthe error passed to the callback will be an AbortError:
const { execFile } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = execFile('node', ['--version'], { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n\nimport { execFile } from 'node:child_process';\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = execFile('node', ['--version'], { signal }, (error) => {\n console.error(error); // an AbortError\n});\ncontroller.abort();\n"
},
{
"textRaw": "`child_process.fork(modulePath[, args][, options])`",
"name": "fork",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": [
{
"version": [
"v17.4.0",
"v16.14.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41225",
"description": "The `modulePath` parameter can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.13.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37256",
"description": "timeout was added."
},
{
"version": [
"v15.11.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37325",
"description": "killSignal for AbortSignal was added."
},
{
"version": [
"v15.6.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36603",
"description": "AbortSignal support was added."
},
{
"version": [
"v13.2.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30162",
"description": "The `serialization` option is supported now."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10866",
"description": "The `stdio` option can now be a string."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7811",
"description": "The `stdio` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`modulePath` {string|URL} The module to run in the child.",
"name": "modulePath",
"type": "string|URL",
"desc": "The module to run in the child."
},
{
"textRaw": "`args` {string[]} List of string arguments.",
"name": "args",
"type": "string[]",
"desc": "List of string arguments.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`detached` {boolean} Prepare child process to run independently of its parent process. Specific behavior depends on the platform (see `options.detached`).",
"name": "detached",
"type": "boolean",
"desc": "Prepare child process to run independently of its parent process. Specific behavior depends on the platform (see `options.detached`)."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`execPath` {string} Executable used to create the child process.",
"name": "execPath",
"type": "string",
"desc": "Executable used to create the child process."
},
{
"textRaw": "`execArgv` {string[]} List of string arguments passed to the executable. **Default:** `process.execArgv`.",
"name": "execArgv",
"type": "string[]",
"default": "`process.execArgv`",
"desc": "List of string arguments passed to the executable."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see `setgid(2)`)."
},
{
"textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for more details. **Default:** `'json'`.",
"name": "serialization",
"type": "string",
"default": "`'json'`",
"desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for more details."
},
{
"textRaw": "`signal` {AbortSignal} Allows closing the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "Allows closing the child process using an AbortSignal."
},
{
"textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`",
"desc": "The signal value to be used when the spawned process will be killed by timeout or abort signal."
},
{
"textRaw": "`silent` {boolean} If `true`, stdin, stdout, and stderr of the child process will be piped to the parent process, otherwise they will be inherited from the parent process, see the `'pipe'` and `'inherit'` options for `child_process.spawn()`'s `stdio` for more details. **Default:** `false`.",
"name": "silent",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, stdin, stdout, and stderr of the child process will be piped to the parent process, otherwise they will be inherited from the parent process, see the `'pipe'` and `'inherit'` options for `child_process.spawn()`'s `stdio` for more details."
},
{
"textRaw": "`stdio` {Array|string} See `child_process.spawn()`'s `stdio`. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`.",
"name": "stdio",
"type": "Array|string",
"desc": "See `child_process.spawn()`'s `stdio`. When this option is provided, it overrides `silent`. If the array variant is used, it must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see `setuid(2)`)."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix."
},
{
"textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.",
"name": "timeout",
"type": "number",
"default": "`undefined`",
"desc": "In milliseconds the maximum amount of time the process is allowed to run."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
}
}
],
"desc": "The child_process.fork() method is a special case of\nchild_process.spawn() used specifically to spawn new Node.js processes.\nLike child_process.spawn(), a ChildProcess object is returned. The\nreturned ChildProcess will have an additional communication channel\nbuilt-in that allows messages to be passed back and forth between the parent and\nchild. See subprocess.send() for details.
Keep in mind that spawned Node.js child processes are\nindependent of the parent with exception of the IPC communication channel\nthat is established between the two. Each process has its own memory, with\ntheir own V8 instances. Because of the additional resource allocations\nrequired, spawning a large number of child Node.js processes is not\nrecommended.
\nBy default, child_process.fork() will spawn new Node.js instances using the\nprocess.execPath of the parent process. The execPath property in the\noptions object allows for an alternative execution path to be used.
Node.js processes launched with a custom execPath will communicate with the\nparent process using the file descriptor (fd) identified using the\nenvironment variable NODE_CHANNEL_FD on the child process.
Unlike the fork(2) POSIX system call, child_process.fork() does not clone the\ncurrent process.
The shell option available in child_process.spawn() is not supported by\nchild_process.fork() and will be ignored if set.
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .kill() on the child process except\nthe error passed to the callback will be an AbortError:
const { fork } = require('node:child_process');\nconst process = require('node:process');\n\nif (process.argv[2] === 'child') {\n setTimeout(() => {\n console.log(`Hello from ${process.argv[2]}!`);\n }, 1_000);\n} else {\n const controller = new AbortController();\n const { signal } = controller;\n const child = fork(__filename, ['child'], { signal });\n child.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n });\n controller.abort(); // Stops the child process\n}\n\nimport { fork } from 'node:child_process';\nimport process from 'node:process';\n\nif (process.argv[2] === 'child') {\n setTimeout(() => {\n console.log(`Hello from ${process.argv[2]}!`);\n }, 1_000);\n} else {\n const controller = new AbortController();\n const { signal } = controller;\n const child = fork(import.meta.url, ['child'], { signal });\n child.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n });\n controller.abort(); // Stops the child process\n}\n"
},
{
"textRaw": "`child_process.spawn(command[, args][, options])`",
"name": "spawn",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": [
"v23.11.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57389",
"description": "Passing `args` when `shell` is set to `true` is deprecated."
},
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": [
"v15.13.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37256",
"description": "timeout was added."
},
{
"version": [
"v15.11.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/37325",
"description": "killSignal for AbortSignal was added."
},
{
"version": [
"v15.5.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36432",
"description": "AbortSignal support was added."
},
{
"version": [
"v13.2.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30162",
"description": "The `serialization` option is supported now."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
},
{
"version": "v6.4.0",
"pr-url": "https://github.com/nodejs/node/pull/7696",
"description": "The `argv0` option is supported now."
},
{
"version": "v5.7.0",
"pr-url": "https://github.com/nodejs/node/pull/4598",
"description": "The `shell` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`command` {string} The command to run.",
"name": "command",
"type": "string",
"desc": "The command to run."
},
{
"textRaw": "`args` {string[]} List of string arguments.",
"name": "args",
"type": "string[]",
"desc": "List of string arguments.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.",
"name": "argv0",
"type": "string",
"desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified."
},
{
"textRaw": "`stdio` {Array|string} Child's stdio configuration (see `options.stdio`).",
"name": "stdio",
"type": "Array|string",
"desc": "Child's stdio configuration (see `options.stdio`)."
},
{
"textRaw": "`detached` {boolean} Prepare child process to run independently of its parent process. Specific behavior depends on the platform (see `options.detached`).",
"name": "detached",
"type": "boolean",
"desc": "Prepare child process to run independently of its parent process. Specific behavior depends on the platform (see `options.detached`)."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process (see `setuid(2)`)."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process (see `setgid(2)`)."
},
{
"textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for more details. **Default:** `'json'`.",
"name": "serialization",
"type": "string",
"default": "`'json'`",
"desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for more details."
},
{
"textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. **Default:** `false` (no shell).",
"name": "shell",
"type": "boolean|string",
"default": "`false` (no shell)",
"desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell."
},
{
"textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.",
"name": "windowsVerbatimArguments",
"type": "boolean",
"default": "`false`",
"desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting the child process using an AbortSignal.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting the child process using an AbortSignal."
},
{
"textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.",
"name": "timeout",
"type": "number",
"default": "`undefined`",
"desc": "In milliseconds the maximum amount of time the process is allowed to run."
},
{
"textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`",
"desc": "The signal value to be used when the spawned process will be killed by timeout or abort signal."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {ChildProcess}",
"name": "return",
"type": "ChildProcess"
}
}
],
"desc": "The child_process.spawn() method spawns a new process using the given\ncommand, with command-line arguments in args. If omitted, args defaults\nto an empty array.
If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
A third argument may be used to specify additional options, with these defaults:
\nconst defaults = {\n cwd: undefined,\n env: process.env,\n};\n\nUse cwd to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory. If given,\nbut the path does not exist, the child process emits an ENOENT error\nand exits immediately. ENOENT is also emitted when the command\ndoes not exist.
Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.
undefined values in env will be ignored.
Example of running ls -lh /usr, capturing stdout, stderr, and the\nexit code:
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n\nimport { spawn } from 'node:child_process';\nimport { once } from 'node:events';\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.stderr.on('data', (data) => {\n console.error(`stderr: ${data}`);\n});\n\nconst [code] = await once(ls, 'close');\nconsole.log(`child process exited with code ${code}`);\n\nExample: A very elaborate way to run ps ax | grep ssh
const { spawn } = require('node:child_process');\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n console.error(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n if (code !== 0) {\n console.log(`ps process exited with code ${code}`);\n }\n grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n console.error(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n if (code !== 0) {\n console.log(`grep process exited with code ${code}`);\n }\n});\n\nimport { spawn } from 'node:child_process';\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n console.error(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n if (code !== 0) {\n console.log(`ps process exited with code ${code}`);\n }\n grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n console.error(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n if (code !== 0) {\n console.log(`grep process exited with code ${code}`);\n }\n});\n\nExample of checking for failed spawn:
const { spawn } = require('node:child_process');\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n console.error('Failed to start subprocess.');\n});\n\nimport { spawn } from 'node:child_process';\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n console.error('Failed to start subprocess.');\n});\n\nCertain platforms (macOS, Linux) will use the value of argv[0] for the process\ntitle while others (Windows, SunOS) will use command.
Node.js overwrites argv[0] with process.execPath on startup, so\nprocess.argv[0] in a Node.js child process will not match the argv0\nparameter passed to spawn from the parent. Retrieve it with the\nprocess.argv0 property instead.
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .kill() on the child process except\nthe error passed to the callback will be an AbortError:
const { spawn } = require('node:child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst grep = spawn('grep', ['ssh'], { signal });\ngrep.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n});\ncontroller.abort(); // Stops the child process\n\nimport { spawn } from 'node:child_process';\nconst controller = new AbortController();\nconst { signal } = controller;\nconst grep = spawn('grep', ['ssh'], { signal });\ngrep.on('error', (err) => {\n // This will be called with err being an AbortError if the controller aborts\n});\ncontroller.abort(); // Stops the child process\n",
"properties": [
{
"textRaw": "`options.detached`",
"name": "detached",
"type": "property",
"meta": {
"added": [
"v0.7.10"
],
"changes": []
},
"desc": "On Windows, setting options.detached to true makes it possible for the\nchild process to continue running after the parent exits. The child process\nwill have its own console window. Once enabled for a child process,\nit cannot be disabled.
On non-Windows platforms, if options.detached is set to true, the child\nprocess will be made the leader of a new process group and session. Child\nprocesses may continue running after the parent exits regardless of whether\nthey are detached or not. See setsid(2) for more information.
By default, the parent will wait for the detached child process to exit.\nTo prevent the parent process from waiting for a given subprocess to exit, use\nthe subprocess.unref() method. Doing so will cause the parent process' event\nloop to not include the child process in its reference count, allowing the\nparent process to exit independently of the child process, unless there is an established\nIPC channel between the child and the parent processes.
When using the detached option to start a long-running process, the process\nwill not stay running in the background after the parent exits unless it is\nprovided with a stdio configuration that is not connected to the parent.\nIf the parent process' stdio is inherited, the child process will remain attached\nto the controlling terminal.
Example of a long-running process, by detaching and also ignoring its parent\nstdio file descriptors, in order to ignore the parent's termination:
const { spawn } = require('node:child_process');\nconst process = require('node:process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n\nimport { spawn } from 'node:child_process';\nimport process from 'node:process';\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n\nAlternatively one can redirect the child process' output into files:
\nconst { openSync } = require('node:fs');\nconst { spawn } = require('node:child_process');\nconst out = openSync('./out.log', 'a');\nconst err = openSync('./out.log', 'a');\n\nconst subprocess = spawn('prg', [], {\n detached: true,\n stdio: [ 'ignore', out, err ],\n});\n\nsubprocess.unref();\n\nimport { openSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nconst out = openSync('./out.log', 'a');\nconst err = openSync('./out.log', 'a');\n\nconst subprocess = spawn('prg', [], {\n detached: true,\n stdio: [ 'ignore', out, err ],\n});\n\nsubprocess.unref();\n"
},
{
"textRaw": "`options.stdio`",
"name": "stdio",
"type": "property",
"meta": {
"added": [
"v0.7.10"
],
"changes": [
{
"version": [
"v15.6.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/29412",
"description": "Added the `overlapped` stdio flag."
},
{
"version": "v3.3.1",
"pr-url": "https://github.com/nodejs/node/pull/2727",
"description": "The value `0` is now accepted as a file descriptor."
}
]
},
"desc": "The options.stdio option is used to configure the pipes that are established\nbetween the parent and child process. By default, the child's stdin, stdout,\nand stderr are redirected to corresponding subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr streams on the\nChildProcess object. This is equivalent to setting the options.stdio\nequal to ['pipe', 'pipe', 'pipe'].
For convenience, options.stdio may be one of the following strings:
'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)'overlapped': equivalent to ['overlapped', 'overlapped', 'overlapped']'ignore': equivalent to ['ignore', 'ignore', 'ignore']'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]Otherwise, the value of options.stdio is an array where each index corresponds\nto an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,\nand stderr, respectively. Additional fds can be specified to create additional\npipes between the parent and child. The value is one of the following:
'pipe': Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as subprocess.stdio[fd]. Pipes\ncreated for fds 0, 1, and 2 are also available as subprocess.stdin,\nsubprocess.stdout and subprocess.stderr, respectively.\nThese are not actual Unix pipes and therefore the child process\ncan not use them by their descriptor files,\ne.g. /dev/fd/2 or /dev/stdout.
'overlapped': Same as 'pipe' except that the FILE_FLAG_OVERLAPPED flag\nis set on the handle. This is necessary for overlapped I/O on the child\nprocess's stdio handles. See the\ndocs\nfor more details. This is exactly the same as 'pipe' on non-Windows\nsystems.
'ipc': Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC\nstdio file descriptor. Setting this option enables the\nsubprocess.send() method. If the child process is a Node.js instance,\nthe presence of an IPC channel will enable process.send() and\nprocess.disconnect() methods, as well as 'disconnect' and\n'message' events within the child process.
Accessing the IPC channel fd in any way other than process.send()\nor using the IPC channel with a child process that is not a Node.js instance\nis not supported.
'ignore': Instructs Node.js to ignore the fd in the child. While Node.js\nwill always open fds 0, 1, and 2 for the processes it spawns, setting the fd\nto 'ignore' will cause Node.js to open /dev/null and attach it to the\nchild's fd.
'inherit': Pass through the corresponding stdio stream to/from the\nparent process. In the first three positions, this is equivalent to\nprocess.stdin, process.stdout, and process.stderr, respectively. In\nany other position, equivalent to 'ignore'.
<Stream> object: Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that\ncorresponds to the index in the stdio array. The stream must have an\nunderlying descriptor (file streams do not start until the 'open' event has\noccurred).\nNOTE: While it is technically possible to pass stdin as a writable or\nstdout/stderr as readable, it is not recommended.\nReadable and writable streams are designed with distinct behaviors, and using\nthem incorrectly (e.g., passing a readable stream where a writable stream is\nexpected) can lead to unexpected results or errors. This practice is discouraged\nas it may result in undefined behavior or dropped callbacks if the stream\nencounters errors. Always ensure that stdin is used as readable and\nstdout/stderr as writable to maintain the intended flow of data between\nthe parent and child processes.
Positive integer: The integer value is interpreted as a file descriptor\nthat is open in the parent process. It is shared with the child\nprocess, similar to how <Stream> objects can be shared. Passing sockets\nis not supported on Windows.
null, undefined: Use default value. For stdio fds 0, 1, and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
const { spawn } = require('node:child_process');\nconst process = require('node:process');\n\n// Child will use parent's stdios.\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr.\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs presenting a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });\n\nimport { spawn } from 'node:child_process';\nimport process from 'node:process';\n\n// Child will use parent's stdios.\nspawn('prg', [], { stdio: 'inherit' });\n\n// Spawn child sharing only stderr.\nspawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });\n\n// Open an extra fd=4, to interact with programs presenting a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });\n\nIt is worth noting that when an IPC channel is established between the\nparent and child processes, and the child process is a Node.js instance,\nthe child process is launched with the IPC channel unreferenced (using\nunref()) until the child process registers an event handler for the\n'disconnect' event or the 'message' event. This allows the\nchild process to exit normally without the process being held open by the\nopen IPC channel.\nSee also: child_process.exec() and child_process.fork().
The child_process.spawnSync(), child_process.execSync(), and\nchild_process.execFileSync() methods are synchronous and will block the\nNode.js event loop, pausing execution of any additional code until the spawned\nprocess exits.
Blocking calls like these are mostly useful for simplifying general-purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.
", "methods": [ { "textRaw": "`child_process.execFileSync(file[, args][, options])`", "name": "execFileSync", "type": "method", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": [ "v16.4.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38862", "description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22409", "description": "The `input` option can now be any `TypedArray` or a `DataView`." }, { "version": "v8.8.0", "pr-url": "https://github.com/nodejs/node/pull/15380", "description": "The `windowsHide` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10653", "description": "The `input` option can now be a `Uint8Array`." }, { "version": [ "v6.2.1", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6939", "description": "The `encoding` option can now explicitly be set to `buffer`." } ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string} The name or path of the executable file to run.", "name": "file", "type": "string", "desc": "The name or path of the executable file to run." }, { "textRaw": "`args` {string[]} List of string arguments.", "name": "args", "type": "string[]", "desc": "List of string arguments.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cwd` {string|URL} Current working directory of the child process.", "name": "cwd", "type": "string|URL", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`.", "name": "input", "type": "string|Buffer|TypedArray|DataView", "desc": "The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. See `child_process.spawn()`'s `stdio`. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.", "name": "stdio", "type": "string|Array", "default": "`'pipe'`", "desc": "Child's stdio configuration. See `child_process.spawn()`'s `stdio`. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified." }, { "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "Environment key-value pairs." }, { "textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).", "name": "uid", "type": "number", "desc": "Sets the user identity of the process (see `setuid(2)`)." }, { "textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).", "name": "gid", "type": "number", "desc": "Sets the group identity of the process (see `setgid(2)`)." }, { "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", "name": "timeout", "type": "number", "default": "`undefined`", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", "name": "killSignal", "type": "string|integer", "default": "`'SIGTERM'`", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at `maxBuffer` and Unicode. **Default:** `1024 * 1024`.", "name": "maxBuffer", "type": "number", "default": "`1024 * 1024`", "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at `maxBuffer` and Unicode." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", "name": "encoding", "type": "string", "default": "`'buffer'`", "desc": "The encoding used for all stdio inputs and outputs." }, { "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the subprocess console window that would normally be created on Windows systems." }, { "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. **Default:** `false` (no shell).", "name": "shell", "type": "boolean|string", "default": "`false` (no shell)", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell." } ], "optional": true } ], "return": { "textRaw": "Returns: {Buffer|string} The stdout from the command.", "name": "return", "type": "Buffer|string", "desc": "The stdout from the command." } } ], "desc": "The child_process.execFileSync() method is generally identical to\nchild_process.execFile() with the exception that the method will not\nreturn until the child process has fully closed. When a timeout has been\nencountered and killSignal is sent, the method won't return until the process\nhas completely exited.
If the child process intercepts and handles the SIGTERM signal and\ndoes not exit, the parent process will still wait until the child process has\nexited.
If the process times out or has a non-zero exit code, this method will throw an\nError that will include the full result of the underlying\nchild_process.spawnSync().
If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
const { execFileSync } = require('node:child_process');\n\ntry {\n const stdout = execFileSync('my-script.sh', ['my-arg'], {\n // Capture stdout and stderr from child process. Overrides the\n // default behavior of streaming child stderr to the parent stderr\n stdio: 'pipe',\n\n // Use utf8 encoding for stdio pipes\n encoding: 'utf8',\n });\n\n console.log(stdout);\n} catch (err) {\n if (err.code) {\n // Spawning child process failed\n console.error(err.code);\n } else {\n // Child was spawned but exited with non-zero exit code\n // Error contains any stdout and stderr from the child\n const { stdout, stderr } = err;\n\n console.error({ stdout, stderr });\n }\n}\n\nimport { execFileSync } from 'node:child_process';\n\ntry {\n const stdout = execFileSync('my-script.sh', ['my-arg'], {\n // Capture stdout and stderr from child process. Overrides the\n // default behavior of streaming child stderr to the parent stderr\n stdio: 'pipe',\n\n // Use utf8 encoding for stdio pipes\n encoding: 'utf8',\n });\n\n console.log(stdout);\n} catch (err) {\n if (err.code) {\n // Spawning child process failed\n console.error(err.code);\n } else {\n // Child was spawned but exited with non-zero exit code\n // Error contains any stdout and stderr from the child\n const { stdout, stderr } = err;\n\n console.error({ stdout, stderr });\n }\n}\n"
},
{
"textRaw": "`child_process.execSync(command[, options])`",
"name": "execSync",
"type": "method",
"meta": {
"added": [
"v0.11.12"
],
"changes": [
{
"version": [
"v16.4.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/38862",
"description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": "v10.10.0",
"pr-url": "https://github.com/nodejs/node/pull/22409",
"description": "The `input` option can now be any `TypedArray` or a `DataView`."
},
{
"version": "v8.8.0",
"pr-url": "https://github.com/nodejs/node/pull/15380",
"description": "The `windowsHide` option is supported now."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/10653",
"description": "The `input` option can now be a `Uint8Array`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`command` {string} The command to run.",
"name": "command",
"type": "string",
"desc": "The command to run."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cwd` {string|URL} Current working directory of the child process.",
"name": "cwd",
"type": "string|URL",
"desc": "Current working directory of the child process."
},
{
"textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`.",
"name": "input",
"type": "string|Buffer|TypedArray|DataView",
"desc": "The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`."
},
{
"textRaw": "`stdio` {string|Array} Child's stdio configuration. See `child_process.spawn()`'s `stdio`. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified. **Default:** `'pipe'`.",
"name": "stdio",
"type": "string|Array",
"default": "`'pipe'`",
"desc": "Child's stdio configuration. See `child_process.spawn()`'s `stdio`. `stderr` by default will be output to the parent process' stderr unless `stdio` is specified."
},
{
"textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.",
"name": "env",
"type": "Object",
"default": "`process.env`",
"desc": "Environment key-value pairs."
},
{
"textRaw": "`shell` {string} Shell to execute the command with. See Shell requirements and Default Windows shell. **Default:** `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.",
"name": "shell",
"type": "string",
"default": "`'/bin/sh'` on Unix, `process.env.ComSpec` on Windows",
"desc": "Shell to execute the command with. See Shell requirements and Default Windows shell."
},
{
"textRaw": "`uid` {number} Sets the user identity of the process. (See `setuid(2)`).",
"name": "uid",
"type": "number",
"desc": "Sets the user identity of the process. (See `setuid(2)`)."
},
{
"textRaw": "`gid` {number} Sets the group identity of the process. (See `setgid(2)`).",
"name": "gid",
"type": "number",
"desc": "Sets the group identity of the process. (See `setgid(2)`)."
},
{
"textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.",
"name": "timeout",
"type": "number",
"default": "`undefined`",
"desc": "In milliseconds the maximum amount of time the process is allowed to run."
},
{
"textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.",
"name": "killSignal",
"type": "string|integer",
"default": "`'SIGTERM'`",
"desc": "The signal value to be used when the spawned process will be killed."
},
{
"textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode. **Default:** `1024 * 1024`.",
"name": "maxBuffer",
"type": "number",
"default": "`1024 * 1024`",
"desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode."
},
{
"textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.",
"name": "encoding",
"type": "string",
"default": "`'buffer'`",
"desc": "The encoding used for all stdio inputs and outputs."
},
{
"textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.",
"name": "windowsHide",
"type": "boolean",
"default": "`false`",
"desc": "Hide the subprocess console window that would normally be created on Windows systems."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string} The stdout from the command.",
"name": "return",
"type": "Buffer|string",
"desc": "The stdout from the command."
}
}
],
"desc": "The child_process.execSync() method is generally identical to\nchild_process.exec() with the exception that the method will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the child process intercepts and handles the SIGTERM\nsignal and doesn't exit, the parent process will wait until the child process\nhas exited.
If the process times out or has a non-zero exit code, this method will throw.\nThe Error object will contain the entire result from\nchild_process.spawnSync().
Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.
" }, { "textRaw": "`child_process.spawnSync(command[, args][, options])`", "name": "spawnSync", "type": "method", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": [ "v16.4.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/38862", "description": "The `cwd` option can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22409", "description": "The `input` option can now be any `TypedArray` or a `DataView`." }, { "version": "v8.8.0", "pr-url": "https://github.com/nodejs/node/pull/15380", "description": "The `windowsHide` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10653", "description": "The `input` option can now be a `Uint8Array`." }, { "version": [ "v6.2.1", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6939", "description": "The `encoding` option can now explicitly be set to `buffer`." }, { "version": "v5.7.0", "pr-url": "https://github.com/nodejs/node/pull/4598", "description": "The `shell` option is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`command` {string} The command to run.", "name": "command", "type": "string", "desc": "The command to run." }, { "textRaw": "`args` {string[]} List of string arguments.", "name": "args", "type": "string[]", "desc": "List of string arguments.", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cwd` {string|URL} Current working directory of the child process.", "name": "cwd", "type": "string|URL", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer|TypedArray|DataView} The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`.", "name": "input", "type": "string|Buffer|TypedArray|DataView", "desc": "The value which will be passed as stdin to the spawned process. If `stdio[0]` is set to `'pipe'`, Supplying this value will override `stdio[0]`." }, { "textRaw": "`argv0` {string} Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified.", "name": "argv0", "type": "string", "desc": "Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` if not specified." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. See `child_process.spawn()`'s `stdio`. **Default:** `'pipe'`.", "name": "stdio", "type": "string|Array", "default": "`'pipe'`", "desc": "Child's stdio configuration. See `child_process.spawn()`'s `stdio`." }, { "textRaw": "`env` {Object} Environment key-value pairs. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "Environment key-value pairs." }, { "textRaw": "`uid` {number} Sets the user identity of the process (see `setuid(2)`).", "name": "uid", "type": "number", "desc": "Sets the user identity of the process (see `setuid(2)`)." }, { "textRaw": "`gid` {number} Sets the group identity of the process (see `setgid(2)`).", "name": "gid", "type": "number", "desc": "Sets the group identity of the process (see `setgid(2)`)." }, { "textRaw": "`timeout` {number} In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`.", "name": "timeout", "type": "number", "default": "`undefined`", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`.", "name": "killSignal", "type": "string|integer", "default": "`'SIGTERM'`", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {number} Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode. **Default:** `1024 * 1024`.", "name": "maxBuffer", "type": "number", "default": "`1024 * 1024`", "desc": "Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at `maxBuffer` and Unicode." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`.", "name": "encoding", "type": "string", "default": "`'buffer'`", "desc": "The encoding used for all stdio inputs and outputs." }, { "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. **Default:** `false` (no shell).", "name": "shell", "type": "boolean|string", "default": "`false` (no shell)", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell." }, { "textRaw": "`windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD. **Default:** `false`.", "name": "windowsVerbatimArguments", "type": "boolean", "default": "`false`", "desc": "No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to `true` automatically when `shell` is specified and is CMD." }, { "textRaw": "`windowsHide` {boolean} Hide the subprocess console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the subprocess console window that would normally be created on Windows systems." } ], "optional": true } ], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`pid` {number} Pid of the child process.", "name": "pid", "type": "number", "desc": "Pid of the child process." }, { "textRaw": "`output` {Array} Array of results from stdio output.", "name": "output", "type": "Array", "desc": "Array of results from stdio output." }, { "textRaw": "`stdout` {Buffer|string} The contents of `output[1]`.", "name": "stdout", "type": "Buffer|string", "desc": "The contents of `output[1]`." }, { "textRaw": "`stderr` {Buffer|string} The contents of `output[2]`.", "name": "stderr", "type": "Buffer|string", "desc": "The contents of `output[2]`." }, { "textRaw": "`status` {number|null} The exit code of the subprocess, or `null` if the subprocess terminated due to a signal.", "name": "status", "type": "number|null", "desc": "The exit code of the subprocess, or `null` if the subprocess terminated due to a signal." }, { "textRaw": "`signal` {string|null} The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal.", "name": "signal", "type": "string|null", "desc": "The signal used to kill the subprocess, or `null` if the subprocess did not terminate due to a signal." }, { "textRaw": "`error` {Error} The error object if the child process failed or timed out.", "name": "error", "type": "Error", "desc": "The error object if the child process failed or timed out." } ] } } ], "desc": "The child_process.spawnSync() method is generally identical to\nchild_process.spawn() with the exception that the function will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal is sent, the method won't return until the process has\ncompletely exited. If the process intercepts and handles the SIGTERM signal\nand doesn't exit, the parent process will wait until the child process has\nexited.
If the shell option is enabled, do not pass unsanitized user input to this\nfunction. Any input containing shell metacharacters may be used to trigger\narbitrary command execution.
The maxBuffer option specifies the largest number of bytes allowed on stdout\nor stderr. If this value is exceeded, then the child process is terminated.\nThis impacts output that includes multibyte character encodings such as UTF-8 or\nUTF-16. For instance, console.log('中文测试') will send 13 UTF-8 encoded bytes\nto stdout although there are only 4 characters.
The shell should understand the -c switch. If the shell is 'cmd.exe', it\nshould understand the /d /s /c switches and command-line parsing should be\ncompatible.
Although Microsoft specifies %COMSPEC% must contain the path to\n'cmd.exe' in the root environment, child processes are not always subject to\nthe same requirement. Thus, in child_process functions where a shell can be\nspawned, 'cmd.exe' is used as a fallback if process.env.ComSpec is\nunavailable.
Child processes support a serialization mechanism for IPC that is based on the\nserialization API of the node:v8 module, based on the\nHTML structured clone algorithm. This is generally more powerful and\nsupports more built-in JavaScript object types, such as BigInt, Map\nand Set, ArrayBuffer and TypedArray, Buffer, Error, RegExp etc.
However, this format is not a full superset of JSON, and e.g. properties set on\nobjects of such built-in types will not be passed on through the serialization\nstep. Additionally, performance may not be equivalent to that of JSON, depending\non the structure of the passed data.\nTherefore, this feature requires opting in by setting the\nserialization option to 'advanced' when calling child_process.spawn()\nor child_process.fork().
<EventEmitter>Instances of the ChildProcess represent spawned child processes.
Instances of ChildProcess are not intended to be created directly. Rather,\nuse the child_process.spawn(), child_process.exec(),\nchild_process.execFile(), or child_process.fork() methods to create\ninstances of ChildProcess.
The 'close' event is emitted after a process has ended and the stdio\nstreams of a child process have been closed. This is distinct from the\n'exit' event, since multiple processes might share the same stdio\nstreams. The 'close' event will always emit after 'exit' was\nalready emitted, or 'error' if the child process failed to spawn.
If the process exited, code is the final exit code of the process, otherwise\nnull. If the process terminated due to receipt of a signal, signal is the\nstring name of the signal, otherwise null. One of the two will always be\nnon-null.
const { spawn } = require('node:child_process');\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process close all stdio with code ${code}`);\n});\n\nls.on('exit', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n\nimport { spawn } from 'node:child_process';\nimport { once } from 'node:events';\nconst ls = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', (data) => {\n console.log(`stdout: ${data}`);\n});\n\nls.on('close', (code) => {\n console.log(`child process close all stdio with code ${code}`);\n});\n\nls.on('exit', (code) => {\n console.log(`child process exited with code ${code}`);\n});\n\nconst [code] = await once(ls, 'close');\nconsole.log(`child process close all stdio with code ${code}`);\n"
},
{
"textRaw": "Event: `'disconnect'`",
"name": "disconnect",
"type": "event",
"meta": {
"added": [
"v0.7.2"
],
"changes": []
},
"params": [],
"desc": "The 'disconnect' event is emitted after calling the\nsubprocess.disconnect() method in parent process or\nprocess.disconnect() in child process. After disconnecting it is no longer\npossible to send or receive messages, and the subprocess.connected\nproperty is false.
The 'error' event is emitted whenever:
signal option.The 'exit' event may or may not fire after an error has occurred. When\nlistening to both the 'exit' and 'error' events, guard\nagainst accidentally invoking handler functions multiple times.
See also subprocess.kill() and subprocess.send().
The 'exit' event is emitted after the child process ends. If the process\nexited, code is the final exit code of the process, otherwise null. If the\nprocess terminated due to receipt of a signal, signal is the string name of\nthe signal, otherwise null. One of the two will always be non-null.
When the 'exit' event is triggered, child process stdio streams might still be\nopen.
Node.js establishes signal handlers for SIGINT and SIGTERM and Node.js\nprocesses will not terminate immediately due to receipt of those signals.\nRather, Node.js will perform a sequence of cleanup actions and then will\nre-raise the handled signal.
See waitpid(2).
When code is null due to signal termination, you can use\nutil.convertProcessSignalToExitCode() to convert the signal to a POSIX\nexit code.
The 'message' event is triggered when a child process uses\nprocess.send() to send messages.
The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.
\nIf the serialization option was set to 'advanced' used when spawning the\nchild process, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for more details.
The 'spawn' event is emitted once the child process has spawned successfully.\nIf the child process does not spawn successfully, the 'spawn' event is not\nemitted and the 'error' event is emitted instead.
If emitted, the 'spawn' event comes before all other events and before any\ndata is received via stdout or stderr.
The 'spawn' event will fire regardless of whether an error occurs within\nthe spawned process. For example, if bash some-command spawns successfully,\nthe 'spawn' event will fire, though bash may fail to spawn some-command.\nThis caveat also applies when using { shell: true }.
The subprocess.channel property is a reference to the child's IPC channel. If\nno IPC channel exists, this property is undefined.
This method makes the IPC channel keep the event loop of the parent process\nrunning if .unref() has been called before.
This method makes the IPC channel not keep the event loop of the parent process\nrunning, and lets it finish even while the channel is open.
" } ] }, { "textRaw": "Type: {boolean} Set to `false` after `subprocess.disconnect()` is called.", "name": "connected", "type": "boolean", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "The subprocess.connected property indicates whether it is still possible to\nsend and receive messages from a child process. When subprocess.connected is\nfalse, it is no longer possible to send or receive messages.
The subprocess.exitCode property indicates the exit code of the child process.\nIf the child process is still running, the field will be null.
When the child process is terminated by a signal, subprocess.exitCode will be\nnull and subprocess.signalCode will be set. To get the corresponding\nPOSIX exit code, use\nutil.convertProcessSignalToExitCode(subprocess.signalCode).
The subprocess.killed property indicates whether the child process\nsuccessfully received a signal from subprocess.kill(). The killed property\ndoes not indicate that the child process has been terminated.
Returns the process identifier (PID) of the child process. If the child process\nfails to spawn due to errors, then the value is undefined and error is\nemitted.
const { spawn } = require('node:child_process');\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n\nimport { spawn } from 'node:child_process';\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n"
},
{
"textRaw": "Type: {string|null}",
"name": "signalCode",
"type": "string|null",
"desc": "The subprocess.signalCode property indicates the signal received by\nthe child process if any, else null.
When the child process is terminated by a signal, subprocess.exitCode will be null.\nTo get the corresponding POSIX exit code, use\nutil.convertProcessSignalToExitCode(subprocess.signalCode).
The subprocess.spawnargs property represents the full list of command-line\narguments the child process was launched with.
The subprocess.spawnfile property indicates the executable file name of\nthe child process that is launched.
For child_process.fork(), its value will be equal to\nprocess.execPath.\nFor child_process.spawn(), its value will be the name of\nthe executable file.\nFor child_process.exec(), its value will be the name of the shell\nin which the child process is launched.
A Readable Stream that represents the child process's stderr.
If the child process was spawned with stdio[2] set to anything other than 'pipe',\nthen this will be null.
subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will\nrefer to the same value.
The subprocess.stderr property can be null or undefined\nif the child process could not be successfully spawned.
A Writable Stream that represents the child process's stdin.
If a child process waits to read all of its input, the child process will not continue\nuntil this stream has been closed via end().
If the child process was spawned with stdio[0] set to anything other than 'pipe',\nthen this will be null.
subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will\nrefer to the same value.
The subprocess.stdin property can be null or undefined\nif the child process could not be successfully spawned.
A sparse array of pipes to the child process, corresponding with positions in\nthe stdio option passed to child_process.spawn() that have been set\nto the value 'pipe'. subprocess.stdio[0], subprocess.stdio[1], and\nsubprocess.stdio[2] are also available as subprocess.stdin,\nsubprocess.stdout, and subprocess.stderr, respectively.
In the following example, only the child's fd 1 (stdout) is configured as a\npipe, so only the parent's subprocess.stdio[1] is a stream, all other values\nin the array are null.
const assert = require('node:assert');\nconst fs = require('node:fs');\nconst child_process = require('node:child_process');\n\nconst subprocess = child_process.spawn('ls', {\n stdio: [\n 0, // Use parent's stdin for child.\n 'pipe', // Pipe child's stdout to parent.\n fs.openSync('err.out', 'w'), // Direct child's stderr to a file.\n ],\n});\n\nassert.strictEqual(subprocess.stdio[0], null);\nassert.strictEqual(subprocess.stdio[0], subprocess.stdin);\n\nassert(subprocess.stdout);\nassert.strictEqual(subprocess.stdio[1], subprocess.stdout);\n\nassert.strictEqual(subprocess.stdio[2], null);\nassert.strictEqual(subprocess.stdio[2], subprocess.stderr);\n\nimport assert from 'node:assert';\nimport fs from 'node:fs';\nimport child_process from 'node:child_process';\n\nconst subprocess = child_process.spawn('ls', {\n stdio: [\n 0, // Use parent's stdin for child.\n 'pipe', // Pipe child's stdout to parent.\n fs.openSync('err.out', 'w'), // Direct child's stderr to a file.\n ],\n});\n\nassert.strictEqual(subprocess.stdio[0], null);\nassert.strictEqual(subprocess.stdio[0], subprocess.stdin);\n\nassert(subprocess.stdout);\nassert.strictEqual(subprocess.stdio[1], subprocess.stdout);\n\nassert.strictEqual(subprocess.stdio[2], null);\nassert.strictEqual(subprocess.stdio[2], subprocess.stderr);\n\nThe subprocess.stdio property can be undefined if the child process could\nnot be successfully spawned.
A Readable Stream that represents the child process's stdout.
If the child process was spawned with stdio[1] set to anything other than 'pipe',\nthen this will be null.
subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will\nrefer to the same value.
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n console.log(`Received chunk ${data}`);\n});\n\nimport { spawn } from 'node:child_process';\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n console.log(`Received chunk ${data}`);\n});\n\nThe subprocess.stdout property can be null or undefined\nif the child process could not be successfully spawned.
Closes the IPC channel between parent and child processes, allowing the child\nprocess to exit gracefully once there are no other connections keeping it alive.\nAfter calling this method the subprocess.connected and\nprocess.connected properties in both the parent and child processes\n(respectively) will be set to false, and it will be no longer possible\nto pass messages between the processes.
The 'disconnect' event will be emitted when there are no messages in the\nprocess of being received. This will most often be triggered immediately after\ncalling subprocess.disconnect().
When the child process is a Node.js instance (e.g. spawned using\nchild_process.fork()), the process.disconnect() method can be invoked\nwithin the child process to close the IPC channel as well.
The subprocess.kill() method sends a signal to the child process. If no\nargument is given, the process will be sent the 'SIGTERM' signal. See\nsignal(7) for a list of available signals. This function returns true if\nkill(2) succeeds, and false otherwise.
const { spawn } = require('node:child_process');\nconst grep = spawn('grep', ['ssh']);\n\ngrep.on('close', (code, signal) => {\n console.log(\n `child process terminated due to receipt of signal ${signal}`);\n});\n\n// Send SIGHUP to process.\ngrep.kill('SIGHUP');\n\nimport { spawn } from 'node:child_process';\nconst grep = spawn('grep', ['ssh']);\n\ngrep.on('close', (code, signal) => {\n console.log(\n `child process terminated due to receipt of signal ${signal}`);\n});\n\n// Send SIGHUP to process.\ngrep.kill('SIGHUP');\n\nThe ChildProcess object may emit an 'error' event if the signal\ncannot be delivered. Sending a signal to a child process that has already exited\nis not an error but may have unforeseen consequences. Specifically, if the\nprocess identifier (PID) has been reassigned to another process, the signal will\nbe delivered to that process instead which can have unexpected results.
While the function is called kill, the signal delivered to the child process\nmay not actually terminate the process.
See kill(2) for reference.
On Windows, where POSIX signals do not exist, the signal argument will be\nignored except for 'SIGKILL', 'SIGTERM', 'SIGINT' and 'SIGQUIT', and the\nprocess will always be killed forcefully and abruptly (similar to 'SIGKILL').\nSee Signal Events for more details.
On Linux, child processes of child processes will not be terminated\nwhen attempting to kill their parent. This is likely to happen when running a\nnew process in a shell or with the use of the shell option of ChildProcess:
const { spawn } = require('node:child_process');\n\nconst subprocess = spawn(\n 'sh',\n [\n '-c',\n `node -e \"setInterval(() => {\n console.log(process.pid, 'is alive')\n }, 500);\"`,\n ], {\n stdio: ['inherit', 'inherit', 'inherit'],\n },\n);\n\nsetTimeout(() => {\n subprocess.kill(); // Does not terminate the Node.js process in the shell.\n}, 2000);\n\nimport { spawn } from 'node:child_process';\n\nconst subprocess = spawn(\n 'sh',\n [\n '-c',\n `node -e \"setInterval(() => {\n console.log(process.pid, 'is alive')\n }, 500);\"`,\n ], {\n stdio: ['inherit', 'inherit', 'inherit'],\n },\n);\n\nsetTimeout(() => {\n subprocess.kill(); // Does not terminate the Node.js process in the shell.\n}, 2000);\n"
},
{
"textRaw": "`subprocess[Symbol.dispose]()`",
"name": "[Symbol.dispose]",
"type": "method",
"meta": {
"added": [
"v20.5.0",
"v18.18.0"
],
"changes": [
{
"version": "v24.2.0",
"pr-url": "https://github.com/nodejs/node/pull/58467",
"description": "No longer experimental."
}
]
},
"signatures": [
{
"params": []
}
],
"desc": "Calls subprocess.kill() with 'SIGTERM'.
Calling subprocess.ref() after making a call to subprocess.unref() will\nrestore the removed reference count for the child process, forcing the parent\nprocess to wait for the child process to exit before exiting itself.
const { spawn } = require('node:child_process');\nconst process = require('node:process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\nsubprocess.ref();\n\nimport { spawn } from 'node:child_process';\nimport process from 'node:process';\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\nsubprocess.ref();\n"
},
{
"textRaw": "`subprocess.send(message[, sendHandle[, options]][, callback])`",
"name": "send",
"type": "method",
"meta": {
"added": [
"v0.5.9"
],
"changes": [
{
"version": "v5.8.0",
"pr-url": "https://github.com/nodejs/node/pull/5283",
"description": "The `options` parameter, and the `keepOpen` option in particular, is supported now."
},
{
"version": "v5.0.0",
"pr-url": "https://github.com/nodejs/node/pull/3516",
"description": "This method returns a boolean for flow control now."
},
{
"version": "v4.0.0",
"pr-url": "https://github.com/nodejs/node/pull/2620",
"description": "The `callback` parameter is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {Object}",
"name": "message",
"type": "Object"
},
{
"textRaw": "`sendHandle` {Handle|undefined} `undefined`, or a `net.Socket`, `net.Server`, or `dgram.Socket` object.",
"name": "sendHandle",
"type": "Handle|undefined",
"desc": "`undefined`, or a `net.Socket`, `net.Server`, or `dgram.Socket` object.",
"optional": true
},
{
"textRaw": "`options` {Object} The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"name": "options",
"type": "Object",
"desc": "The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties:",
"options": [
{
"textRaw": "`keepOpen` {boolean} A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process. **Default:** `false`.",
"name": "keepOpen",
"type": "boolean",
"default": "`false`",
"desc": "A value that can be used when passing instances of `net.Socket`. When `true`, the socket is kept open in the sending process."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "When an IPC channel has been established between the parent and child processes\n( i.e. when using child_process.fork()), the subprocess.send() method\ncan be used to send messages to the child process. When the child process is a\nNode.js instance, these messages can be received via the 'message' event.
The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.
\nFor example, in the parent script:
\nconst { fork } = require('node:child_process');\nconst forkedProcess = fork(`${__dirname}/sub.js`);\n\nforkedProcess.on('message', (message) => {\n console.log('PARENT got message:', message);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nforkedProcess.send({ hello: 'world' });\n\nimport { fork } from 'node:child_process';\nconst forkedProcess = fork(`${import.meta.dirname}/sub.js`);\n\nforkedProcess.on('message', (message) => {\n console.log('PARENT got message:', message);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nforkedProcess.send({ hello: 'world' });\n\nAnd then the child script, 'sub.js' might look like this:
process.on('message', (message) => {\n console.log('CHILD got message:', message);\n});\n\n// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }\nprocess.send({ foo: 'bar', baz: NaN });\n\nChild Node.js processes will have a process.send() method of their own\nthat allows the child process to send messages back to the parent process.
There is a special case when sending a {cmd: 'NODE_foo'} message. Messages\ncontaining a NODE_ prefix in the cmd property are reserved for use within\nNode.js core and will not be emitted in the child's 'message'\nevent. Rather, such messages are emitted using the\n'internalMessage' event and are consumed internally by Node.js.\nApplications should avoid using such messages or listening for\n'internalMessage' events as it is subject to change without notice.
The optional sendHandle argument that may be passed to subprocess.send() is\nfor passing a TCP server or socket object to the child process. The child process will\nreceive the object as the second argument passed to the callback function\nregistered on the 'message' event. Any data that is received\nand buffered in the socket will not be sent to the child. Sending IPC sockets is\nnot supported on Windows.
The optional callback is a function that is invoked after the message is\nsent but before the child process may have received it. The function is called with a\nsingle argument: null on success, or an Error object on failure.
If no callback function is provided and the message cannot be sent, an\n'error' event will be emitted by the ChildProcess object. This can\nhappen, for instance, when the child process has already exited.
subprocess.send() will return false if the channel has closed or when the\nbacklog of unsent messages exceeds a threshold that makes it unwise to send\nmore. Otherwise, the method returns true. The callback function can be\nused to implement flow control.
The sendHandle argument can be used, for instance, to pass the handle of\na TCP server object to the child process as illustrated in the example below:
const { fork } = require('node:child_process');\nconst { createServer } = require('node:net');\n\nconst subprocess = fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = createServer();\nserver.on('connection', (socket) => {\n socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n subprocess.send('server', server);\n});\n\nimport { fork } from 'node:child_process';\nimport { createServer } from 'node:net';\n\nconst subprocess = fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = createServer();\nserver.on('connection', (socket) => {\n socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n subprocess.send('server', server);\n});\n\nThe child process would then receive the server object as:
\nprocess.on('message', (m, server) => {\n if (m === 'server') {\n server.on('connection', (socket) => {\n socket.end('handled by child');\n });\n }\n});\n\nOnce the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.
\nWhile the example above uses a server created using the node:net module,\nnode:dgram module servers use exactly the same workflow with the exceptions of\nlistening on a 'message' event instead of 'connection' and using\nserver.bind() instead of server.listen(). This is, however, only\nsupported on Unix platforms.
Similarly, the sendHandler argument can be used to pass the handle of a\nsocket to the child process. The example below spawns two children that each\nhandle connections with \"normal\" or \"special\" priority:
const { fork } = require('node:child_process');\nconst { createServer } = require('node:net');\n\nconst normal = fork('subprocess.js', ['normal']);\nconst special = fork('subprocess.js', ['special']);\n\n// Open up the server and send sockets to child. Use pauseOnConnect to prevent\n// the sockets from being read before they are sent to the child process.\nconst server = createServer({ pauseOnConnect: true });\nserver.on('connection', (socket) => {\n\n // If this is special priority...\n if (socket.remoteAddress === '74.125.127.100') {\n special.send('socket', socket);\n return;\n }\n // This is normal priority.\n normal.send('socket', socket);\n});\nserver.listen(1337);\n\nimport { fork } from 'node:child_process';\nimport { createServer } from 'node:net';\n\nconst normal = fork('subprocess.js', ['normal']);\nconst special = fork('subprocess.js', ['special']);\n\n// Open up the server and send sockets to child. Use pauseOnConnect to prevent\n// the sockets from being read before they are sent to the child process.\nconst server = createServer({ pauseOnConnect: true });\nserver.on('connection', (socket) => {\n\n // If this is special priority...\n if (socket.remoteAddress === '74.125.127.100') {\n special.send('socket', socket);\n return;\n }\n // This is normal priority.\n normal.send('socket', socket);\n});\nserver.listen(1337);\n\nThe subprocess.js would receive the socket handle as the second argument\npassed to the event callback function:
process.on('message', (m, socket) => {\n if (m === 'socket') {\n if (socket) {\n // Check that the client socket exists.\n // It is possible for the socket to be closed between the time it is\n // sent and the time it is received in the child process.\n socket.end(`Request handled with ${process.argv[2]} priority`);\n }\n }\n});\n\nDo not use .maxConnections on a socket that has been passed to a subprocess.\nThe parent cannot track when the socket is destroyed.
Any 'message' handlers in the subprocess should verify that socket exists,\nas the connection may have been closed during the time it takes to send the\nconnection to the child.
By default, the parent process will wait for the detached child process to exit.\nTo prevent the parent process from waiting for a given subprocess to exit, use the\nsubprocess.unref() method. Doing so will cause the parent's event loop to not\ninclude the child process in its reference count, allowing the parent to exit\nindependently of the child, unless there is an established IPC channel between\nthe child and the parent processes.
const { spawn } = require('node:child_process');\nconst process = require('node:process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n\nimport { spawn } from 'node:child_process';\nimport process from 'node:process';\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore',\n});\n\nsubprocess.unref();\n"
}
]
}
],
"displayName": "Child process",
"source": "doc/api/child_process.md"
},
{
"textRaw": "Cluster",
"name": "cluster",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "Clusters of Node.js processes can be used to run multiple instances of Node.js\nthat can distribute workloads among their application threads. When process\nisolation is not needed, use the worker_threads module instead, which\nallows running multiple application threads within a single Node.js instance.
The cluster module allows easy creation of child processes that all share\nserver ports.
\nimport cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nconst numCPUs = availableParallelism();\n\nif (cluster.isPrimary) {\n console.log(`Primary ${process.pid} is running`);\n\n // Fork workers.\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n cluster.on('exit', (worker, code, signal) => {\n console.log(`worker ${worker.process.pid} died`);\n });\n} else {\n // Workers can share any TCP connection\n // In this case it is an HTTP server\n http.createServer((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n }).listen(8000);\n\n console.log(`Worker ${process.pid} started`);\n}\n\nconst cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\nconst process = require('node:process');\n\nif (cluster.isPrimary) {\n console.log(`Primary ${process.pid} is running`);\n\n // Fork workers.\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n cluster.on('exit', (worker, code, signal) => {\n console.log(`worker ${worker.process.pid} died`);\n });\n} else {\n // Workers can share any TCP connection\n // In this case it is an HTTP server\n http.createServer((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n }).listen(8000);\n\n console.log(`Worker ${process.pid} started`);\n}\n\nRunning Node.js will now share port 8000 between the workers:
\n$ node server.js\nPrimary 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n\nOn Windows, it is not yet possible to set up a named pipe server in a worker.
", "miscs": [ { "textRaw": "How it works", "name": "How it works", "type": "misc", "desc": "The worker processes are spawned using the child_process.fork() method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.
The cluster module supports two methods of distributing incoming\nconnections.
\nThe first one (and the default one on all platforms except Windows)\nis the round-robin approach, where the primary process listens on a\nport, accepts new connections and distributes them across the workers\nin a round-robin fashion, with some built-in smarts to avoid\noverloading a worker process.
\nThe second approach is where the primary process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.
\nThe second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.
\nBecause server.listen() hands off most of the work to the primary\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:
server.listen({fd: 7}) Because the message is passed to the primary,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the primary\nprocess.server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame \"random\" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. To listen\non a unique port, generate a port number based on the cluster worker ID.Node.js does not provide routing logic. It is therefore important to design an\napplication such that it does not rely too heavily on in-memory data objects for\nthings like sessions and login.
\nBecause workers are all separate processes, they can be killed or\nre-spawned depending on a program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. If no workers are alive, existing connections\nwill be dropped and new connections will be refused. Node.js does not\nautomatically manage the number of workers, however. It is the application's\nresponsibility to manage the worker pool based on its own needs.
\nAlthough a primary use case for the node:cluster module is networking, it can\nalso be used for other use cases requiring worker processes.
<EventEmitter>A Worker object contains all public information and method about a worker.\nIn the primary it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.
Similar to the cluster.on('disconnect') event, but specific to this worker.
cluster.fork().on('disconnect', () => {\n // Worker has disconnected\n});\n"
},
{
"textRaw": "Event: `'error'`",
"name": "error",
"type": "event",
"meta": {
"added": [
"v0.7.3"
],
"changes": []
},
"params": [],
"desc": "This event is the same as the one provided by child_process.fork().
Within a worker, process.on('error') may also be used.
Similar to the cluster.on('exit') event, but specific to this worker.
import cluster from 'node:cluster';\n\nif (cluster.isPrimary) {\n const worker = cluster.fork();\n worker.on('exit', (code, signal) => {\n if (signal) {\n console.log(`worker was killed by signal: ${signal}`);\n } else if (code !== 0) {\n console.log(`worker exited with error code: ${code}`);\n } else {\n console.log('worker success!');\n }\n });\n}\n\nconst cluster = require('node:cluster');\n\nif (cluster.isPrimary) {\n const worker = cluster.fork();\n worker.on('exit', (code, signal) => {\n if (signal) {\n console.log(`worker was killed by signal: ${signal}`);\n } else if (code !== 0) {\n console.log(`worker exited with error code: ${code}`);\n } else {\n console.log('worker success!');\n }\n });\n}\n"
},
{
"textRaw": "Event: `'listening'`",
"name": "listening",
"type": "event",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`address` {Object}",
"name": "address",
"type": "Object"
}
],
"desc": "Similar to the cluster.on('listening') event, but specific to this worker.
cluster.fork().on('listening', (address) => {\n // Worker is listening\n});\n\ncluster.fork().on('listening', (address) => {\n // Worker is listening\n});\n\nIt is not emitted in the worker.
" }, { "textRaw": "Event: `'message'`", "name": "message", "type": "event", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`handle` {undefined|Object}", "name": "handle", "type": "undefined|Object" } ], "desc": "Similar to the 'message' event of cluster, but specific to this worker.
Within a worker, process.on('message') may also be used.
Here is an example using the message system. It keeps a count in the primary\nprocess of the number of HTTP requests received by the workers:
\nimport cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nif (cluster.isPrimary) {\n\n // Keep track of http requests\n let numReqs = 0;\n setInterval(() => {\n console.log(`numReqs = ${numReqs}`);\n }, 1000);\n\n // Count requests\n function messageHandler(msg) {\n if (msg.cmd && msg.cmd === 'notifyRequest') {\n numReqs += 1;\n }\n }\n\n // Start workers and listen for messages containing notifyRequest\n const numCPUs = availableParallelism();\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n for (const id in cluster.workers) {\n cluster.workers[id].on('message', messageHandler);\n }\n\n} else {\n\n // Worker processes have a http server.\n http.Server((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n\n // Notify primary about the request\n process.send({ cmd: 'notifyRequest' });\n }).listen(8000);\n}\n\nconst cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\nconst process = require('node:process');\n\nif (cluster.isPrimary) {\n\n // Keep track of http requests\n let numReqs = 0;\n setInterval(() => {\n console.log(`numReqs = ${numReqs}`);\n }, 1000);\n\n // Count requests\n function messageHandler(msg) {\n if (msg.cmd && msg.cmd === 'notifyRequest') {\n numReqs += 1;\n }\n }\n\n // Start workers and listen for messages containing notifyRequest\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n for (const id in cluster.workers) {\n cluster.workers[id].on('message', messageHandler);\n }\n\n} else {\n\n // Worker processes have a http server.\n http.Server((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n\n // Notify primary about the request\n process.send({ cmd: 'notifyRequest' });\n }).listen(8000);\n}\n"
},
{
"textRaw": "Event: `'online'`",
"name": "online",
"type": "event",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [],
"desc": "Similar to the cluster.on('online') event, but specific to this worker.
cluster.fork().on('online', () => {\n // Worker is online\n});\n\nIt is not emitted in the worker.
" } ], "methods": [ { "textRaw": "`worker.disconnect()`", "name": "disconnect", "type": "method", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v7.3.0", "pr-url": "https://github.com/nodejs/node/pull/10019", "description": "This method now returns a reference to `worker`." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {cluster.Worker} A reference to `worker`.", "name": "return", "type": "cluster.Worker", "desc": "A reference to `worker`." } } ], "desc": "In a worker, this function will close all servers, wait for the 'close' event\non those servers, and then disconnect the IPC channel.
In the primary, an internal message is sent to the worker causing it to call\n.disconnect() on itself.
Causes .exitedAfterDisconnect to be set.
After a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker will close allowing it\nto die gracefully.
The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.
\nIn a worker, process.disconnect exists, but it is not this function;\nit is disconnect().
Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe 'disconnect' event has not been emitted after some time.
if (cluster.isPrimary) {\n const worker = cluster.fork();\n let timeout;\n\n worker.on('listening', (address) => {\n worker.send('shutdown');\n worker.disconnect();\n timeout = setTimeout(() => {\n worker.kill();\n }, 2000);\n });\n\n worker.on('disconnect', () => {\n clearTimeout(timeout);\n });\n\n} else if (cluster.isWorker) {\n const net = require('node:net');\n const server = net.createServer((socket) => {\n // Connections never end\n });\n\n server.listen(8000);\n\n process.on('message', (msg) => {\n if (msg === 'shutdown') {\n // Initiate graceful close of any connections to server\n }\n });\n}\n"
},
{
"textRaw": "`worker.isConnected()`",
"name": "isConnected",
"type": "method",
"meta": {
"added": [
"v0.11.14"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "This function returns true if the worker is connected to its primary via its\nIPC channel, false otherwise. A worker is connected to its primary after it\nhas been created. It is disconnected after the 'disconnect' event is emitted.
This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.
import cluster from 'node:cluster';\nimport http from 'node:http';\nimport { availableParallelism } from 'node:os';\nimport process from 'node:process';\n\nconst numCPUs = availableParallelism();\n\nif (cluster.isPrimary) {\n console.log(`Primary ${process.pid} is running`);\n\n // Fork workers.\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n cluster.on('fork', (worker) => {\n console.log('worker is dead:', worker.isDead());\n });\n\n cluster.on('exit', (worker, code, signal) => {\n console.log('worker is dead:', worker.isDead());\n });\n} else {\n // Workers can share any TCP connection. In this case, it is an HTTP server.\n http.createServer((req, res) => {\n res.writeHead(200);\n res.end(`Current process\\n ${process.pid}`);\n process.kill(process.pid);\n }).listen(8000);\n}\n\nconst cluster = require('node:cluster');\nconst http = require('node:http');\nconst numCPUs = require('node:os').availableParallelism();\nconst process = require('node:process');\n\nif (cluster.isPrimary) {\n console.log(`Primary ${process.pid} is running`);\n\n // Fork workers.\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n cluster.on('fork', (worker) => {\n console.log('worker is dead:', worker.isDead());\n });\n\n cluster.on('exit', (worker, code, signal) => {\n console.log('worker is dead:', worker.isDead());\n });\n} else {\n // Workers can share any TCP connection. In this case, it is an HTTP server.\n http.createServer((req, res) => {\n res.writeHead(200);\n res.end(`Current process\\n ${process.pid}`);\n process.kill(process.pid);\n }).listen(8000);\n}\n"
},
{
"textRaw": "`worker.kill([signal])`",
"name": "kill",
"type": "method",
"meta": {
"added": [
"v0.9.12"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`signal` {string} Name of the kill signal to send to the worker process. **Default:** `'SIGTERM'`",
"name": "signal",
"type": "string",
"default": "`'SIGTERM'`",
"desc": "Name of the kill signal to send to the worker process.",
"optional": true
}
]
}
],
"desc": "This function will kill the worker. In the primary worker, it does this by\ndisconnecting the worker.process, and once disconnected, killing with\nsignal. In the worker, it does it by killing the process with signal.
The kill() function kills the worker process without waiting for a graceful\ndisconnect, it has the same behavior as worker.process.kill().
This method is aliased as worker.destroy() for backwards compatibility.
In a worker, process.kill() exists, but it is not this function;\nit is kill().
Send a message to a worker or primary, optionally with a handle.
\nIn the primary, this sends a message to a specific worker. It is identical to\nChildProcess.send().
In a worker, this sends a message to the primary. It is identical to\nprocess.send().
This example will echo back all messages from the primary:
\nif (cluster.isPrimary) {\n const worker = cluster.fork();\n worker.send('hi there');\n\n} else if (cluster.isWorker) {\n process.on('message', (msg) => {\n process.send(msg);\n });\n}\n"
}
],
"properties": [
{
"textRaw": "Type: {boolean}",
"name": "exitedAfterDisconnect",
"type": "boolean",
"meta": {
"added": [
"v6.0.0"
],
"changes": []
},
"desc": "This property is true if the worker exited due to .disconnect().\nIf the worker exited any other way, it is false. If the\nworker has not exited, it is undefined.
The boolean worker.exitedAfterDisconnect allows distinguishing between\nvoluntary and accidental exit, the primary may choose not to respawn a worker\nbased on this value.
cluster.on('exit', (worker, code, signal) => {\n if (worker.exitedAfterDisconnect === true) {\n console.log('Oh, it was just voluntary – no need to worry');\n }\n});\n\n// kill worker\nworker.kill();\n"
},
{
"textRaw": "Type: {integer}",
"name": "id",
"type": "integer",
"meta": {
"added": [
"v0.8.0"
],
"changes": []
},
"desc": "Each new worker is given its own unique id, this id is stored in the\nid.
While a worker is alive, this is the key that indexes it in\ncluster.workers.
All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.
See: Child Process module.
\nWorkers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.
Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).
There may be a delay between the 'disconnect' and 'exit' events. These\nevents can be used to detect if the process is stuck in a cleanup or if there\nare long-living connections.
cluster.on('disconnect', (worker) => {\n console.log(`The worker #${worker.id} has disconnected`);\n});\n"
},
{
"textRaw": "Event: `'exit'`",
"name": "exit",
"type": "event",
"meta": {
"added": [
"v0.7.9"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
},
{
"textRaw": "`code` {number} The exit code, if it exited normally.",
"name": "code",
"type": "number",
"desc": "The exit code, if it exited normally."
},
{
"textRaw": "`signal` {string} The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed.",
"name": "signal",
"type": "string",
"desc": "The name of the signal (e.g. `'SIGHUP'`) that caused the process to be killed."
}
],
"desc": "When any of the workers die the cluster module will emit the 'exit' event.
This can be used to restart the worker by calling .fork() again.
cluster.on('exit', (worker, code, signal) => {\n console.log('worker %d died (%s). restarting...',\n worker.process.pid, signal || code);\n cluster.fork();\n});\n\nSee child_process event: 'exit'.
When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create a custom timeout.
const timeouts = [];\nfunction errorMsg() {\n console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n clearTimeout(timeouts[worker.id]);\n errorMsg();\n});\n"
},
{
"textRaw": "Event: `'listening'`",
"name": "listening",
"type": "event",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"params": [
{
"textRaw": "`worker` {cluster.Worker}",
"name": "worker",
"type": "cluster.Worker"
},
{
"textRaw": "`address` {Object}",
"name": "address",
"type": "Object"
}
],
"desc": "After calling listen() from a worker, when the 'listening' event is emitted\non the server, a 'listening' event will also be emitted on cluster in the\nprimary.
The event handler is executed with two arguments, the worker contains the\nworker object and the address object contains the following connection\nproperties: address, port, and addressType. This is very useful if the\nworker is listening on more than one address.
cluster.on('listening', (worker, address) => {\n console.log(\n `A worker is now connected to ${address.address}:${address.port}`);\n});\n\nThe addressType is one of:
4 (TCPv4)6 (TCPv6)-1 (Unix domain socket)'udp4' or 'udp6' (UDPv4 or UDPv6)Emitted when the cluster primary receives a message from any worker.
\nSee child_process event: 'message'.
After forking a new worker, the worker should respond with an online message.\nWhen the primary receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nprimary forks a worker, and 'online' is emitted when the worker is running.
cluster.on('online', (worker) => {\n console.log('Yay, the worker responded after it was forked');\n});\n"
},
{
"textRaw": "Event: `'setup'`",
"name": "setup",
"type": "event",
"meta": {
"added": [
"v0.7.1"
],
"changes": []
},
"params": [
{
"textRaw": "`settings` {Object}",
"name": "settings",
"type": "Object"
}
],
"desc": "Emitted every time .setupPrimary() is called.
The settings object is the cluster.settings object at the time\n.setupPrimary() was called and is advisory only, since multiple calls to\n.setupPrimary() can be made in a single tick.
If accuracy is important, use cluster.settings.
Calls .disconnect() on each worker in cluster.workers.
When they are disconnected all internal handles will be closed, allowing the\nprimary process to die gracefully if no other event is waiting.
\nThe method takes an optional callback argument which will be called when\nfinished.
\nThis can only be called from the primary process.
" }, { "textRaw": "`cluster.fork([env])`", "name": "fork", "type": "method", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment.", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment.", "optional": true } ], "return": { "textRaw": "Returns: {cluster.Worker}", "name": "return", "type": "cluster.Worker" } } ], "desc": "Spawn a new worker process.
\nThis can only be called from the primary process.
" }, { "textRaw": "`cluster.setupMaster([settings])`", "name": "setupMaster", "type": "method", "meta": { "added": [ "v0.7.1" ], "changes": [ { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7838", "description": "The `stdio` option is supported now." } ], "deprecated": [ "v16.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "Deprecated alias for .setupPrimary().
setupPrimary is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.
Any settings changes only affect future calls to .fork() and have no\neffect on workers that are already running.
The only attribute of a worker that cannot be set via .setupPrimary() is\nthe env passed to .fork().
The defaults above apply to the first call only; the defaults for later\ncalls are the current values at the time of cluster.setupPrimary() is called.
import cluster from 'node:cluster';\n\ncluster.setupPrimary({\n exec: 'worker.js',\n args: ['--use', 'https'],\n silent: true,\n});\ncluster.fork(); // https worker\ncluster.setupPrimary({\n exec: 'worker.js',\n args: ['--use', 'http'],\n});\ncluster.fork(); // http worker\n\nconst cluster = require('node:cluster');\n\ncluster.setupPrimary({\n exec: 'worker.js',\n args: ['--use', 'https'],\n silent: true,\n});\ncluster.fork(); // https worker\ncluster.setupPrimary({\n exec: 'worker.js',\n args: ['--use', 'http'],\n});\ncluster.fork(); // http worker\n\nThis can only be called from the primary process.
" } ], "properties": [ { "textRaw": "`cluster.isMaster`", "name": "isMaster", "type": "property", "meta": { "added": [ "v0.8.1" ], "changes": [], "deprecated": [ "v16.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "desc": "Deprecated alias for cluster.isPrimary.
True if the process is a primary. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isPrimary is true.
True if the process is not a primary (it is the negation of cluster.isPrimary).
The scheduling policy, either cluster.SCHED_RR for round-robin or\ncluster.SCHED_NONE to leave it to the operating system. This is a\nglobal setting and effectively frozen once either the first worker is spawned,\nor .setupPrimary() is called, whichever comes first.
SCHED_RR is the default on all operating systems except Windows.\nWindows will change to SCHED_RR once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.
cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are 'rr' and 'none'.
After calling .setupPrimary() (or .fork()) this settings object will\ncontain the settings, including the default values.
This object is not intended to be changed or set manually.
", "options": [ { "textRaw": "`execArgv` {string[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`.", "name": "execArgv", "type": "string[]", "default": "`process.execArgv`", "desc": "List of string arguments passed to the Node.js executable." }, { "textRaw": "`exec` {string} File path to worker file. **Default:** `process.argv[1]`.", "name": "exec", "type": "string", "default": "`process.argv[1]`", "desc": "File path to worker file." }, { "textRaw": "`args` {string[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`.", "name": "args", "type": "string[]", "default": "`process.argv.slice(2)`", "desc": "String arguments passed to worker." }, { "textRaw": "`cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process).", "name": "cwd", "type": "string", "default": "`undefined` (inherits from parent process)", "desc": "Current working directory of the worker process." }, { "textRaw": "`serialization` {string} Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for `child_process` for more details. **Default:** `false`.", "name": "serialization", "type": "string", "default": "`false`", "desc": "Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. See Advanced serialization for `child_process` for more details." }, { "textRaw": "`silent` {boolean} Whether or not to send output to parent's stdio. **Default:** `false`.", "name": "silent", "type": "boolean", "default": "`false`", "desc": "Whether or not to send output to parent's stdio." }, { "textRaw": "`stdio` {Array} Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See `child_process.spawn()`'s `stdio`.", "name": "stdio", "type": "Array", "desc": "Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See `child_process.spawn()`'s `stdio`." }, { "textRaw": "`uid` {number} Sets the user identity of the process. (See `setuid(2)`.)", "name": "uid", "type": "number", "desc": "Sets the user identity of the process. (See `setuid(2)`.)" }, { "textRaw": "`gid` {number} Sets the group identity of the process. (See `setgid(2)`.)", "name": "gid", "type": "number", "desc": "Sets the group identity of the process. (See `setgid(2)`.)" }, { "textRaw": "`inspectPort` {number|Function} Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the primary's `process.debugPort`.", "name": "inspectPort", "type": "number|Function", "desc": "Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the primary's `process.debugPort`." }, { "textRaw": "`windowsHide` {boolean} Hide the forked processes console window that would normally be created on Windows systems. **Default:** `false`.", "name": "windowsHide", "type": "boolean", "default": "`false`", "desc": "Hide the forked processes console window that would normally be created on Windows systems." } ] }, { "textRaw": "Type: {Object}", "name": "worker", "type": "Object", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "A reference to the current worker object. Not available in the primary process.
\nimport cluster from 'node:cluster';\n\nif (cluster.isPrimary) {\n console.log('I am primary');\n cluster.fork();\n cluster.fork();\n} else if (cluster.isWorker) {\n console.log(`I am worker #${cluster.worker.id}`);\n}\n\nconst cluster = require('node:cluster');\n\nif (cluster.isPrimary) {\n console.log('I am primary');\n cluster.fork();\n cluster.fork();\n} else if (cluster.isWorker) {\n console.log(`I am worker #${cluster.worker.id}`);\n}\n"
},
{
"textRaw": "Type: {Object}",
"name": "workers",
"type": "Object",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"desc": "A hash that stores the active worker objects, keyed by id field. This makes it\neasy to loop through all the workers. It is only available in the primary\nprocess.
A worker is removed from cluster.workers after the worker has disconnected\nand exited. The order between these two events cannot be determined in\nadvance. However, it is guaranteed that the removal from the cluster.workers\nlist happens before the last 'disconnect' or 'exit' event is emitted.
import cluster from 'node:cluster';\n\nfor (const worker of Object.values(cluster.workers)) {\n worker.send('big announcement to all workers');\n}\n\nconst cluster = require('node:cluster');\n\nfor (const worker of Object.values(cluster.workers)) {\n worker.send('big announcement to all workers');\n}\n"
}
],
"displayName": "Cluster",
"source": "doc/api/cluster.md"
},
{
"textRaw": "Console",
"name": "console",
"introduced_in": "v0.10.13",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:console module provides a simple debugging console that is similar to\nthe JavaScript console mechanism provided by web browsers.
The module exports two specific components:
\nConsole class with methods such as console.log(), console.error(), and\nconsole.warn() that can be used to write to any Node.js stream.console instance configured to write to process.stdout and\nprocess.stderr. The global console can be used without calling\nrequire('node:console').Warning: The global console object's methods are neither consistently\nsynchronous like the browser APIs they resemble, nor are they consistently\nasynchronous like all other Node.js streams. Programs that desire to depend\non the synchronous / asynchronous behavior of the console functions should\nfirst figure out the nature of console's backing stream. This is because the\nstream is dependent on the underlying platform and standard stream\nconfiguration of the current process. See the note on process I/O for\nmore information.
\nExample using the global console:
console.log('hello world');\n// Prints: hello world, to stdout\nconsole.log('hello %s', 'world');\n// Prints: hello world, to stdout\nconsole.error(new Error('Whoops, something bad happened'));\n// Prints error message and stack trace to stderr:\n// Error: Whoops, something bad happened\n// at [eval]:5:15\n// at Script.runInThisContext (node:vm:132:18)\n// at Object.runInThisContext (node:vm:309:38)\n// at node:internal/process/execution:77:19\n// at [eval]-wrapper:6:22\n// at evalScript (node:internal/process/execution:76:60)\n// at node:internal/main/eval_string:23:3\n\nconst name = 'Will Robinson';\nconsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to stderr\n\nExample using the Console class:
const out = getStreamSomehow();\nconst err = getStreamSomehow();\nconst myConsole = new console.Console(out, err);\n\nmyConsole.log('hello world');\n// Prints: hello world, to out\nmyConsole.log('hello %s', 'world');\n// Prints: hello world, to out\nmyConsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to err\n\nconst name = 'Will Robinson';\nmyConsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to err\n",
"classes": [
{
"textRaw": "Class: `Console`",
"name": "Console",
"type": "class",
"meta": {
"changes": [
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/9744",
"description": "Errors that occur while writing to the underlying streams will now be ignored by default."
}
]
},
"desc": "The Console class can be used to create a simple logger with configurable\noutput streams and can be accessed using either require('node:console').Console\nor console.Console (or their destructured counterparts):
import { Console } from 'node:console';\n\nconst { Console } = require('node:console');\n\nconst { Console } = console;\n",
"signatures": [
{
"textRaw": "`new Console(stdout[, stderr][, ignoreErrors])`",
"name": "Console",
"type": "ctor",
"params": [
{
"name": "stdout"
},
{
"name": "stderr",
"optional": true
},
{
"name": "ignoreErrors",
"optional": true
}
]
},
{
"textRaw": "`new Console(options)`",
"name": "Console",
"type": "ctor",
"meta": {
"changes": [
{
"version": "v24.10.0",
"pr-url": "https://github.com/nodejs/node/pull/60082",
"description": "The `inspectOptions` option can be a `Map` from stream to options."
},
{
"version": [
"v14.2.0",
"v12.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/32964",
"description": "The `groupIndentation` option was introduced."
},
{
"version": "v11.7.0",
"pr-url": "https://github.com/nodejs/node/pull/24978",
"description": "The `inspectOptions` option is introduced."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/19372",
"description": "The `Console` constructor now supports an `options` argument, and the `colorMode` option was introduced."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/9744",
"description": "The `ignoreErrors` option was introduced."
}
]
},
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`stdout` {stream.Writable}",
"name": "stdout",
"type": "stream.Writable"
},
{
"textRaw": "`stderr` {stream.Writable}",
"name": "stderr",
"type": "stream.Writable"
},
{
"textRaw": "`ignoreErrors` {boolean} Ignore errors when writing to the underlying streams. **Default:** `true`.",
"name": "ignoreErrors",
"type": "boolean",
"default": "`true`",
"desc": "Ignore errors when writing to the underlying streams."
},
{
"textRaw": "`colorMode` {boolean|string} Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well. **Default:** `'auto'`.",
"name": "colorMode",
"type": "boolean|string",
"default": "`'auto'`",
"desc": "Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. This option can not be used, if `inspectOptions.colors` is set as well."
},
{
"textRaw": "`inspectOptions` {Object|Map} Specifies options that are passed along to `util.inspect()`. Can be an options object or, if different options for stdout and stderr are desired, a `Map` from stream objects to options.",
"name": "inspectOptions",
"type": "Object|Map",
"desc": "Specifies options that are passed along to `util.inspect()`. Can be an options object or, if different options for stdout and stderr are desired, a `Map` from stream objects to options."
},
{
"textRaw": "`groupIndentation` {number} Set group indentation. **Default:** `2`.",
"name": "groupIndentation",
"type": "number",
"default": "`2`",
"desc": "Set group indentation."
}
]
}
],
"desc": "Creates a new Console with one or two writable stream instances. stdout is a\nwritable stream to print log or info output. stderr is used for warning or\nerror output. If stderr is not provided, stdout is used for stderr.
import { createWriteStream } from 'node:fs';\nimport { Console } from 'node:console';\n// Alternatively\n// const { Console } = console;\n\nconst output = createWriteStream('./stdout.log');\nconst errorOutput = createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n\nconst fs = require('node:fs');\nconst { Console } = require('node:console');\n// Alternatively\n// const { Console } = console;\n\nconst output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// Custom simple logger\nconst logger = new Console({ stdout: output, stderr: errorOutput });\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// In stdout.log: count 5\n\nThe global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:
new Console({ stdout: process.stdout, stderr: process.stderr });\n"
}
],
"methods": [
{
"textRaw": "`console.assert(value[, ...message])`",
"name": "assert",
"type": "method",
"meta": {
"added": [
"v0.1.101"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/17706",
"description": "The implementation is now spec compliant and does not throw anymore."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} The value tested for being truthy.",
"name": "value",
"type": "any",
"desc": "The value tested for being truthy."
},
{
"textRaw": "`...message` {any} All arguments besides `value` are used as error message.",
"name": "...message",
"type": "any",
"desc": "All arguments besides `value` are used as error message.",
"optional": true
}
]
}
],
"desc": "console.assert() writes a message if value is falsy or omitted. It only\nwrites a message and does not otherwise affect execution. The output always\nstarts with \"Assertion failed\". If provided, message is formatted using\nutil.format().
If value is truthy, nothing happens.
console.assert(true, 'does nothing');\n\nconsole.assert(false, 'Whoops %s work', 'didn\\'t');\n// Assertion failed: Whoops didn't work\n\nconsole.assert();\n// Assertion failed\n"
},
{
"textRaw": "`console.clear()`",
"name": "clear",
"type": "method",
"meta": {
"added": [
"v8.3.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "When stdout is a TTY, calling console.clear() will attempt to clear the\nTTY. When stdout is not a TTY, this method does nothing.
The specific operation of console.clear() can vary across operating systems\nand terminal types. For most Linux operating systems, console.clear()\noperates similarly to the clear shell command. On Windows, console.clear()\nwill clear only the output in the current terminal viewport for the Node.js\nbinary.
Maintains an internal counter specific to label and outputs to stdout the\nnumber of times console.count() has been called with the given label.
> console.count()\ndefault: 1\nundefined\n> console.count('default')\ndefault: 2\nundefined\n> console.count('abc')\nabc: 1\nundefined\n> console.count('xyz')\nxyz: 1\nundefined\n> console.count('abc')\nabc: 2\nundefined\n> console.count()\ndefault: 3\nundefined\n>\n"
},
{
"textRaw": "`console.countReset([label])`",
"name": "countReset",
"type": "method",
"meta": {
"added": [
"v8.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`label` {string} The display label for the counter. **Default:** `'default'`.",
"name": "label",
"type": "string",
"default": "`'default'`",
"desc": "The display label for the counter.",
"optional": true
}
]
}
],
"desc": "Resets the internal counter specific to label.
> console.count('abc');\nabc: 1\nundefined\n> console.countReset('abc');\nundefined\n> console.count('abc');\nabc: 1\nundefined\n>\n"
},
{
"textRaw": "`console.debug(data[, ...args])`",
"name": "debug",
"type": "method",
"meta": {
"added": [
"v8.0.0"
],
"changes": [
{
"version": "v8.10.0",
"pr-url": "https://github.com/nodejs/node/pull/17033",
"description": "`console.debug` is now an alias for `console.log`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`data` {any}",
"name": "data",
"type": "any"
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "The console.debug() function is an alias for console.log().
Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj.
This method calls console.log() passing it the arguments received.\nThis method does not produce any XML formatting.
Prints to stderr with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to util.format()).
const code = 5;\nconsole.error('error #%d', code);\n// Prints: error #5, to stderr\nconsole.error('error', code);\n// Prints: error 5, to stderr\n\nIf formatting elements (e.g. %d) are not found in the first string then\nutil.inspect() is called on each argument and the resulting string\nvalues are concatenated. See util.format() for more information.
Increases indentation of subsequent lines by spaces for groupIndentation\nlength.
If one or more labels are provided, those are printed first without the\nadditional indentation.
An alias for console.group().
Decreases indentation of subsequent lines by spaces for groupIndentation\nlength.
The console.info() function is an alias for console.log().
Prints to stdout with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;\nconsole.log('count: %d', count);\n// Prints: count: 5, to stdout\nconsole.log('count:', count);\n// Prints: count: 5, to stdout\n\nSee util.format() for more information.
Try to construct a table with the columns of the properties of tabularData\n(or use properties) and rows of tabularData and log it. Falls back to just\nlogging the argument if it can't be parsed as tabular.
// These can't be parsed as tabular data\nconsole.table(Symbol());\n// Symbol()\n\nconsole.table(undefined);\n// undefined\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);\n// ┌─────────┬─────┬─────┐\n// │ (index) │ a │ b │\n// ├─────────┼─────┼─────┤\n// │ 0 │ 1 │ 'Y' │\n// │ 1 │ 'Z' │ 2 │\n// └─────────┴─────┴─────┘\n\nconsole.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);\n// ┌─────────┬─────┐\n// │ (index) │ a │\n// ├─────────┼─────┤\n// │ 0 │ 1 │\n// │ 1 │ 'Z' │\n// └─────────┴─────┘\n"
},
{
"textRaw": "`console.time([label])`",
"name": "time",
"type": "method",
"meta": {
"added": [
"v0.1.104"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`label` {string} **Default:** `'default'`",
"name": "label",
"type": "string",
"default": "`'default'`",
"optional": true
}
]
}
],
"desc": "Starts a timer that can be used to compute the duration of an operation. Timers\nare identified by a unique label. Use the same label when calling\nconsole.timeEnd() to stop the timer and output the elapsed time in\nsuitable time units to stdout. For example, if the elapsed\ntime is 3869ms, console.timeEnd() displays \"3.869s\".
Stops a timer that was previously started by calling console.time() and\nprints the result to stdout:
console.time('bunch-of-stuff');\n// Do a bunch of stuff.\nconsole.timeEnd('bunch-of-stuff');\n// Prints: bunch-of-stuff: 225.438ms\n"
},
{
"textRaw": "`console.timeLog([label][, ...data])`",
"name": "timeLog",
"type": "method",
"meta": {
"added": [
"v10.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`label` {string} **Default:** `'default'`",
"name": "label",
"type": "string",
"default": "`'default'`",
"optional": true
},
{
"textRaw": "`...data` {any}",
"name": "...data",
"type": "any",
"optional": true
}
]
}
],
"desc": "For a timer that was previously started by calling console.time(), prints\nthe elapsed time and other data arguments to stdout:
console.time('process');\nconst value = expensiveProcess1(); // Returns 42\nconsole.timeLog('process', value);\n// Prints \"process: 365.227ms 42\".\ndoExpensiveProcess2(value);\nconsole.timeEnd('process');\n"
},
{
"textRaw": "`console.trace([message][, ...args])`",
"name": "trace",
"type": "method",
"meta": {
"added": [
"v0.1.104"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {any}",
"name": "message",
"type": "any",
"optional": true
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "Prints to stderr the string 'Trace: ', followed by the util.format()\nformatted message and stack trace to the current position in the code.
console.trace('Show me');\n// Prints: (stack trace will vary based on where trace is called)\n// Trace: Show me\n// at repl:2:9\n// at REPLServer.defaultEval (repl.js:248:27)\n// at bound (domain.js:287:14)\n// at REPLServer.runBound [as eval] (domain.js:300:12)\n// at REPLServer.<anonymous> (repl.js:412:12)\n// at emitOne (events.js:82:20)\n// at REPLServer.emit (events.js:169:7)\n// at REPLServer.Interface._onLine (readline.js:210:10)\n// at REPLServer.Interface._line (readline.js:549:8)\n// at REPLServer.Interface._ttyWrite (readline.js:826:14)\n"
},
{
"textRaw": "`console.warn([data][, ...args])`",
"name": "warn",
"type": "method",
"meta": {
"added": [
"v0.1.100"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`data` {any}",
"name": "data",
"type": "any",
"optional": true
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "The console.warn() function is an alias for console.error().
The following methods are exposed by the V8 engine in the general API but do\nnot display anything unless used in conjunction with the inspector\n(--inspect flag).
This method does not display anything unless used in the inspector. The\nconsole.profile() method starts a JavaScript CPU profile with an optional\nlabel until console.profileEnd() is called. The profile is then added to\nthe Profile panel of the inspector.
console.profile('MyLabel');\n// Some code\nconsole.profileEnd('MyLabel');\n// Adds the profile 'MyLabel' to the Profiles panel of the inspector.\n"
},
{
"textRaw": "`console.profileEnd([label])`",
"name": "profileEnd",
"type": "method",
"meta": {
"added": [
"v8.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`label` {string}",
"name": "label",
"type": "string",
"optional": true
}
]
}
],
"desc": "This method does not display anything unless used in the inspector. Stops the\ncurrent JavaScript CPU profiling session if one has been started and prints\nthe report to the Profiles panel of the inspector. See\nconsole.profile() for an example.
If this method is called without a label, the most recently started profile is\nstopped.
" }, { "textRaw": "`console.timeStamp([label])`", "name": "timeStamp", "type": "method", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string}", "name": "label", "type": "string", "optional": true } ] } ], "desc": "This method does not display anything unless used in the inspector. The\nconsole.timeStamp() method adds an event with the label 'label' to the\nTimeline panel of the inspector.
The node:crypto module provides cryptographic functionality that includes a\nset of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify\nfunctions.
const { createHmac } = await import('node:crypto');\n\nconst secret = 'abcdefg';\nconst hash = createHmac('sha256', secret)\n .update('I love cupcakes')\n .digest('hex');\nconsole.log(hash);\n// Prints:\n// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n\nconst { createHmac } = require('node:crypto');\n\nconst secret = 'abcdefg';\nconst hash = createHmac('sha256', secret)\n .update('I love cupcakes')\n .digest('hex');\nconsole.log(hash);\n// Prints:\n// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n",
"modules": [
{
"textRaw": "Determining if crypto support is unavailable",
"name": "determining_if_crypto_support_is_unavailable",
"type": "module",
"desc": "It is possible for Node.js to be built without including support for the\nnode:crypto module. In such cases, attempting to import from crypto or\ncalling require('node:crypto') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
\nlet crypto;\ntry {\n crypto = require('node:crypto');\n} catch (err) {\n console.error('crypto support is disabled!');\n}\n\nWhen using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made (using, for instance,\na preload module).
When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:
let crypto;\ntry {\n crypto = await import('node:crypto');\n} catch (err) {\n console.error('crypto support is disabled!');\n}\n",
"displayName": "Determining if crypto support is unavailable"
},
{
"textRaw": "Asymmetric key types",
"name": "asymmetric_key_types",
"type": "module",
"desc": "The following table lists the asymmetric key types recognized by the KeyObject API:
| Key Type | Description | OID |
|---|---|---|
'dh' | Diffie-Hellman | 1.2.840.113549.1.3.1 |
'dsa' | DSA | 1.2.840.10040.4.1 |
'ec' | Elliptic curve | 1.2.840.10045.2.1 |
'ed25519' | Ed25519 | 1.3.101.112 |
'ed448' | Ed448 | 1.3.101.113 |
'ml-dsa-44'1 | ML-DSA-44 | 2.16.840.1.101.3.4.3.17 |
'ml-dsa-65'1 | ML-DSA-65 | 2.16.840.1.101.3.4.3.18 |
'ml-dsa-87'1 | ML-DSA-87 | 2.16.840.1.101.3.4.3.19 |
'ml-kem-512'1 | ML-KEM-512 | 2.16.840.1.101.3.4.4.1 |
'ml-kem-768'1 | ML-KEM-768 | 2.16.840.1.101.3.4.4.2 |
'ml-kem-1024'1 | ML-KEM-1024 | 2.16.840.1.101.3.4.4.3 |
'rsa-pss' | RSA PSS | 1.2.840.113549.1.1.10 |
'rsa' | RSA | 1.2.840.113549.1.1.1 |
'slh-dsa-sha2-128f'1 | SLH-DSA-SHA2-128f | 2.16.840.1.101.3.4.3.21 |
'slh-dsa-sha2-128s'1 | SLH-DSA-SHA2-128s | 2.16.840.1.101.3.4.3.20 |
'slh-dsa-sha2-192f'1 | SLH-DSA-SHA2-192f | 2.16.840.1.101.3.4.3.23 |
'slh-dsa-sha2-192s'1 | SLH-DSA-SHA2-192s | 2.16.840.1.101.3.4.3.22 |
'slh-dsa-sha2-256f'1 | SLH-DSA-SHA2-256f | 2.16.840.1.101.3.4.3.25 |
'slh-dsa-sha2-256s'1 | SLH-DSA-SHA2-256s | 2.16.840.1.101.3.4.3.24 |
'slh-dsa-shake-128f'1 | SLH-DSA-SHAKE-128f | 2.16.840.1.101.3.4.3.27 |
'slh-dsa-shake-128s'1 | SLH-DSA-SHAKE-128s | 2.16.840.1.101.3.4.3.26 |
'slh-dsa-shake-192f'1 | SLH-DSA-SHAKE-192f | 2.16.840.1.101.3.4.3.29 |
'slh-dsa-shake-192s'1 | SLH-DSA-SHAKE-192s | 2.16.840.1.101.3.4.3.28 |
'slh-dsa-shake-256f'1 | SLH-DSA-SHAKE-256f | 2.16.840.1.101.3.4.3.31 |
'slh-dsa-shake-256s'1 | SLH-DSA-SHAKE-256s | 2.16.840.1.101.3.4.3.30 |
'x25519' | X25519 | 1.3.101.110 |
'x448' | X448 | 1.3.101.111 |
Provides an asynchronous Argon2 implementation. Argon2 is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe nonce should be as unique as possible. It is recommended that a nonce is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for message, nonce, secret or associatedData, please\nconsider caveats when using strings as inputs to cryptographic APIs.
The callback function is called with two arguments: err and derivedKey.\nerr is an exception object when key derivation fails, otherwise err is\nnull. derivedKey is passed to the callback as a Buffer.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst { argon2, randomBytes } = await import('node:crypto');\n\nconst parameters = {\n message: 'password',\n nonce: randomBytes(16),\n parallelism: 4,\n tagLength: 64,\n memory: 65536,\n passes: 3,\n};\n\nargon2('argon2id', parameters, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // 'af91dad...9520f15'\n});\n\nconst { argon2, randomBytes } = require('node:crypto');\n\nconst parameters = {\n message: 'password',\n nonce: randomBytes(16),\n parallelism: 4,\n tagLength: 64,\n memory: 65536,\n passes: 3,\n};\n\nargon2('argon2id', parameters, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // 'af91dad...9520f15'\n});\n"
},
{
"textRaw": "`crypto.argon2Sync(algorithm, parameters)`",
"name": "argon2Sync",
"type": "method",
"meta": {
"added": [
"v24.7.0"
],
"changes": []
},
"stability": 1.2,
"stabilityText": "Release candidate",
"signatures": [
{
"params": [
{
"textRaw": "`algorithm` {string} Variant of Argon2, one of `\"argon2d\"`, `\"argon2i\"` or `\"argon2id\"`.",
"name": "algorithm",
"type": "string",
"desc": "Variant of Argon2, one of `\"argon2d\"`, `\"argon2i\"` or `\"argon2id\"`."
},
{
"textRaw": "`parameters` {Object}",
"name": "parameters",
"type": "Object",
"options": [
{
"textRaw": "`message` {string|ArrayBuffer|Buffer|TypedArray|DataView} REQUIRED, this is the password for password hashing applications of Argon2.",
"name": "message",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "REQUIRED, this is the password for password hashing applications of Argon2."
},
{
"textRaw": "`nonce` {string|ArrayBuffer|Buffer|TypedArray|DataView} REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2.",
"name": "nonce",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2."
},
{
"textRaw": "`parallelism` {number} REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be greater than 1 and less than `2**24-1`.",
"name": "parallelism",
"type": "number",
"desc": "REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be greater than 1 and less than `2**24-1`."
},
{
"textRaw": "`tagLength` {number} REQUIRED, the length of the key to generate. Must be greater than 4 and less than `2**32-1`.",
"name": "tagLength",
"type": "number",
"desc": "REQUIRED, the length of the key to generate. Must be greater than 4 and less than `2**32-1`."
},
{
"textRaw": "`memory` {number} REQUIRED, memory cost in 1KiB blocks. Must be greater than `8 * parallelism` and less than `2**32-1`. The actual number of blocks is rounded down to the nearest multiple of `4 * parallelism`.",
"name": "memory",
"type": "number",
"desc": "REQUIRED, memory cost in 1KiB blocks. Must be greater than `8 * parallelism` and less than `2**32-1`. The actual number of blocks is rounded down to the nearest multiple of `4 * parallelism`."
},
{
"textRaw": "`passes` {number} REQUIRED, number of passes (iterations). Must be greater than 1 and less than `2**32-1`.",
"name": "passes",
"type": "number",
"desc": "REQUIRED, number of passes (iterations). Must be greater than 1 and less than `2**32-1`."
},
{
"textRaw": "`secret` {string|ArrayBuffer|Buffer|TypedArray|DataView|undefined} OPTIONAL, Random additional input, similar to the salt, that should **NOT** be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than `2**32-1` bytes.",
"name": "secret",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|undefined",
"desc": "OPTIONAL, Random additional input, similar to the salt, that should **NOT** be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than `2**32-1` bytes."
},
{
"textRaw": "`associatedData` {string|ArrayBuffer|Buffer|TypedArray|DataView|undefined} OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than `2**32-1` bytes.",
"name": "associatedData",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|undefined",
"desc": "OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than `2**32-1` bytes."
}
]
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Provides a synchronous Argon2 implementation. Argon2 is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe nonce should be as unique as possible. It is recommended that a nonce is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for message, nonce, secret or associatedData, please\nconsider caveats when using strings as inputs to cryptographic APIs.
An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst { argon2Sync, randomBytes } = await import('node:crypto');\n\nconst parameters = {\n message: 'password',\n nonce: randomBytes(16),\n parallelism: 4,\n tagLength: 64,\n memory: 65536,\n passes: 3,\n};\n\nconst derivedKey = argon2Sync('argon2id', parameters);\nconsole.log(derivedKey.toString('hex')); // 'af91dad...9520f15'\n\nconst { argon2Sync, randomBytes } = require('node:crypto');\n\nconst parameters = {\n message: 'password',\n nonce: randomBytes(16),\n parallelism: 4,\n tagLength: 64,\n memory: 65536,\n passes: 3,\n};\n\nconst derivedKey = argon2Sync('argon2id', parameters);\nconsole.log(derivedKey.toString('hex')); // 'af91dad...9520f15'\n"
},
{
"textRaw": "`crypto.checkPrime(candidate[, options], callback)`",
"name": "checkPrime",
"type": "method",
"meta": {
"added": [
"v15.8.0"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint} A possible prime encoded as a sequence of big endian octets of arbitrary length.",
"name": "candidate",
"type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint",
"desc": "A possible prime encoded as a sequence of big endian octets of arbitrary length."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`checks` {number} The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the `BN_is_prime_ex` function `nchecks` options for more details. **Default:** `0`",
"name": "checks",
"type": "number",
"default": "`0`",
"desc": "The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the `BN_is_prime_ex` function `nchecks` options for more details."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error} Set to an {Error} object if an error occurred during check.",
"name": "err",
"type": "Error",
"desc": "Set to an {Error} object if an error occurred during check."
},
{
"textRaw": "`result` {boolean} `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.",
"name": "result",
"type": "boolean",
"desc": "`true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`."
}
]
}
]
}
],
"desc": "Checks the primality of the candidate.
Checks the primality of the candidate.
Creates and returns a Cipheriv object, with the given algorithm, key and\ninitialization vector (iv).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.
When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.
Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a\ngiven IV will be.
" }, { "textRaw": "`crypto.createDecipheriv(algorithm, key, iv[, options])`", "name": "createDecipheriv", "type": "method", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": [ "v17.9.0", "v16.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/42427", "description": "The `authTagLength` option is now optional when using the `chacha20-poly1305` cipher and defaults to 16 bytes." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `key` argument can now be a `KeyObject`." }, { "version": [ "v11.2.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/24081", "description": "The cipher `chacha20-poly1305` (the IETF variant of ChaCha20-Poly1305) is now supported." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20039", "description": "The `authTagLength` option can now be used to restrict accepted GCM authentication tag lengths." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/18644", "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." } ] }, "signatures": [ { "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey" }, { "textRaw": "`iv` {string|ArrayBuffer|Buffer|TypedArray|DataView|null}", "name": "iv", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|null" }, { "textRaw": "`options` {Object} `stream.transform` options", "name": "options", "type": "Object", "desc": "`stream.transform` options", "optional": true } ], "return": { "textRaw": "Returns: {Decipheriv}", "name": "return", "type": "Decipheriv" } } ], "desc": "Creates and returns a Decipheriv object that uses the given algorithm, key\nand initialization vector (iv).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.\nFor chacha20-poly1305, the authTagLength option defaults to 16\nbytes and must be set to a different value if a different length is used.\nFor AES-GCM, the authTagLength option has no default value when decrypting,\nand setAuthTag() will accept arbitrarily short authentication tags. This\nbehavior is deprecated and subject to change (see DEP0182). \nIn the meantime, applications should either set the authTagLength option or\ncheck the actual authentication tag length before passing it to setAuthTag().
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.
When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.
Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a given\nIV will be.
" }, { "textRaw": "`crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`", "name": "createDiffieHellman", "type": "method", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `prime` argument can be any `TypedArray` or `DataView` now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11983", "description": "The `prime` argument can be a `Uint8Array` now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default for the encoding parameters changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`prime` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "prime", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`primeEncoding` {string} The encoding of the `prime` string.", "name": "primeEncoding", "type": "string", "desc": "The encoding of the `prime` string.", "optional": true }, { "textRaw": "`generator` {number|string|ArrayBuffer|Buffer|TypedArray|DataView} **Default:** `2`", "name": "generator", "type": "number|string|ArrayBuffer|Buffer|TypedArray|DataView", "default": "`2`", "optional": true }, { "textRaw": "`generatorEncoding` {string} The encoding of the `generator` string.", "name": "generatorEncoding", "type": "string", "desc": "The encoding of the `generator` string.", "optional": true } ], "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" } } ], "desc": "Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.
The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.
If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.
If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.
Creates a DiffieHellman key exchange object and generates a prime of\nprimeLength bits using an optional specific numeric generator.\nIf generator is not specified, the value 2 is used.
An alias for crypto.getDiffieHellman()
Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curveName string. Use\ncrypto.getCurves() to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves will also display the name\nand description of each available elliptic curve.
Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm. Optional options argument controls stream\nbehavior. For XOF hash functions such as 'shake256', the outputLength option\ncan be used to specify the desired output length in bytes.
The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms will\ndisplay the available digest algorithms.
Example: generating the sha256 sum of a file
\nimport {\n createReadStream,\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHash,\n} = await import('node:crypto');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHash,\n} = require('node:crypto');\nconst { argv } = require('node:process');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n"
},
{
"textRaw": "`crypto.createHmac(algorithm, key[, options])`",
"name": "createHmac",
"type": "method",
"meta": {
"added": [
"v0.1.94"
],
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The key can also be an ArrayBuffer or CryptoKey. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes."
},
{
"version": "v11.6.0",
"pr-url": "https://github.com/nodejs/node/pull/24234",
"description": "The `key` argument can now be a `KeyObject`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`algorithm` {string}",
"name": "algorithm",
"type": "string"
},
{
"textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}",
"name": "key",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey"
},
{
"textRaw": "`options` {Object} `stream.transform` options",
"name": "options",
"type": "Object",
"desc": "`stream.transform` options",
"options": [
{
"textRaw": "`encoding` {string} The string encoding to use when `key` is a string.",
"name": "encoding",
"type": "string",
"desc": "The string encoding to use when `key` is a string."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Hmac}",
"name": "return",
"type": "Hmac"
}
}
],
"desc": "Creates and returns an Hmac object that uses the given algorithm and key.\nOptional options argument controls stream behavior.
The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms will\ndisplay the available digest algorithms.
The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret. If it is a string, please consider\ncaveats when using strings as inputs to cryptographic APIs. If it was\nobtained from a cryptographically secure source of entropy, such as\ncrypto.randomBytes() or crypto.generateKey(), its length should not\nexceed the block size of algorithm (e.g., 512 bits for SHA-256).
Example: generating the sha256 HMAC of a file
\nimport {\n createReadStream,\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHmac,\n} = await import('node:crypto');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { argv } = require('node:process');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n"
},
{
"textRaw": "`crypto.createPrivateKey(key)`",
"name": "createPrivateKey",
"type": "method",
"meta": {
"added": [
"v11.6.0"
],
"changes": [
{
"version": "v24.6.0",
"pr-url": "https://github.com/nodejs/node/pull/59259",
"description": "Add support for ML-DSA keys."
},
{
"version": "v15.12.0",
"pr-url": "https://github.com/nodejs/node/pull/37254",
"description": "The key can also be a JWK object."
},
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "key",
"type": "Object|string|ArrayBuffer|Buffer|TypedArray|DataView",
"options": [
{
"textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key material, either in PEM, DER, or JWK format.",
"name": "key",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|Object",
"desc": "The key material, either in PEM, DER, or JWK format."
},
{
"textRaw": "`format` {string} Must be `'pem'`, `'der'`, or '`'jwk'`. **Default:** `'pem'`.",
"name": "format",
"type": "string",
"default": "`'pem'`",
"desc": "Must be `'pem'`, `'der'`, or '`'jwk'`."
},
{
"textRaw": "`type` {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored otherwise.",
"name": "type",
"type": "string",
"desc": "Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is required only if the `format` is `'der'` and ignored otherwise."
},
{
"textRaw": "`passphrase` {string|Buffer} The passphrase to use for decryption.",
"name": "passphrase",
"type": "string|Buffer",
"desc": "The passphrase to use for decryption."
},
{
"textRaw": "`encoding` {string} The string encoding to use when `key` is a string.",
"name": "encoding",
"type": "string",
"desc": "The string encoding to use when `key` is a string."
}
]
}
],
"return": {
"textRaw": "Returns: {KeyObject}",
"name": "return",
"type": "KeyObject"
}
}
],
"desc": "Creates and returns a new key object containing a private key. If key is a\nstring or Buffer, format is assumed to be 'pem'; otherwise, key\nmust be an object with the properties described above.
If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.
Creates and returns a new key object containing a public key. If key is a\nstring or Buffer, format is assumed to be 'pem'; if key is a KeyObject\nwith type 'private', the public key is derived from the given private key;\notherwise, 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\npassed instead of a public key. In that case, this function behaves as if\ncrypto.createPrivateKey() had been called, except that the type of the\nreturned KeyObject will be 'public' and that the private key cannot be\nextracted from the returned KeyObject. Similarly, if a KeyObject with type\n'private' is given, a new KeyObject with type 'public' will be returned\nand it will be impossible to extract the private key from the returned object.
Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.
Creates and returns a Sign object that uses the given algorithm. Use\ncrypto.getHashes() to obtain the names of the available digest algorithms.\nOptional options argument controls the stream.Writable behavior.
In some cases, a Sign instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.
Creates and returns a Verify object that uses the given algorithm.\nUse crypto.getHashes() to obtain an array of names of the available\nsigning algorithms. Optional options argument controls the\nstream.Writable behavior.
In some cases, a Verify instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.
Key decapsulation using a KEM algorithm with a private key.
\nSupported key types and their KEM algorithms are:
\n'rsa'1 RSA Secret Value Encapsulation'ec'2 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)'x25519'2 DHKEM(X25519, HKDF-SHA256)'x448'2 DHKEM(X448, HKDF-SHA512)'ml-kem-512'3 ML-KEM'ml-kem-768'3 ML-KEM'ml-kem-1024'3 ML-KEMIf key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey().
If the callback function is provided this function uses libuv's threadpool.
Computes the Diffie-Hellman shared secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType and must support either the DH or\nECDH operation.
If the callback function is provided this function uses libuv's threadpool.
Key encapsulation using a KEM algorithm with a public key.
\nSupported key types and their KEM algorithms are:
\n'rsa'1 RSA Secret Value Encapsulation'ec'2 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)'x25519'2 DHKEM(X25519, HKDF-SHA256)'x448'2 DHKEM(X448, HKDF-SHA512)'ml-kem-512'3 ML-KEM'ml-kem-768'3 ML-KEM'ml-kem-1024'3 ML-KEMIf key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey().
If the callback function is provided this function uses libuv's threadpool.
Asynchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
const {\n generateKey,\n} = await import('node:crypto');\n\ngenerateKey('hmac', { length: 512 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n\nconst {\n generateKey,\n} = require('node:crypto');\n\ngenerateKey('hmac', { length: 512 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n\nThe size of a generated HMAC key should not exceed the block size of the\nunderlying hash function. See crypto.createHmac() for more information.
Generates a new asymmetric key pair of the given type. See the\nsupported asymmetric key types.
If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.
It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:
const {\n generateKeyPair,\n} = await import('node:crypto');\n\ngenerateKeyPair('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret',\n },\n}, (err, publicKey, privateKey) => {\n // Handle errors and use the generated key pair.\n});\n\nconst {\n generateKeyPair,\n} = require('node:crypto');\n\ngenerateKeyPair('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret',\n },\n}, (err, publicKey, privateKey) => {\n // Handle errors and use the generated key pair.\n});\n\nOn completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.
If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.
Generates a new asymmetric key pair of the given type. See the\nsupported asymmetric key types.
If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.
When encoding public keys, it is recommended to use 'spki'. When encoding\nprivate keys, it is recommended to use 'pkcs8' with a strong passphrase,\nand to keep the passphrase confidential.
const {\n generateKeyPairSync,\n} = await import('node:crypto');\n\nconst {\n publicKey,\n privateKey,\n} = generateKeyPairSync('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret',\n },\n});\n\nconst {\n generateKeyPairSync,\n} = require('node:crypto');\n\nconst {\n publicKey,\n privateKey,\n} = generateKeyPairSync('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret',\n },\n});\n\nThe return value { publicKey, privateKey } represents the generated key pair.\nWhen PEM encoding was selected, the respective key will be a string, otherwise\nit will be a buffer containing the data encoded as DER.
Synchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
const {\n generateKeySync,\n} = await import('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 512 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n\nconst {\n generateKeySync,\n} = require('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 512 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n\nThe size of a generated HMAC key should not exceed the block size of the\nunderlying hash function. See crypto.createHmac() for more information.
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:
options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.options.add is set and options.safe is set to true, the prime\nwill instead satisfy the condition that prime % add = 3. This is necessary\nbecause prime % add = 1 for options.add > 2 would contradict the condition\nenforced 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\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.
By default, the prime is encoded as a big-endian sequence of octets\nin an <ArrayBuffer>. If the bigint option is true, then a <bigint>\nis provided.
The size of the prime will have a direct impact on how long it takes to\ngenerate the prime. The larger the size, the longer it will take. Because\nwe use OpenSSL's BN_generate_prime_ex function, which provides only\nminimal control over our ability to interrupt the generation process,\nit is not recommended to generate overly large primes, as doing so may make\nthe process unresponsive.
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:
options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.options.add is set and options.safe is set to true, the prime\nwill instead satisfy the condition that prime % add = 3. This is necessary\nbecause prime % add = 1 for options.add > 2 would contradict the condition\nenforced 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\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.
By default, the prime is encoded as a big-endian sequence of octets\nin an <ArrayBuffer>. If the bigint option is true, then a <bigint>\nis provided.
The size of the prime will have a direct impact on how long it takes to\ngenerate the prime. The larger the size, the longer it will take. Because\nwe use OpenSSL's BN_generate_prime_ex function, which provides only\nminimal control over our ability to interrupt the generation process,\nit is not recommended to generate overly large primes, as doing so may make\nthe process unresponsive.
Returns information about a given cipher.
\nSome ciphers accept variable length keys and initialization vectors. By default,\nthe crypto.getCipherInfo() method will return the default values for these\nciphers. To test if a given key length or iv length is acceptable for given\ncipher, use the keyLength and ivLength options. If the given values are\nunacceptable, undefined will be returned.
const {\n getCiphers,\n} = await import('node:crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n\nconst {\n getCiphers,\n} = require('node:crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n"
},
{
"textRaw": "`crypto.getCurves()`",
"name": "getCurves",
"type": "method",
"meta": {
"added": [
"v2.3.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]} An array with the names of the supported elliptic curves.",
"name": "return",
"type": "string[]",
"desc": "An array with the names of the supported elliptic curves."
}
}
],
"desc": "const {\n getCurves,\n} = await import('node:crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n\nconst {\n getCurves,\n} = require('node:crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n"
},
{
"textRaw": "`crypto.getDiffieHellman(groupName)`",
"name": "getDiffieHellman",
"type": "method",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`groupName` {string}",
"name": "groupName",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {DiffieHellmanGroup}",
"name": "return",
"type": "DiffieHellmanGroup"
}
}
],
"desc": "Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are listed in the documentation for DiffieHellmanGroup.
The returned object mimics the interface of objects created by\ncrypto.createDiffieHellman(), but will not allow changing\nthe keys (with diffieHellman.setPublicKey(), for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.
Example (obtaining a shared secret):
\nconst {\n getDiffieHellman,\n} = await import('node:crypto');\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n\nconst {\n getDiffieHellman,\n} = require('node:crypto');\n\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n"
},
{
"textRaw": "`crypto.getFips()`",
"name": "getFips",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {number} `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.",
"name": "return",
"type": "number",
"desc": "`1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}."
}
}
]
},
{
"textRaw": "`crypto.getHashes()`",
"name": "getHashes",
"type": "method",
"meta": {
"added": [
"v0.9.3"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms.",
"name": "return",
"type": "string[]",
"desc": "An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms."
}
}
],
"desc": "const {\n getHashes,\n} = await import('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n\nconst {\n getHashes,\n} = require('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n"
},
{
"textRaw": "`crypto.getRandomValues(typedArray)`",
"name": "getRandomValues",
"type": "method",
"meta": {
"added": [
"v17.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`typedArray` {Buffer|TypedArray|DataView|ArrayBuffer}",
"name": "typedArray",
"type": "Buffer|TypedArray|DataView|ArrayBuffer"
}
],
"return": {
"textRaw": "Returns: {Buffer|TypedArray|DataView|ArrayBuffer} Returns `typedArray`.",
"name": "return",
"type": "Buffer|TypedArray|DataView|ArrayBuffer",
"desc": "Returns `typedArray`."
}
}
],
"desc": "A convenient alias for crypto.webcrypto.getRandomValues(). This\nimplementation is not compliant with the Web Crypto spec, to write\nweb-compatible code use crypto.webcrypto.getRandomValues() instead.
A utility for creating one-shot hash digests of data. It can be faster than\nthe object-based crypto.createHash() when hashing a smaller amount of data\n(<= 5MB) that's readily available. If the data can be big or if it is streamed,\nit's still recommended to use crypto.createHash() instead.
The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms will\ndisplay the available digest algorithms.
If options is a string, then it specifies the outputEncoding.
Example:
\nconst crypto = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\n// Hashing a string and return the result as a hex-encoded string.\nconst string = 'Node.js';\n// 10b3493287f831e81a438811a1ffba01f8cec4b7\nconsole.log(crypto.hash('sha1', string));\n\n// Encode a base64-encoded string into a Buffer, hash it and return\n// the result as a buffer.\nconst base64 = 'Tm9kZS5qcw==';\n// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>\nconsole.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));\n\nimport crypto from 'node:crypto';\nimport { Buffer } from 'node:buffer';\n\n// Hashing a string and return the result as a hex-encoded string.\nconst string = 'Node.js';\n// 10b3493287f831e81a438811a1ffba01f8cec4b7\nconsole.log(crypto.hash('sha1', string));\n\n// Encode a base64-encoded string into a Buffer, hash it and return\n// the result as a buffer.\nconst base64 = 'Tm9kZS5qcw==';\n// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>\nconsole.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));\n"
},
{
"textRaw": "`crypto.hkdf(digest, ikm, salt, info, keylen, callback)`",
"name": "hkdf",
"type": "method",
"meta": {
"added": [
"v15.0.0"
],
"changes": [
{
"version": [
"v18.8.0",
"v16.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/44201",
"description": "The input keying material can now be zero-length."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`digest` {string} The digest algorithm to use.",
"name": "digest",
"type": "string",
"desc": "The digest algorithm to use."
},
{
"textRaw": "`ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input keying material. Must be provided but can be zero-length.",
"name": "ikm",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject",
"desc": "The input keying material. Must be provided but can be zero-length."
},
{
"textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must be provided but can be zero-length.",
"name": "salt",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "The salt value. Must be provided but can be zero-length."
},
{
"textRaw": "`info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.",
"name": "info",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes."
},
{
"textRaw": "`keylen` {number} The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes).",
"name": "keylen",
"type": "number",
"desc": "The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes)."
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`derivedKey` {ArrayBuffer}",
"name": "derivedKey",
"type": "ArrayBuffer"
}
]
}
]
}
],
"desc": "HKDF is a simple key derivation function defined in RFC 5869. The given ikm,\nsalt 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\nderivedKey. If an errors occurs while deriving the key, err will be set;\notherwise err will be null. The successfully generated derivedKey will\nbe passed to the callback as an <ArrayBuffer>. An error will be thrown if any\nof the input arguments specify invalid values or types.
import { Buffer } from 'node:buffer';\nconst {\n hkdf,\n} = await import('node:crypto');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n});\n\nconst {\n hkdf,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n});\n"
},
{
"textRaw": "`crypto.hkdfSync(digest, ikm, salt, info, keylen)`",
"name": "hkdfSync",
"type": "method",
"meta": {
"added": [
"v15.0.0"
],
"changes": [
{
"version": [
"v18.8.0",
"v16.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/44201",
"description": "The input keying material can now be zero-length."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`digest` {string} The digest algorithm to use.",
"name": "digest",
"type": "string",
"desc": "The digest algorithm to use."
},
{
"textRaw": "`ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input keying material. Must be provided but can be zero-length.",
"name": "ikm",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject",
"desc": "The input keying material. Must be provided but can be zero-length."
},
{
"textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must be provided but can be zero-length.",
"name": "salt",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "The salt value. Must be provided but can be zero-length."
},
{
"textRaw": "`info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.",
"name": "info",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView",
"desc": "Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes."
},
{
"textRaw": "`keylen` {number} The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes).",
"name": "keylen",
"type": "number",
"desc": "The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes)."
}
],
"return": {
"textRaw": "Returns: {ArrayBuffer}",
"name": "return",
"type": "ArrayBuffer"
}
}
],
"desc": "Provides a synchronous HKDF key derivation function as defined in RFC 5869. The\ngiven ikm, salt and info are used with the digest to derive a key of\nkeylen bytes.
The successfully generated derivedKey will be returned as an <ArrayBuffer>.
An error will be thrown if any of the input arguments specify invalid values or\ntypes, or if the derived key cannot be generated.
\nimport { Buffer } from 'node:buffer';\nconst {\n hkdfSync,\n} = await import('node:crypto');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n\nconst {\n hkdfSync,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n"
},
{
"textRaw": "`crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`",
"name": "pbkdf2",
"type": "method",
"meta": {
"added": [
"v0.5.5"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The password and salt arguments can also be ArrayBuffer instances."
},
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/30578",
"description": "The `iterations` parameter is now restricted to positive values. Earlier releases treated other values as one."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/11305",
"description": "The `digest` parameter is always required now."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/4047",
"description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/5522",
"description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "password",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "salt",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`iterations` {number}",
"name": "iterations",
"type": "number"
},
{
"textRaw": "`keylen` {number}",
"name": "keylen",
"type": "number"
},
{
"textRaw": "`digest` {string}",
"name": "digest",
"type": "string"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`derivedKey` {Buffer}",
"name": "derivedKey",
"type": "Buffer"
}
]
}
]
}
],
"desc": "Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.
The supplied callback function is called with two arguments: err and\nderivedKey. If an error occurs while deriving the key, err will be set;\notherwise err will be null. By default, the successfully generated\nderivedKey will be passed to the callback as a Buffer. An error will be\nthrown if any of the input arguments specify invalid values or types.
The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
const {\n pbkdf2,\n} = await import('node:crypto');\n\npbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n\nconst {\n pbkdf2,\n} = require('node:crypto');\n\npbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes().
This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest is\napplied to derive a key of the requested byte length (keylen) from the\npassword, salt and iterations.
If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer.
The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
const {\n pbkdf2Sync,\n} = await import('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n\nconst {\n pbkdf2Sync,\n} = require('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes().
Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.
Using crypto.constants.RSA_PKCS1_PADDING in crypto.privateDecrypt()\nrequires OpenSSL to support implicit rejection (rsa_pkcs1_implicit_rejection).\nIf the version of OpenSSL used by Node.js does not support this feature,\nattempting to use RSA_PKCS1_PADDING will fail.
Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.
Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().
If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
" }, { "textRaw": "`crypto.publicEncrypt(key, buffer)`", "name": "publicEncrypt", "type": "method", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel and passphrase can be ArrayBuffers. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes." }, { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29489", "description": "The `oaepLabel` option was added." }, { "version": "v12.9.0", "pr-url": "https://github.com/nodejs/node/pull/28335", "description": "The `oaepHash` option was added." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [ { "textRaw": "`key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey", "options": [ { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} A PEM encoded public or private key, {KeyObject}, or {CryptoKey}.", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey", "desc": "A PEM encoded public or private key, {KeyObject}, or {CryptoKey}." }, { "textRaw": "`oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'`", "name": "oaepHash", "type": "string", "default": "`'sha1'`", "desc": "The hash function to use for OAEP padding and MGF1." }, { "textRaw": "`oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to use for OAEP padding. If not specified, no label is used.", "name": "oaepLabel", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "The label to use for OAEP padding. If not specified, no label is used." }, { "textRaw": "`passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional passphrase for the private key.", "name": "passphrase", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "An optional passphrase for the private key." }, { "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", "name": "padding", "type": "crypto.constants", "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." }, { "textRaw": "`encoding` {string} The string encoding to use when `buffer`, `key`, `oaepLabel`, or `passphrase` are strings.", "name": "encoding", "type": "string", "desc": "The string encoding to use when `buffer`, `key`, `oaepLabel`, or `passphrase` are strings." } ] }, { "textRaw": "`buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "buffer", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" } ], "return": { "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", "name": "return", "type": "Buffer", "desc": "A new `Buffer` with the encrypted content." } } ], "desc": "Encrypts the content of buffer with key and returns a new\nBuffer with encrypted content. The returned data can be decrypted using\nthe corresponding private key, for example using crypto.privateDecrypt().
If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
" }, { "textRaw": "`crypto.randomBytes(size[, callback])`", "name": "randomBytes", "type": "method", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/16454", "description": "Passing `null` as the `callback` argument now throws `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "desc": "The number of bytes to generate. The `size` must not be larger than `2**31 - 1`." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`buf` {Buffer}", "name": "buf", "type": "Buffer" } ], "optional": true } ], "return": { "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", "name": "return", "type": "Buffer", "desc": "if the `callback` function is not provided." } } ], "desc": "Generates cryptographically strong pseudorandom data. The size argument\nis a number indicating the number of bytes to generate.
If a callback function is provided, the bytes are generated asynchronously\nand the callback function is invoked with two arguments: err and buf.\nIf an error occurs, err will be an Error object; otherwise it is null. The\nbuf argument is a Buffer containing the generated bytes.
// Asynchronous\nconst {\n randomBytes,\n} = await import('node:crypto');\n\nrandomBytes(256, (err, buf) => {\n if (err) throw err;\n console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n\n// Asynchronous\nconst {\n randomBytes,\n} = require('node:crypto');\n\nrandomBytes(256, (err, buf) => {\n if (err) throw err;\n console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n\nIf the callback function is not provided, the random bytes are generated\nsynchronously and returned as a Buffer. An error will be thrown if\nthere is a problem generating the bytes.
// Synchronous\nconst {\n randomBytes,\n} = await import('node:crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n\n// Synchronous\nconst {\n randomBytes,\n} = require('node:crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n\nThe crypto.randomBytes() method will not complete until there is\nsufficient entropy available.\nThis should normally never take longer than a few milliseconds. The only time\nwhen generating the random bytes may conceivably block for a longer period of\ntime is right after boot, when the whole system is still low on entropy.
This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.
The asynchronous version of crypto.randomBytes() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomBytes requests when doing so as part of fulfilling a client\nrequest.
This function is similar to crypto.randomBytes() but requires the first\nargument to be a Buffer that will be filled. It also\nrequires that a callback is passed in.
If the callback function is not provided, an error will be thrown.
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node:crypto');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nconst { randomFill } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nAny ArrayBuffer, TypedArray, or DataView instance may be passed as\nbuffer.
While this includes instances of Float32Array and Float64Array, this\nfunction should not be used to generate random floating-point numbers. The\nresult may contain +Infinity, -Infinity, and NaN, and even if the array\ncontains finite numbers only, they are not drawn from a uniform random\ndistribution and have no meaningful lower or upper bounds.
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node:crypto');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf).toString('hex'));\n});\n\nconst { randomFill } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf).toString('hex'));\n});\n\nThis API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.
The asynchronous version of crypto.randomFill() is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomFill requests when doing so as part of fulfilling a client\nrequest.
Synchronous version of crypto.randomFill().
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node:crypto');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n\nconst { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n\nAny ArrayBuffer, TypedArray or DataView instance may be passed as\nbuffer.
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node:crypto');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n\nconst { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n"
},
{
"textRaw": "`crypto.randomInt([min, ]max[, callback])`",
"name": "randomInt",
"type": "method",
"meta": {
"added": [
"v14.10.0",
"v12.19.0"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`min` {integer} Start of random range (inclusive). **Default:** `0`.",
"name": "min",
"type": "integer",
"default": "`0`",
"desc": "Start of random range (inclusive).",
"optional": true
},
{
"textRaw": "`max` {integer} End of random range (exclusive).",
"name": "max",
"type": "integer",
"desc": "End of random range (exclusive)."
},
{
"textRaw": "`callback` {Function} `function(err, n) {}`.",
"name": "callback",
"type": "Function",
"desc": "`function(err, n) {}`.",
"optional": true
}
]
}
],
"desc": "Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.
The range (max - min) must be less than 248. min and max must\nbe safe integers.
If the callback function is not provided, the random integer is\ngenerated synchronously.
// Asynchronous\nconst {\n randomInt,\n} = await import('node:crypto');\n\nrandomInt(3, (err, n) => {\n if (err) throw err;\n console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n\n// Asynchronous\nconst {\n randomInt,\n} = require('node:crypto');\n\nrandomInt(3, (err, n) => {\n if (err) throw err;\n console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n\n// Synchronous\nconst {\n randomInt,\n} = await import('node:crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n\n// Synchronous\nconst {\n randomInt,\n} = require('node:crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n\n// With `min` argument\nconst {\n randomInt,\n} = await import('node:crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n\n// With `min` argument\nconst {\n randomInt,\n} = require('node:crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n"
},
{
"textRaw": "`crypto.randomUUID([options])`",
"name": "randomUUID",
"type": "method",
"meta": {
"added": [
"v15.6.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`disableEntropyCache` {boolean} By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set `disableEntropyCache` to `true`. **Default:** `false`.",
"name": "disableEntropyCache",
"type": "boolean",
"default": "`false`",
"desc": "By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set `disableEntropyCache` to `true`."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
}
}
],
"desc": "Generates a random RFC 4122 version 4 UUID. The UUID is generated using a\ncryptographic pseudorandom number generator.
" }, { "textRaw": "`crypto.scrypt(password, salt, keylen[, options], callback)`", "name": "scrypt", "type": "method", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password and salt arguments can also be ArrayBuffer instances." }, { "version": [ "v12.8.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/28799", "description": "The `maxmem` value can now be any safe integer." }, { "version": "v10.9.0", "pr-url": "https://github.com/nodejs/node/pull/21525", "description": "The `cost`, `blockSize` and `parallelization` option names have been added." } ] }, "signatures": [ { "params": [ { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", "name": "cost", "type": "number", "default": "`16384`", "desc": "CPU/memory cost parameter. Must be a power of two greater than one." }, { "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", "name": "blockSize", "type": "number", "default": "`8`", "desc": "Block size parameter." }, { "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", "name": "parallelization", "type": "number", "default": "`1`", "desc": "Parallelization parameter." }, { "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", "name": "N", "type": "number", "desc": "Alias for `cost`. Only one of both may be specified." }, { "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", "name": "r", "type": "number", "desc": "Alias for `blockSize`. Only one of both may be specified." }, { "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", "name": "p", "type": "number", "desc": "Alias for `parallelization`. Only one of both may be specified." }, { "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", "name": "maxmem", "type": "number", "default": "`32 * 1024 * 1024`", "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." } ], "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {Buffer}", "name": "derivedKey", "type": "Buffer" } ] } ] } ], "desc": "Provides an asynchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
The callback function is called with two arguments: err and derivedKey.\nerr is an exception object when key derivation fails, otherwise err is\nnull. derivedKey is passed to the callback as a Buffer.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst {\n scrypt,\n} = await import('node:crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'\n});\n\nconst {\n scrypt,\n} = require('node:crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'\n});\n"
},
{
"textRaw": "`crypto.scryptSync(password, salt, keylen[, options])`",
"name": "scryptSync",
"type": "method",
"meta": {
"added": [
"v10.5.0"
],
"changes": [
{
"version": [
"v12.8.0",
"v10.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/28799",
"description": "The `maxmem` value can now be any safe integer."
},
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21525",
"description": "The `cost`, `blockSize` and `parallelization` option names have been added."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`password` {string|Buffer|TypedArray|DataView}",
"name": "password",
"type": "string|Buffer|TypedArray|DataView"
},
{
"textRaw": "`salt` {string|Buffer|TypedArray|DataView}",
"name": "salt",
"type": "string|Buffer|TypedArray|DataView"
},
{
"textRaw": "`keylen` {number}",
"name": "keylen",
"type": "number"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.",
"name": "cost",
"type": "number",
"default": "`16384`",
"desc": "CPU/memory cost parameter. Must be a power of two greater than one."
},
{
"textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.",
"name": "blockSize",
"type": "number",
"default": "`8`",
"desc": "Block size parameter."
},
{
"textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.",
"name": "parallelization",
"type": "number",
"default": "`1`",
"desc": "Parallelization parameter."
},
{
"textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.",
"name": "N",
"type": "number",
"desc": "Alias for `cost`. Only one of both may be specified."
},
{
"textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.",
"name": "r",
"type": "number",
"desc": "Alias for `blockSize`. Only one of both may be specified."
},
{
"textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.",
"name": "p",
"type": "number",
"desc": "Alias for `parallelization`. Only one of both may be specified."
},
{
"textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.",
"name": "maxmem",
"type": "number",
"default": "`32 * 1024 * 1024`",
"desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer}",
"name": "return",
"type": "Buffer"
}
}
],
"desc": "Provides a synchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst {\n scryptSync,\n} = await import('node:crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex')); // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex')); // '3745e48...aa39b34'\n\nconst {\n scryptSync,\n} = require('node:crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex')); // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex')); // '3745e48...aa39b34'\n"
},
{
"textRaw": "`crypto.secureHeapUsed()`",
"name": "secureHeapUsed",
"type": "method",
"meta": {
"added": [
"v15.6.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`total` {number} The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.",
"name": "total",
"type": "number",
"desc": "The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag."
},
{
"textRaw": "`min` {number} The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.",
"name": "min",
"type": "number",
"desc": "The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag."
},
{
"textRaw": "`used` {number} The total number of bytes currently allocated from the secure heap.",
"name": "used",
"type": "number",
"desc": "The total number of bytes currently allocated from the secure heap."
},
{
"textRaw": "`utilization` {number} The calculated ratio of `used` to `total` allocated bytes.",
"name": "utilization",
"type": "number",
"desc": "The calculated ratio of `used` to `total` allocated bytes."
}
]
}
}
]
},
{
"textRaw": "`crypto.setEngine(engine[, flags])`",
"name": "setEngine",
"type": "method",
"meta": {
"added": [
"v0.11.11"
],
"changes": [
{
"version": [
"v22.4.0",
"v20.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/53329",
"description": "Custom engine support in OpenSSL 3 is deprecated."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`engine` {string}",
"name": "engine",
"type": "string"
},
{
"textRaw": "`flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`",
"name": "flags",
"type": "crypto.constants",
"default": "`crypto.constants.ENGINE_METHOD_ALL`",
"optional": true
}
]
}
],
"desc": "Load and set the engine for some or all OpenSSL functions (selected by flags).\nSupport for custom engines in OpenSSL is deprecated from OpenSSL 3.
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\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants):
crypto.constants.ENGINE_METHOD_RSAcrypto.constants.ENGINE_METHOD_DSAcrypto.constants.ENGINE_METHOD_DHcrypto.constants.ENGINE_METHOD_RANDcrypto.constants.ENGINE_METHOD_ECcrypto.constants.ENGINE_METHOD_CIPHERScrypto.constants.ENGINE_METHOD_DIGESTScrypto.constants.ENGINE_METHOD_PKEY_METHScrypto.constants.ENGINE_METHOD_PKEY_ASN1_METHScrypto.constants.ENGINE_METHOD_ALLcrypto.constants.ENGINE_METHOD_NONEEnables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.
" }, { "textRaw": "`crypto.sign(algorithm, data, key[, callback])`", "name": "sign", "type": "method", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": "v24.8.0", "pr-url": "https://github.com/nodejs/node/pull/59570", "description": "Add support for ML-DSA, Ed448, and SLH-DSA context parameter." }, { "version": "v24.8.0", "pr-url": "https://github.com/nodejs/node/pull/59537", "description": "Add support for SLH-DSA signing." }, { "version": "v24.6.0", "pr-url": "https://github.com/nodejs/node/pull/59259", "description": "Add support for ML-DSA signing." }, { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37500", "description": "Optional callback argument added." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." } ] }, "signatures": [ { "params": [ { "textRaw": "`algorithm` {string|null|undefined}", "name": "algorithm", "type": "string|null|undefined" }, { "textRaw": "`data` {ArrayBuffer|Buffer|TypedArray|DataView}", "name": "data", "type": "ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`signature` {Buffer}", "name": "signature", "type": "Buffer" } ], "optional": true } ], "return": { "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", "name": "return", "type": "Buffer", "desc": "if the `callback` function is not provided." } } ], "desc": "Calculates and returns the signature for data using the given private key and\nalgorithm. If algorithm is null or undefined, then the algorithm is\ndependent upon the key type.
algorithm is required to be null or undefined for Ed25519, Ed448, and\nML-DSA.
If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey(). If it is an object, the following\nadditional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.
saltLength <integer> Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
context <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> For Ed448, ML-DSA, and SLH-DSA,\nthis option specifies the optional context to differentiate signatures generated\nfor different purposes with the same key.
If the callback function is provided this function uses libuv's threadpool.
This function compares the underlying bytes that represent the given\nArrayBuffer, TypedArray, or DataView instances using a constant-time\nalgorithm.
This function does not leak timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.
\na and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same byte length. An error is thrown if a and b have\ndifferent byte lengths.
If at least one of a and b is a TypedArray with more than one byte per\nentry, such as Uint16Array, the result will be computed using the platform\nbyte order.
When both of the inputs are Float32Arrays or\nFloat64Arrays, this function might return unexpected results due to IEEE 754\nencoding of floating-point numbers. In particular, neither x === y nor\nObject.is(x, y) implies that the byte representations of two floating-point\nnumbers x and y are equal.
Use of crypto.timingSafeEqual does not guarantee that the surrounding code\nis timing-safe. Care should be taken to ensure that the surrounding code does\nnot introduce timing vulnerabilities.
Verifies the given signature for data using the given key and algorithm. If\nalgorithm is null or undefined, then the algorithm is dependent upon the\nkey type.
algorithm is required to be null or undefined for Ed25519, Ed448, and\nML-DSA.
If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey(). If it is an object, the following\nadditional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.
saltLength <integer> Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
context <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> For Ed448, ML-DSA, and SLH-DSA,\nthis option specifies the optional context to differentiate signatures generated\nfor different purposes with the same key.
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\nkey may be passed for key.
If the callback function is provided this function uses libuv's threadpool.
An object containing commonly used constants for crypto and security related\noperations. The specific constants currently defined are described in\nCrypto constants.
" }, { "textRaw": "`crypto.fips`", "name": "fips", "type": "property", "meta": { "added": [ "v6.0.0" ], "changes": [], "deprecated": [ "v10.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "desc": "Property for checking and controlling whether a FIPS compliant crypto provider\nis currently in use. Setting to true requires a FIPS build of Node.js.
\nThis property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.
A convenient alias for crypto.webcrypto.subtle.
Type: <Crypto> An implementation of the Web Crypto API standard.
See the Web Crypto API documentation for details.
" } ], "displayName": "`node:crypto` module methods and properties" }, { "textRaw": "Notes", "name": "notes", "type": "module", "modules": [ { "textRaw": "Using strings as inputs to cryptographic APIs", "name": "using_strings_as_inputs_to_cryptographic_apis", "type": "module", "desc": "For historical reasons, many cryptographic APIs provided by Node.js accept\nstrings as inputs where the underlying cryptographic algorithm works on byte\nsequences. These instances include plaintexts, ciphertexts, symmetric keys,\ninitialization vectors, passphrases, salts, authentication tags,\nand additional authenticated data.
\nWhen passing strings to cryptographic APIs, consider the following factors.
\nNot all byte sequences are valid UTF-8 strings. Therefore, when a byte\nsequence of length n is derived from a string, its entropy is generally\nlower than the entropy of a random or pseudorandom n byte sequence.\nFor example, no UTF-8 string will result in the byte sequence c0 af. Secret\nkeys should almost exclusively be random or pseudorandom byte sequences.
Similarly, when converting random or pseudorandom byte sequences to UTF-8\nstrings, subsequences that do not represent valid code points may be replaced\nby the Unicode replacement character (U+FFFD). The byte representation of\nthe resulting Unicode string may, therefore, not be equal to the byte sequence\nthat the string was created from.
const original = [0xc0, 0xaf];\nconst bytesAsString = Buffer.from(original).toString('utf8');\nconst stringAsBytes = Buffer.from(bytesAsString, 'utf8');\nconsole.log(stringAsBytes);\n// Prints '<Buffer ef bf bd ef bf bd>'.\n\nThe outputs of ciphers, hash functions, signature algorithms, and key\nderivation functions are pseudorandom byte sequences and should not be\nused as Unicode strings.
\nWhen strings are obtained from user input, some Unicode characters can be\nrepresented in multiple equivalent ways that result in different byte\nsequences. For example, when passing a user passphrase to a key derivation\nfunction, such as PBKDF2 or scrypt, the result of the key derivation function\ndepends on whether the string uses composed or decomposed characters. Node.js\ndoes not normalize character representations. Developers should consider using\nString.prototype.normalize() on user inputs before passing them to\ncryptographic APIs.
The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data. As such, many crypto classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'latin1' encoded strings by default rather than Buffers. This\ndefault was changed in Node.js 0.9.3 to use Buffer objects by default\ninstead.
The node:crypto module still supports some algorithms which are already\ncompromised and are not recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are too weak for safe\nuse.
Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.
\nBased on the recommendations of NIST SP 800-131A:
\nmodp1, modp2 and modp5 have a key size\nsmaller than 2048 bits and are not recommended.See the reference for other recommendations and details.
\nSome algorithms that have known weaknesses and are of little relevance in\npractice are only available through the legacy provider, which is not\nenabled by default.
", "displayName": "Support for weak or compromised algorithms" }, { "textRaw": "CCM mode", "name": "ccm_mode", "type": "module", "desc": "CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:
\nauthTagLength option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.N must be between 7 and 13\nbytes (7 ≤ N ≤ 13).2 ** (8 * (15 - N)) bytes.setAuthTag() before\ncalling update().\nOtherwise, decryption will fail and final() will throw an error in\ncompliance with section 2.6 of RFC 3610.write(data), end(data) or pipe() in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.setAAD() via the plaintextLength\noption.\nMany crypto libraries include the authentication tag in the ciphertext,\nwhich means that they produce ciphertexts of the length\nplaintextLength + authTagLength. Node.js does not include the authentication\ntag, so the ciphertext length is always plaintextLength.\nThis is not necessary if no AAD is used.update() must be called exactly\nonce.update() is sufficient to encrypt/decrypt the message,\napplications must call final() to compute or verify the\nauthentication tag.import { Buffer } from 'node:buffer';\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} = await import('node:crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16,\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n plaintextLength: Buffer.byteLength(plaintext),\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16,\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n plaintextLength: ciphertext.length,\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n decipher.final();\n} catch (err) {\n throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n\nconst { Buffer } = require('node:buffer');\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} = require('node:crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16,\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n plaintextLength: Buffer.byteLength(plaintext),\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16,\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n plaintextLength: ciphertext.length,\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n decipher.final();\n} catch (err) {\n throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n",
"displayName": "CCM mode"
},
{
"textRaw": "FIPS mode",
"name": "fips_mode",
"type": "module",
"desc": "When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate\nOpenSSL 3 provider, such as the FIPS provider from OpenSSL 3 which can be\ninstalled by following the instructions in OpenSSL's FIPS README file.
\nFor FIPS support in Node.js you will need:
\nNode.js will need to be configured with an OpenSSL configuration file that\npoints to the FIPS provider. An example configuration file looks like this:
\nnodejs_conf = nodejs_init\n\n.include /<absolute path>/fipsmodule.cnf\n\n[nodejs_init]\nproviders = provider_sect\n\n[provider_sect]\ndefault = default_sect\n# The fips section name should match the section name inside the\n# included fipsmodule.cnf.\nfips = fips_sect\n\n[default_sect]\nactivate = 1\n\nwhere fipsmodule.cnf is the FIPS module configuration file generated from the\nFIPS provider installation step:
openssl fipsinstall\n\nSet the OPENSSL_CONF environment variable to point to\nyour configuration file and OPENSSL_MODULES to the location of the FIPS\nprovider dynamic library. e.g.
export OPENSSL_CONF=/<path to configuration file>/nodejs.cnf\nexport OPENSSL_MODULES=/<path to openssl lib>/ossl-modules\n\nFIPS mode can then be enabled in Node.js either by:
\n--enable-fips or --force-fips command line flags.crypto.setFips(true).Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration\nfile. e.g.
\nnodejs_conf = nodejs_init\n\n.include /<absolute path>/fipsmodule.cnf\n\n[nodejs_init]\nproviders = provider_sect\nalg_section = algorithm_sect\n\n[provider_sect]\ndefault = default_sect\n# The fips section name should match the section name inside the\n# included fipsmodule.cnf.\nfips = fips_sect\n\n[default_sect]\nactivate = 1\n\n[algorithm_sect]\ndefault_properties = fips=yes\n",
"displayName": "FIPS mode"
}
],
"displayName": "Notes"
},
{
"textRaw": "Crypto constants",
"name": "crypto_constants",
"type": "module",
"desc": "The following constants exported by crypto.constants apply to various uses of\nthe node:crypto, node:tls, and node:https modules and are generally\nspecific to OpenSSL.
See the list of SSL OP Flags for details.
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Constant | Description |
|---|---|
SSL_OP_ALL | Applies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html\n for detail. |
SSL_OP_ALLOW_NO_DHE_KEX | Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3 |
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION | Allows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html. |
SSL_OP_CIPHER_SERVER_PREFERENCE | Attempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html. |
SSL_OP_CISCO_ANYCONNECT | Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. |
SSL_OP_COOKIE_EXCHANGE | Instructs OpenSSL to turn on cookie exchange. |
SSL_OP_CRYPTOPRO_TLSEXT_BUG | Instructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft. |
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d. |
SSL_OP_LEGACY_SERVER_CONNECT | Allows initial connection to servers that do not support RI. |
SSL_OP_NO_COMPRESSION | Instructs OpenSSL to disable support for SSL/TLS compression. |
SSL_OP_NO_ENCRYPT_THEN_MAC | Instructs OpenSSL to disable encrypt-then-MAC. |
SSL_OP_NO_QUERY_MTU | |
SSL_OP_NO_RENEGOTIATION | Instructs OpenSSL to disable renegotiation. |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | Instructs OpenSSL to always start a new session when performing\n renegotiation. |
SSL_OP_NO_SSLv2 | Instructs OpenSSL to turn off SSL v2 |
SSL_OP_NO_SSLv3 | Instructs OpenSSL to turn off SSL v3 |
SSL_OP_NO_TICKET | Instructs OpenSSL to disable use of RFC4507bis tickets. |
SSL_OP_NO_TLSv1 | Instructs OpenSSL to turn off TLS v1 |
SSL_OP_NO_TLSv1_1 | Instructs OpenSSL to turn off TLS v1.1 |
SSL_OP_NO_TLSv1_2 | Instructs OpenSSL to turn off TLS v1.2 |
SSL_OP_NO_TLSv1_3 | Instructs OpenSSL to turn off TLS v1.3 |
SSL_OP_PRIORITIZE_CHACHA | Instructs OpenSSL server to prioritize ChaCha20-Poly1305\n when the client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled. |
SSL_OP_TLS_ROLLBACK_BUG | Instructs OpenSSL to disable version rollback attack detection. |
| Constant | Description |
|---|---|
ENGINE_METHOD_RSA | Limit engine usage to RSA |
ENGINE_METHOD_DSA | Limit engine usage to DSA |
ENGINE_METHOD_DH | Limit engine usage to DH |
ENGINE_METHOD_RAND | Limit engine usage to RAND |
ENGINE_METHOD_EC | Limit engine usage to EC |
ENGINE_METHOD_CIPHERS | Limit engine usage to CIPHERS |
ENGINE_METHOD_DIGESTS | Limit engine usage to DIGESTS |
ENGINE_METHOD_PKEY_METHS | Limit engine usage to PKEY_METHS |
ENGINE_METHOD_PKEY_ASN1_METHS | Limit engine usage to PKEY_ASN1_METHS |
ENGINE_METHOD_ALL | |
ENGINE_METHOD_NONE |
| Constant | Description |
|---|---|
DH_CHECK_P_NOT_SAFE_PRIME | |
DH_CHECK_P_NOT_PRIME | |
DH_UNABLE_TO_CHECK_GENERATOR | |
DH_NOT_SUITABLE_GENERATOR | |
RSA_PKCS1_PADDING | |
RSA_SSLV23_PADDING | |
RSA_NO_PADDING | |
RSA_PKCS1_OAEP_PADDING | |
RSA_X931_PADDING | |
RSA_PKCS1_PSS_PADDING | |
RSA_PSS_SALTLEN_DIGEST | Sets the salt length for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying. |
RSA_PSS_SALTLEN_MAX_SIGN | Sets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data. |
RSA_PSS_SALTLEN_AUTO | Causes the salt length for RSA_PKCS1_PSS_PADDING to be\n determined automatically when verifying a signature. |
POINT_CONVERSION_COMPRESSED | |
POINT_CONVERSION_UNCOMPRESSED | |
POINT_CONVERSION_HYBRID |
| Constant | Description |
|---|---|
defaultCoreCipherList | Specifies the built-in default cipher list used by Node.js. |
defaultCipherList | Specifies the active default cipher list used by the current Node.js\n process. |
SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.
<keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.
The node:crypto module provides the Certificate class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.
const { Certificate } = await import('node:crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n\nconst { Certificate } = require('node:crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n"
},
{
"textRaw": "Static method: `Certificate.exportPublicKey(spkac[, encoding])`",
"name": "exportPublicKey",
"type": "classMethod",
"meta": {
"added": [
"v9.0.0"
],
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "spkac",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`encoding` {string} The encoding of the `spkac` string.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the `spkac` string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.",
"name": "return",
"type": "Buffer",
"desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge."
}
}
],
"desc": "const { Certificate } = await import('node:crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n\nconst { Certificate } = require('node:crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n"
},
{
"textRaw": "Static method: `Certificate.verifySpkac(spkac[, encoding])`",
"name": "verifySpkac",
"type": "classMethod",
"meta": {
"added": [
"v9.0.0"
],
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The spkac argument can be an ArrayBuffer. Added encoding. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "spkac",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`encoding` {string} The encoding of the `spkac` string.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the `spkac` string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if the given `spkac` data structure is valid, `false` otherwise."
}
}
],
"desc": "import { Buffer } from 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n\nconst { Buffer } = require('node:buffer');\nconst { Certificate } = require('node:crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n"
}
],
"modules": [
{
"textRaw": "Legacy API",
"name": "legacy_api",
"type": "module",
"stability": 0,
"stabilityText": "Deprecated",
"desc": "As a legacy interface, it is possible to create new instances of\nthe crypto.Certificate class as illustrated in the examples below.
Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:
const { Certificate } = await import('node:crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n\nconst { Certificate } = require('node:crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n"
}
],
"methods": [
{
"textRaw": "`certificate.exportChallenge(spkac[, encoding])`",
"name": "exportChallenge",
"type": "method",
"meta": {
"added": [
"v0.11.8"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "spkac",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`encoding` {string} The encoding of the `spkac` string.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the `spkac` string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.",
"name": "return",
"type": "Buffer",
"desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge."
}
}
],
"desc": "const { Certificate } = await import('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n\nconst { Certificate } = require('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n"
},
{
"textRaw": "`certificate.exportPublicKey(spkac[, encoding])`",
"name": "exportPublicKey",
"type": "method",
"meta": {
"added": [
"v0.11.8"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "spkac",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`encoding` {string} The encoding of the `spkac` string.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the `spkac` string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.",
"name": "return",
"type": "Buffer",
"desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge."
}
}
],
"desc": "const { Certificate } = await import('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n\nconst { Certificate } = require('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n"
},
{
"textRaw": "`certificate.verifySpkac(spkac[, encoding])`",
"name": "verifySpkac",
"type": "method",
"meta": {
"added": [
"v0.11.8"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "spkac",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`encoding` {string} The encoding of the `spkac` string.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the `spkac` string.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if the given `spkac` data structure is valid, `false` otherwise."
}
}
],
"desc": "import { Buffer } from 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n\nconst { Buffer } = require('node:buffer');\nconst { Certificate } = require('node:crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n"
}
],
"displayName": "Legacy API"
}
]
},
{
"textRaw": "Class: `Cipheriv`",
"name": "Cipheriv",
"type": "class",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"desc": "<stream.Transform>Instances of the Cipheriv class are used to encrypt data. The class can be\nused in one of two ways:
cipher.update() and cipher.final() methods to produce\nthe encrypted data.The crypto.createCipheriv() method is\nused to create Cipheriv instances. Cipheriv objects are not to be created\ndirectly using the new keyword.
Example: Using Cipheriv objects as streams:
const {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n // Once we have the key and iv, we can create and use the cipher...\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = '';\n cipher.setEncoding('hex');\n\n cipher.on('data', (chunk) => encrypted += chunk);\n cipher.on('end', () => console.log(encrypted));\n\n cipher.write('some clear text data');\n cipher.end();\n });\n});\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n // Once we have the key and iv, we can create and use the cipher...\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = '';\n cipher.setEncoding('hex');\n\n cipher.on('data', (chunk) => encrypted += chunk);\n cipher.on('end', () => console.log(encrypted));\n\n cipher.write('some clear text data');\n cipher.end();\n });\n});\n\nExample: Using Cipheriv and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\n\nimport {\n pipeline,\n} from 'node:stream';\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n const input = createReadStream('test.js');\n const output = createWriteStream('test.enc');\n\n pipeline(input, cipher, output, (err) => {\n if (err) throw err;\n });\n });\n});\n\nconst {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\n\nconst {\n pipeline,\n} = require('node:stream');\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n const input = createReadStream('test.js');\n const output = createWriteStream('test.enc');\n\n pipeline(input, cipher, output, (err) => {\n if (err) throw err;\n });\n });\n});\n\nExample: Using the cipher.update() and cipher.final() methods:
const {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n encrypted += cipher.final('hex');\n console.log(encrypted);\n });\n});\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n encrypted += cipher.final('hex');\n console.log(encrypted);\n });\n});\n",
"methods": [
{
"textRaw": "`cipher.final([outputEncoding])`",
"name": "final",
"type": "method",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string} Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a `Buffer` is returned.",
"name": "return",
"type": "Buffer|string",
"desc": "Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a `Buffer` is returned."
}
}
],
"desc": "Once the cipher.final() method has been called, the Cipheriv object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.
The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.
If the authTagLength option was set during the cipher instance's creation,\nthis function will return exactly authTagLength bytes.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
The plaintextLength option is optional for GCM and OCB. When using CCM,\nthe plaintextLength option must be specified and its value must match the\nlength of the plaintext in bytes. See CCM mode.
The cipher.setAAD() method must be called before cipher.update().
When using block encryption algorithms, the Cipheriv class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).
When autoPadding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or cipher.final() will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing 0x0 instead of PKCS padding.
The cipher.setAutoPadding() method must be called before\ncipher.final().
Updates the cipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer, TypedArray, or\nDataView. If data is a Buffer, TypedArray, or DataView, then\ninputEncoding is ignored.
The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.
The cipher.update() method can be called multiple times with new data until\ncipher.final() is called. Calling cipher.update() after\ncipher.final() will result in an error being thrown.
<stream.Transform>Instances of the Decipheriv class are used to decrypt data. The class can be\nused in one of two ways:
decipher.update() and decipher.final() methods to\nproduce the unencrypted data.The crypto.createDecipheriv() method is\nused to create Decipheriv instances. Decipheriv objects are not to be created\ndirectly using the new keyword.
Example: Using Decipheriv objects as streams:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n\nExample: Using Decipheriv and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\nimport { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nconst input = createReadStream('test.enc');\nconst output = createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n\nconst {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nconst input = createReadStream('test.enc');\nconst output = createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n\nExample: Using the decipher.update() and decipher.final() methods:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n",
"methods": [
{
"textRaw": "`decipher.final([outputEncoding])`",
"name": "final",
"type": "method",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string} Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a `Buffer` is returned.",
"name": "return",
"type": "Buffer|string",
"desc": "Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a `Buffer` is returned."
}
}
],
"desc": "Once the decipher.final() method has been called, the Decipheriv object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
The options argument is optional for GCM. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the ciphertext in bytes. See CCM mode.
The decipher.setAAD() method must be called before decipher.update().
When passing a string as the buffer, please consider\ncaveats when using strings as inputs to cryptographic APIs.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the decipher.setAuthTag() method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final() will throw, indicating that the\ncipher text should be discarded due to failed authentication. If the tag length\nis invalid according to NIST SP 800-38D or does not match the value of the\nauthTagLength option, decipher.setAuthTag() will throw an error.
The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes and\nchacha20-poly1305.\ndecipher.setAuthTag() can only be called once.
Because the node:crypto module was originally designed to closely mirror\nOpenSSL's behavior, this function permits short GCM authentication tags unless\nan explicit authentication tag length was passed to\ncrypto.createDecipheriv() when the decipher object was created. This\nbehavior is deprecated and subject to change (see DEP0182). \nIn the meantime, applications should either set the authTagLength option when\ncalling createDecipheriv() or check the actual\nauthentication tag length before passing it to setAuthTag().
When passing a string as the authentication tag, please consider\ncaveats when using strings as inputs to cryptographic APIs.
" }, { "textRaw": "`decipher.setAutoPadding([autoPadding])`", "name": "setAutoPadding", "type": "method", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`", "optional": true } ], "return": { "textRaw": "Returns: {Decipheriv} The same Decipher for method chaining.", "name": "return", "type": "Decipheriv", "desc": "The same Decipher for method chaining." } } ], "desc": "When data has been encrypted without standard block padding, calling\ndecipher.setAutoPadding(false) will disable automatic padding to prevent\ndecipher.final() from checking for and removing padding.
Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.
\nThe decipher.setAutoPadding() method must be called before\ndecipher.final().
Updates the decipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then inputEncoding is ignored.
The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.
The decipher.update() method can be called multiple times with new data until\ndecipher.final() is called. Calling decipher.update() after\ndecipher.final() will result in an error being thrown.
Even if the underlying cipher implements authentication, the authenticity and\nintegrity of the plaintext returned from this function may be uncertain at this\ntime. For authenticated encryption algorithms, authenticity is generally only\nestablished when the application calls decipher.final().
The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.
Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.
import assert from 'node:assert';\n\nconst {\n createDiffieHellman,\n} = await import('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n\nconst assert = require('node:assert');\n\nconst {\n createDiffieHellman,\n} = require('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n",
"methods": [
{
"textRaw": "`diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`",
"name": "computeSecret",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "otherPublicKey",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`inputEncoding` {string} The encoding of an `otherPublicKey` string.",
"name": "inputEncoding",
"type": "string",
"desc": "The encoding of an `otherPublicKey` string.",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding, and secret is\nencoded using specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer,\nTypedArray, or DataView.
If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.
Generates private and public Diffie-Hellman key values unless they have been\ngenerated or computed already, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party.\nIf encoding is provided a string is returned; otherwise a\nBuffer is returned.
This function is a thin wrapper around DH_generate_key(). In particular,\nonce a private key has been generated or set, calling this function only updates\nthe public key but does not generate a new private key.
Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
Sets the Diffie-Hellman private key. If the encoding argument is provided,\nprivateKey is expected\nto be a string. If no encoding is provided, privateKey is expected\nto be a Buffer, TypedArray, or DataView.
This function does not automatically compute the associated public key. Either\ndiffieHellman.setPublicKey() or diffieHellman.generateKeys() can be\nused to manually provide the public key or to automatically derive it.
Sets the Diffie-Hellman public key. If the encoding argument is provided,\npublicKey is expected\nto be a string. If no encoding is provided, publicKey is expected\nto be a Buffer, TypedArray, or DataView.
A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.
The following values are valid for this property (as defined in node:constants module):
DH_CHECK_P_NOT_SAFE_PRIMEDH_CHECK_P_NOT_PRIMEDH_UNABLE_TO_CHECK_GENERATORDH_NOT_SUITABLE_GENERATORThe DiffieHellmanGroup class takes a well-known modp group as its argument.\nIt works the same as DiffieHellman, except that it does not allow changing\nits keys after creation. In other words, it does not implement setPublicKey()\nor setPrivateKey() methods.
const { createDiffieHellmanGroup } = await import('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n\nconst { createDiffieHellmanGroup } = require('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n\nThe following groups are supported:
\n'modp14' (2048 bits, RFC 3526 Section 3)'modp15' (3072 bits, RFC 3526 Section 4)'modp16' (4096 bits, RFC 3526 Section 5)'modp17' (6144 bits, RFC 3526 Section 6)'modp18' (8192 bits, RFC 3526 Section 7)The following groups are still supported but deprecated (see Caveats):
\n'modp1' (768 bits, RFC 2409 Section 6.1) 'modp2' (1024 bits, RFC 2409 Section 6.2) 'modp5' (1536 bits, RFC 3526 Section 2) These deprecated groups might be removed in future versions of Node.js.
" }, { "textRaw": "Class: `ECDH`", "name": "ECDH", "type": "class", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.
Instances of the ECDH class can be created using the\ncrypto.createECDH() function.
import assert from 'node:assert';\n\nconst {\n createECDH,\n} = await import('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n\nconst assert = require('node:assert');\n\nconst {\n createECDH,\n} = require('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n",
"classMethods": [
{
"textRaw": "Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`",
"name": "convertKey",
"type": "classMethod",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "key",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`curve` {string}",
"name": "curve",
"type": "string"
},
{
"textRaw": "`inputEncoding` {string} The encoding of the `key` string.",
"name": "inputEncoding",
"type": "string",
"desc": "The encoding of the `key` string.",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
},
{
"textRaw": "`format` {string} **Default:** `'uncompressed'`",
"name": "format",
"type": "string",
"default": "`'uncompressed'`",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Converts the EC Diffie-Hellman public key specified by key and curve to the\nformat specified by format. The format argument specifies point encoding\nand can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is\ninterpreted using the specified inputEncoding, and the returned key is encoded\nusing the specified outputEncoding.
Use crypto.getCurves() to obtain a list of available curve names.\nOn recent OpenSSL releases, openssl ecparam -list_curves will also display\nthe name and description of each available elliptic curve.
If format is not specified the point will be returned in 'uncompressed'\nformat.
If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.
Example (uncompressing a key):
\nconst {\n createECDH,\n ECDH,\n} = await import('node:crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n\nconst {\n createECDH,\n ECDH,\n} = require('node:crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n"
}
],
"methods": [
{
"textRaw": "`ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`",
"name": "computeSecret",
"type": "method",
"meta": {
"added": [
"v0.11.14"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/16849",
"description": "Changed error format to better support invalid public key error."
},
{
"version": "v6.0.0",
"pr-url": "https://github.com/nodejs/node/pull/5522",
"description": "The default `inputEncoding` changed from `binary` to `utf8`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}",
"name": "otherPublicKey",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView"
},
{
"textRaw": "`inputEncoding` {string} The encoding of the `otherPublicKey` string.",
"name": "inputEncoding",
"type": "string",
"desc": "The encoding of the `otherPublicKey` string.",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding, and the returned secret\nis encoded using the specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer, TypedArray, or\nDataView.
If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.
ecdh.computeSecret will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey\nlies outside of the elliptic curve. Since otherPublicKey is\nusually supplied from a remote user over an insecure network,\nbe sure to handle this exception accordingly.
Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format and encoding. This key should be\ntransferred to the other party.
The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified, the point will be returned in\n'uncompressed' format.
If encoding is provided a string is returned; otherwise a Buffer\nis returned.
If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.
The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified the point will be returned in\n'uncompressed' format.
If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.
Sets the EC Diffie-Hellman private key.\nIf encoding is provided, privateKey is expected\nto be a string; otherwise privateKey is expected to be a Buffer,\nTypedArray, or DataView.
If privateKey is not valid for the curve specified when the ECDH object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.
Sets the EC Diffie-Hellman public key.\nIf encoding is provided publicKey is expected to\nbe a string; otherwise a Buffer, TypedArray, or DataView is expected.
There is not normally a reason to call this method because ECDH\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys() or\necdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method\nattempts to generate the public point/key associated with the private key being\nset.
Example (obtaining a shared secret):
\nconst {\n createECDH,\n createHash,\n} = await import('node:crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n createHash('sha256').update('alice', 'utf8').digest(),\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n\nconst {\n createECDH,\n createHash,\n} = require('node:crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n createHash('sha256').update('alice', 'utf8').digest(),\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n"
}
]
},
{
"textRaw": "Class: `Hash`",
"name": "Hash",
"type": "class",
"meta": {
"added": [
"v0.1.92"
],
"changes": []
},
"desc": "<stream.Transform>The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:
hash.update() and hash.digest() methods to produce the\ncomputed hash.The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.
Example: Using Hash objects as streams:
const {\n createHash,\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hash.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n }\n});\n\nhash.write('some data to hash');\nhash.end();\n\nconst {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hash.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n }\n});\n\nhash.write('some data to hash');\nhash.end();\n\nExample: Using Hash and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst { createHash } = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n\nconst { createReadStream } = require('node:fs');\nconst { createHash } = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n\nExample: Using the hash.update() and hash.digest() methods:
const {\n createHash,\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n\nconst {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n",
"methods": [
{
"textRaw": "`hash.copy([options])`",
"name": "copy",
"type": "method",
"meta": {
"added": [
"v13.1.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} `stream.transform` options",
"name": "options",
"type": "Object",
"desc": "`stream.transform` options",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Hash}",
"name": "return",
"type": "Hash"
}
}
],
"desc": "Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.
The optional options argument controls stream behavior. For XOF hash\nfunctions such as 'shake256', the outputLength option can be used to\nspecify the desired output length in bytes.
An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.
// Calculate a rolling hash.\nconst {\n createHash,\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n\n// Calculate a rolling hash.\nconst {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n"
},
{
"textRaw": "`hash.digest([encoding])`",
"name": "digest",
"type": "method",
"meta": {
"added": [
"v0.1.92"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`encoding` {string} The encoding of the return value.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method).\nIf encoding is provided a string will be returned; otherwise\na Buffer is returned.
The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.
Updates the hash content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
" } ] }, { "textRaw": "Class: `Hmac`", "name": "Hmac", "type": "class", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "<stream.Transform>The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:
hmac.update() and hmac.digest() methods to produce the\ncomputed HMAC digest.The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.
Example: Using Hmac objects as streams:
const {\n createHmac,\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hmac.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n\nconst {\n createHmac,\n} = require('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hmac.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n\nExample: Using Hmac and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst {\n createHmac,\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n\nExample: Using the hmac.update() and hmac.digest() methods:
const {\n createHmac,\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n\nconst {\n createHmac,\n} = require('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n",
"methods": [
{
"textRaw": "`hmac.digest([encoding])`",
"name": "digest",
"type": "method",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`encoding` {string} The encoding of the return value.",
"name": "encoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Calculates the HMAC digest of all of the data passed using hmac.update().\nIf encoding is\nprovided a string is returned; otherwise a Buffer is returned;
The Hmac object can not be used again after hmac.digest() has been\ncalled. Multiple calls to hmac.digest() will result in an error being thrown.
Updates the Hmac content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
" } ] }, { "textRaw": "Class: `KeyObject`", "name": "KeyObject", "type": "class", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v24.6.0", "pr-url": "https://github.com/nodejs/node/pull/59259", "description": "Add support for ML-DSA keys." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33360", "description": "Instances of this class can now be passed to worker threads using `postMessage`." }, { "version": "v11.13.0", "pr-url": "https://github.com/nodejs/node/pull/26438", "description": "This class is now exported." } ] }, "desc": "Node.js uses a KeyObject class to represent a symmetric or asymmetric key,\nand each kind of key exposes different functions. The\ncrypto.createSecretKey(), crypto.createPublicKey() and\ncrypto.createPrivateKey() methods are used to create KeyObject\ninstances. KeyObject objects are not to be created directly using the new\nkeyword.
Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.
KeyObject instances can be passed to other threads via postMessage().\nThe receiver obtains a cloned KeyObject, and the KeyObject does not need to\nbe listed in the transferList argument.
Example: Converting a CryptoKey instance to a KeyObject:
const { KeyObject } = await import('node:crypto');\nconst { subtle } = globalThis.crypto;\n\nconst key = await subtle.generateKey({\n name: 'HMAC',\n hash: 'SHA-256',\n length: 256,\n}, true, ['sign', 'verify']);\n\nconst keyObject = KeyObject.from(key);\nconsole.log(keyObject.symmetricKeySize);\n// Prints: 32 (symmetric key size in bytes)\n\nconst { KeyObject } = require('node:crypto');\nconst { subtle } = globalThis.crypto;\n\n(async function() {\n const key = await subtle.generateKey({\n name: 'HMAC',\n hash: 'SHA-256',\n length: 256,\n }, true, ['sign', 'verify']);\n\n const keyObject = KeyObject.from(key);\n console.log(keyObject.symmetricKeySize);\n // Prints: 32 (symmetric key size in bytes)\n})();\n"
}
],
"properties": [
{
"textRaw": "Type: {Object}",
"name": "asymmetricKeyDetails",
"type": "Object",
"meta": {
"added": [
"v15.7.0"
],
"changes": [
{
"version": "v16.9.0",
"pr-url": "https://github.com/nodejs/node/pull/39851",
"description": "Expose `RSASSA-PSS-params` sequence parameters for RSA-PSS keys."
}
]
},
"desc": "This property exists only on asymmetric keys. Depending on the type of the key,\nthis object contains information about the key. None of the information obtained\nthrough this property can be used to uniquely identify a key or to compromise\nthe security of the key.
\nFor RSA-PSS keys, if the key material contains a RSASSA-PSS-params sequence,\nthe hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be\nset.
Other key details might be exposed via this API using additional attributes.
", "options": [ { "textRaw": "`modulusLength` {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent` {bigint} Public exponent (RSA).", "name": "publicExponent", "type": "bigint", "desc": "Public exponent (RSA)." }, { "textRaw": "`hashAlgorithm` {string} Name of the message digest (RSA-PSS).", "name": "hashAlgorithm", "type": "string", "desc": "Name of the message digest (RSA-PSS)." }, { "textRaw": "`mgf1HashAlgorithm` {string} Name of the message digest used by MGF1 (RSA-PSS).", "name": "mgf1HashAlgorithm", "type": "string", "desc": "Name of the message digest used by MGF1 (RSA-PSS)." }, { "textRaw": "`saltLength` {number} Minimal salt length in bytes (RSA-PSS).", "name": "saltLength", "type": "number", "desc": "Minimal salt length in bytes (RSA-PSS)." }, { "textRaw": "`divisorLength` {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve` {string} Name of the curve (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve (EC)." } ] }, { "textRaw": "Type: {string}", "name": "asymmetricKeyType", "type": "string", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v24.8.0", "pr-url": "https://github.com/nodejs/node/pull/59537", "description": "Add support for SLH-DSA keys." }, { "version": "v24.7.0", "pr-url": "https://github.com/nodejs/node/pull/59461", "description": "Add support for ML-KEM keys." }, { "version": "v24.6.0", "pr-url": "https://github.com/nodejs/node/pull/59259", "description": "Add support for ML-DSA keys." }, { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Added support for `'dh'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26960", "description": "Added support for `'rsa-pss'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26786", "description": "This property now returns `undefined` for KeyObject instances of unrecognized type instead of aborting." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26774", "description": "Added support for `'x25519'` and `'x448'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26319", "description": "Added support for `'ed25519'` and `'ed448'`." } ] }, "desc": "For asymmetric keys, this property represents the type of the key. See the\nsupported asymmetric key types.
\nThis property is undefined for unrecognized KeyObject types and symmetric\nkeys.
For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.
Depending on the type of this KeyObject, this property is either\n'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys\nor 'private' for private (asymmetric) keys.
Returns true or false depending on whether the keys have exactly the same\ntype, value, and parameters. This method is not\nconstant time.
For symmetric keys, the following encoding options can be used:
\nformat <string> Must be 'buffer' (default) or 'jwk'.For public keys, the following encoding options can be used:
\ntype <string> Must be one of 'pkcs1' (RSA only) or 'spki'.format <string> Must be 'pem', 'der', or 'jwk'.For private keys, the following encoding options can be used:
\ntype <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or\n'sec1' (EC only).format <string> Must be 'pem', 'der', or 'jwk'.cipher <string> If specified, the private key will be encrypted with\nthe given cipher and passphrase using PKCS#5 v2.0 password based\nencryption.passphrase <string> | <Buffer> The passphrase to use for encryption, see cipher.The result type depends on the selected encoding format, when PEM the\nresult is a string, when DER it will be a buffer containing the data\nencoded as DER, when JWK it will be an object.
\nWhen JWK encoding format was selected, all other encoding options are\nignored.
\nPKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of\nthe cipher and format options. The PKCS#8 type can be used with any\nformat to encrypt any key algorithm (RSA, EC, or DH) by specifying a\ncipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher\nwhen the PEM format is used. For maximum compatibility, use PKCS#8 for\nencrypted private keys. Since PKCS#8 defines its own\nencryption mechanism, PEM-level encryption is not supported when encrypting\na PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for\nPKCS#1 and SEC1 encryption.
extractable <boolean>keyUsages <string[]> See Key usages.<CryptoKey>Converts a KeyObject instance to a CryptoKey.
<stream.Writable>The Sign class is a utility for generating signatures. It can be used in one\nof two ways:
sign.sign() method is used to generate and return the signature, orsign.update() and sign.sign() methods to produce the\nsignature.The crypto.createSign() method is used to create Sign instances. The\nargument is the string name of the hash function to use. Sign objects are not\nto be created directly using the new keyword.
Example: Using Sign and Verify objects as streams:
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = await import('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n namedCurve: 'sect239k1',\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n\nconst {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n namedCurve: 'sect239k1',\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n\nExample: Using the sign.update() and verify.update() methods:
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = await import('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n\nconst {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n",
"methods": [
{
"textRaw": "`sign.sign(privateKey[, outputEncoding])`",
"name": "sign",
"type": "method",
"meta": {
"added": [
"v0.1.92"
],
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/35093",
"description": "The privateKey can also be an ArrayBuffer and CryptoKey."
},
{
"version": [
"v13.2.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/29292",
"description": "This function now supports IEEE-P1363 DSA and ECDSA signatures."
},
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/26960",
"description": "This function now supports RSA-PSS keys."
},
{
"version": "v11.6.0",
"pr-url": "https://github.com/nodejs/node/pull/24234",
"description": "This function now supports key objects."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/11705",
"description": "Support for RSASSA-PSS and additional options was added."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}",
"name": "privateKey",
"type": "Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey",
"options": [
{
"textRaw": "`dsaEncoding` {string}",
"name": "dsaEncoding",
"type": "string"
},
{
"textRaw": "`padding` {integer}",
"name": "padding",
"type": "integer"
},
{
"textRaw": "`saltLength` {integer}",
"name": "saltLength",
"type": "integer"
}
]
},
{
"textRaw": "`outputEncoding` {string} The encoding of the return value.",
"name": "outputEncoding",
"type": "string",
"desc": "The encoding of the return value.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Buffer|string}",
"name": "return",
"type": "Buffer|string"
}
}
],
"desc": "Calculates the signature on all the data passed through using either\nsign.update() or sign.write().
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the following additional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
saltLength <integer> Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.
The Sign object can not be again used after sign.sign() method has been\ncalled. Multiple calls to sign.sign() will result in an error being thrown.
Updates the Sign content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
" } ] }, { "textRaw": "Class: `Verify`", "name": "Verify", "type": "class", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "<stream.Writable>The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:
verify.update() and verify.verify() methods to verify\nthe signature.The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.
See Sign for examples.
Updates the Verify content with the given data, the encoding of which\nis given in inputEncoding.\nIf inputEncoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
" }, { "textRaw": "`verify.verify(object, signature[, signatureEncoding])`", "name": "verify", "type": "method", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The object can also be an ArrayBuffer and CryptoKey." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26960", "description": "This function now supports RSA-PSS keys." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25217", "description": "The key can now be a private key." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "params": [ { "textRaw": "`object` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "object", "type": "Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey", "options": [ { "textRaw": "`dsaEncoding` {string}", "name": "dsaEncoding", "type": "string" }, { "textRaw": "`padding` {integer}", "name": "padding", "type": "integer" }, { "textRaw": "`saltLength` {integer}", "name": "saltLength", "type": "integer" } ] }, { "textRaw": "`signature` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "signature", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`signatureEncoding` {string} The encoding of the `signature` string.", "name": "signatureEncoding", "type": "string", "desc": "The encoding of the `signature` string.", "optional": true } ], "return": { "textRaw": "Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key.", "name": "return", "type": "boolean", "desc": "`true` or `false` depending on the validity of the signature for the data and public key." } } ], "desc": "Verifies the provided data using the given object and signature.
If object is not a KeyObject, this function behaves as if\nobject had been passed to crypto.createPublicKey(). If it is an\nobject, the following additional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
saltLength <integer> Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be\ndetermined automatically.
The signature argument is the previously calculated signature for the data, in\nthe signatureEncoding.\nIf a signatureEncoding is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer,\nTypedArray, or DataView.
The verify object can not be used again after verify.verify() has been\ncalled. Multiple calls to verify.verify() will result in an error being\nthrown.
Because public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
" } ] }, { "textRaw": "Class: `X509Certificate`", "name": "X509Certificate", "type": "class", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "Encapsulates an X509 certificate and provides read-only access to\nits information.
\nconst { X509Certificate } = await import('node:crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n\nconst { X509Certificate } = require('node:crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n",
"signatures": [
{
"textRaw": "`new X509Certificate(buffer)`",
"name": "X509Certificate",
"type": "ctor",
"meta": {
"added": [
"v15.6.0"
],
"changes": []
},
"params": [
{
"textRaw": "`buffer` {string|TypedArray|Buffer|DataView} A PEM or DER encoded X509 Certificate.",
"name": "buffer",
"type": "string|TypedArray|Buffer|DataView",
"desc": "A PEM or DER encoded X509 Certificate."
}
]
}
],
"properties": [
{
"textRaw": "Type: {boolean} Will be `true` if this is a Certificate Authority (CA) certificate.",
"name": "ca",
"type": "boolean",
"meta": {
"added": [
"v15.6.0"
],
"changes": []
},
"desc": "Will be `true` if this is a Certificate Authority (CA) certificate."
},
{
"textRaw": "Type: {string}",
"name": "fingerprint",
"type": "string",
"meta": {
"added": [
"v15.6.0"
],
"changes": []
},
"desc": "The SHA-1 fingerprint of this certificate.
\nBecause SHA-1 is cryptographically broken and because the security of SHA-1 is\nsignificantly worse than that of algorithms that are commonly used to sign\ncertificates, consider using x509.fingerprint256 instead.
The SHA-256 fingerprint of this certificate.
" }, { "textRaw": "Type: {string}", "name": "fingerprint512", "type": "string", "meta": { "added": [ "v17.2.0", "v16.14.0" ], "changes": [] }, "desc": "The SHA-512 fingerprint of this certificate.
\nBecause computing the SHA-256 fingerprint is usually faster and because it is\nonly half the size of the SHA-512 fingerprint, x509.fingerprint256 may be\na better choice. While SHA-512 presumably provides a higher level of security in\ngeneral, the security of SHA-256 matches that of most algorithms that are\ncommonly used to sign certificates.
A textual representation of the certificate's authority information access\nextension.
\nThis is a line feed separated list of access descriptions. Each line begins with\nthe access method and the kind of the access location, followed by a colon and\nthe value associated with the access location.
\nAfter the prefix denoting the access method and the kind of the access location,\nthe remainder of each line might be enclosed in quotes to indicate that the\nvalue is a JSON string literal. For backward compatibility, Node.js only uses\nJSON string literals within this property when necessary to avoid ambiguity.\nThird-party code should be prepared to handle both possible entry formats.
" }, { "textRaw": "Type: {string}", "name": "issuer", "type": "string", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "The issuer identification included in this certificate.
" }, { "textRaw": "Type: {X509Certificate}", "name": "issuerCertificate", "type": "X509Certificate", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "desc": "The issuer certificate or undefined if the issuer certificate is not\navailable.
An array detailing the key extended usages for this certificate.
" }, { "textRaw": "Type: {KeyObject}", "name": "publicKey", "type": "KeyObject", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "The public key <KeyObject> for this certificate.
A Buffer containing the DER encoding of this certificate.
The serial number of this certificate.
\nSerial numbers are assigned by certificate authorities and do not uniquely\nidentify certificates. Consider using x509.fingerprint256 as a unique\nidentifier instead.
The complete subject of this certificate.
" }, { "textRaw": "Type: {string}", "name": "subjectAltName", "type": "string", "meta": { "added": [ "v15.6.0" ], "changes": [ { "version": [ "v17.3.1", "v16.13.2" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/300", "description": "Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532." } ] }, "desc": "The subject alternative name specified for this certificate.
\nThis is a comma-separated list of subject alternative names. Each entry begins\nwith a string identifying the kind of the subject alternative name followed by\na colon and the value associated with the entry.
\nEarlier versions of Node.js incorrectly assumed that it is safe to split this\nproperty at the two-character sequence ', ' (see CVE-2021-44532). However,\nboth malicious and legitimate certificates can contain subject alternative names\nthat include this sequence when represented as a string.
After the prefix denoting the type of the entry, the remainder of each entry\nmight be enclosed in quotes to indicate that the value is a JSON string literal.\nFor backward compatibility, Node.js only uses JSON string literals within this\nproperty when necessary to avoid ambiguity. Third-party code should be prepared\nto handle both possible entry formats.
" }, { "textRaw": "Type: {string}", "name": "validFrom", "type": "string", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "The date/time from which this certificate is valid.
" }, { "textRaw": "Type: {Date}", "name": "validFromDate", "type": "Date", "meta": { "added": [ "v23.0.0", "v22.10.0" ], "changes": [] }, "desc": "The date/time from which this certificate is valid, encapsulated in a Date object.
The date/time until which this certificate is valid.
" }, { "textRaw": "Type: {Date}", "name": "validToDate", "type": "Date", "meta": { "added": [ "v23.0.0", "v22.10.0" ], "changes": [] }, "desc": "The date/time until which this certificate is valid, encapsulated in a Date object.
The algorithm used to sign the certificate or undefined if the signature algorithm is unknown by OpenSSL.
The OID of the algorithm used to sign the certificate.
" } ], "methods": [ { "textRaw": "`x509.checkEmail(email[, options])`", "name": "checkEmail", "type": "method", "meta": { "added": [ "v15.6.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41600", "description": "The subject option now defaults to `'default'`." }, { "version": [ "v17.5.0", "v16.14.1" ], "pr-url": "https://github.com/nodejs/node/pull/41599", "description": "The `wildcards`, `partialWildcards`, `multiLabelWildcards`, and `singleLabelSubdomains` options have been removed since they had no effect." }, { "version": [ "v17.5.0", "v16.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/41569", "description": "The subject option can now be set to `'default'`." } ] }, "signatures": [ { "params": [ { "textRaw": "`email` {string}", "name": "email", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'default'`, `'always'`, or `'never'`. **Default:** `'default'`.", "name": "subject", "type": "string", "default": "`'default'`", "desc": "`'default'`, `'always'`, or `'never'`." } ], "optional": true } ], "return": { "textRaw": "Returns: {string|undefined} Returns `email` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `email` if the certificate matches, `undefined` if it does not." } } ], "desc": "Checks whether the certificate matches the given email address.
\nIf the 'subject' option is undefined or set to 'default', the certificate\nsubject is only considered if the subject alternative name extension either does\nnot exist or does not contain any email addresses.
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching email\naddress, the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never\nconsidered, even if the certificate contains no subject alternative names.
Checks whether the certificate matches the given host name.
\nIf the certificate matches the given host name, the matching subject name is\nreturned. The returned name might be an exact match (e.g., foo.example.com)\nor it might contain wildcards (e.g., *.example.com). Because host name\ncomparisons are case-insensitive, the returned subject name might also differ\nfrom the given name in capitalization.
If the 'subject' option is undefined or set to 'default', the certificate\nsubject is only considered if the subject alternative name extension either does\nnot exist or does not contain any DNS names. This behavior is consistent with\nRFC 2818 (\"HTTP Over TLS\").
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching DNS name,\nthe certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never\nconsidered, even if the certificate contains no subject alternative names.
Checks whether the certificate matches the given IP address (IPv4 or IPv6).
\nOnly RFC 5280 iPAddress subject alternative names are considered, and they\nmust match the given ip address exactly. Other subject alternative names as\nwell as the subject field of the certificate are ignored.
Checks whether this certificate was potentially issued by the given otherCert\nby comparing the certificate metadata.
This is useful for pruning a list of possible issuer certificates which have been\nselected using a more rudimentary filtering routine, i.e. just based on subject\nand issuer names.
\nFinally, to verify that this certificate's signature was produced by a private key\ncorresponding to otherCert's public key use x509.verify(publicKey)\nwith otherCert's public key represented as a KeyObject\nlike so
if (!x509.verify(otherCert.publicKey)) {\n throw new Error('otherCert did not issue x509');\n}\n"
},
{
"textRaw": "`x509.checkPrivateKey(privateKey)`",
"name": "checkPrivateKey",
"type": "method",
"meta": {
"added": [
"v15.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`privateKey` {KeyObject} A private key.",
"name": "privateKey",
"type": "KeyObject",
"desc": "A private key."
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Checks whether the public key for this certificate is consistent with\nthe given private key.
" }, { "textRaw": "`x509.toJSON()`", "name": "toJSON", "type": "method", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "There is no standard JSON encoding for X509 certificates. The\ntoJSON() method returns a string containing the PEM encoded\ncertificate.
Returns information about this certificate using the legacy\ncertificate object encoding.
" }, { "textRaw": "`x509.toString()`", "name": "toString", "type": "method", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Returns the PEM-encoded certificate.
" }, { "textRaw": "`x509.verify(publicKey)`", "name": "verify", "type": "method", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`publicKey` {KeyObject} A public key.", "name": "publicKey", "type": "KeyObject", "desc": "A public key." } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "Verifies that this certificate was signed by the given public key.\nDoes not perform any other validation checks on the certificate.
" } ] } ], "displayName": "Crypto", "source": "doc/api/crypto.md" }, { "textRaw": "Diagnostics Channel", "name": "diagnostics_channel", "introduced_in": "v15.1.0", "type": "module", "meta": { "added": [ "v15.1.0", "v14.17.0" ], "changes": [ { "version": [ "v19.2.0", "v18.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/45290", "description": "diagnostics_channel is now Stable." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "The node:diagnostics_channel module provides an API to create named channels\nto report arbitrary message data for diagnostics purposes.
It can be accessed using:
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nIt is intended that a module writer wanting to report diagnostics messages\nwill create one or many top-level channels to report messages through.\nChannels may also be acquired at runtime but it is not encouraged\ndue to the additional overhead of doing so. Channels may be exported for\nconvenience, but as long as the name is known it can be acquired anywhere.
\nIf you intend for your module to produce diagnostics data for others to\nconsume it is recommended that you include documentation of what named\nchannels are used along with the shape of the message data. Channel names\nshould generally include the module name to avoid collisions with data from\nother modules.
", "modules": [ { "textRaw": "Public API", "name": "public_api", "type": "module", "modules": [ { "textRaw": "Overview", "name": "overview", "type": "module", "desc": "Following is a simple overview of the public API.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\n// Get a reusable channel object\nconst channel = diagnostics_channel.channel('my-channel');\n\nfunction onMessage(message, name) {\n // Received data\n}\n\n// Subscribe to the channel\ndiagnostics_channel.subscribe('my-channel', onMessage);\n\n// Check if the channel has an active subscriber\nif (channel.hasSubscribers) {\n // Publish data to the channel\n channel.publish({\n some: 'data',\n });\n}\n\n// Unsubscribe from the channel\ndiagnostics_channel.unsubscribe('my-channel', onMessage);\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\n// Get a reusable channel object\nconst channel = diagnostics_channel.channel('my-channel');\n\nfunction onMessage(message, name) {\n // Received data\n}\n\n// Subscribe to the channel\ndiagnostics_channel.subscribe('my-channel', onMessage);\n\n// Check if the channel has an active subscriber\nif (channel.hasSubscribers) {\n // Publish data to the channel\n channel.publish({\n some: 'data',\n });\n}\n\n// Unsubscribe from the channel\ndiagnostics_channel.unsubscribe('my-channel', onMessage);\n",
"methods": [
{
"textRaw": "`diagnostics_channel.hasSubscribers(name)`",
"name": "hasSubscribers",
"type": "method",
"meta": {
"added": [
"v15.1.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string|symbol} The channel name",
"name": "name",
"type": "string|symbol",
"desc": "The channel name"
}
],
"return": {
"textRaw": "Returns: {boolean} If there are active subscribers",
"name": "return",
"type": "boolean",
"desc": "If there are active subscribers"
}
}
],
"desc": "Check if there are active subscribers to the named channel. This is helpful if\nthe message you want to send might be expensive to prepare.
\nThis API is optional but helpful when trying to publish messages from very\nperformance-sensitive code.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nif (diagnostics_channel.hasSubscribers('my-channel')) {\n // There are subscribers, prepare and publish message\n}\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nif (diagnostics_channel.hasSubscribers('my-channel')) {\n // There are subscribers, prepare and publish message\n}\n"
},
{
"textRaw": "`diagnostics_channel.channel(name)`",
"name": "channel",
"type": "method",
"meta": {
"added": [
"v15.1.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string|symbol} The channel name",
"name": "name",
"type": "string|symbol",
"desc": "The channel name"
}
],
"return": {
"textRaw": "Returns: {Channel} The named channel object",
"name": "return",
"type": "Channel",
"desc": "The named channel object"
}
}
],
"desc": "This is the primary entry-point for anyone wanting to publish to a named\nchannel. It produces a channel object which is optimized to reduce overhead at\npublish time as much as possible.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n"
},
{
"textRaw": "`diagnostics_channel.subscribe(name, onMessage)`",
"name": "subscribe",
"type": "method",
"meta": {
"added": [
"v18.7.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string|symbol} The channel name",
"name": "name",
"type": "string|symbol",
"desc": "The channel name"
},
{
"textRaw": "`onMessage` {Function} The handler to receive channel messages",
"name": "onMessage",
"type": "Function",
"desc": "The handler to receive channel messages",
"options": [
{
"textRaw": "`message` {any} The message data",
"name": "message",
"type": "any",
"desc": "The message data"
},
{
"textRaw": "`name` {string|symbol} The name of the channel",
"name": "name",
"type": "string|symbol",
"desc": "The name of the channel"
}
]
}
]
}
],
"desc": "Register a message handler to subscribe to this channel. This message handler\nwill be run synchronously whenever a message is published to the channel. Any\nerrors thrown in the message handler will trigger an 'uncaughtException'.
import diagnostics_channel from 'node:diagnostics_channel';\n\ndiagnostics_channel.subscribe('my-channel', (message, name) => {\n // Received data\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\ndiagnostics_channel.subscribe('my-channel', (message, name) => {\n // Received data\n});\n"
},
{
"textRaw": "`diagnostics_channel.unsubscribe(name, onMessage)`",
"name": "unsubscribe",
"type": "method",
"meta": {
"added": [
"v18.7.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string|symbol} The channel name",
"name": "name",
"type": "string|symbol",
"desc": "The channel name"
},
{
"textRaw": "`onMessage` {Function} The previous subscribed handler to remove",
"name": "onMessage",
"type": "Function",
"desc": "The previous subscribed handler to remove"
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if the handler was found, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if the handler was found, `false` otherwise."
}
}
],
"desc": "Remove a message handler previously registered to this channel with\ndiagnostics_channel.subscribe(name, onMessage).
import diagnostics_channel from 'node:diagnostics_channel';\n\nfunction onMessage(message, name) {\n // Received data\n}\n\ndiagnostics_channel.subscribe('my-channel', onMessage);\n\ndiagnostics_channel.unsubscribe('my-channel', onMessage);\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nfunction onMessage(message, name) {\n // Received data\n}\n\ndiagnostics_channel.subscribe('my-channel', onMessage);\n\ndiagnostics_channel.unsubscribe('my-channel', onMessage);\n"
},
{
"textRaw": "`diagnostics_channel.tracingChannel(nameOrChannels)`",
"name": "tracingChannel",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`nameOrChannels` {string|TracingChannel} Channel name or object containing all the TracingChannel Channels",
"name": "nameOrChannels",
"type": "string|TracingChannel",
"desc": "Channel name or object containing all the TracingChannel Channels"
}
],
"return": {
"textRaw": "Returns: {TracingChannel} Collection of channels to trace with",
"name": "return",
"type": "TracingChannel",
"desc": "Collection of channels to trace with"
}
}
],
"desc": "Creates a TracingChannel wrapper for the given\nTracingChannel Channels. If a name is given, the corresponding tracing\nchannels will be created in the form of tracing:${name}:${eventType} where\neventType corresponds to the types of TracingChannel Channels.
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channelsByName = diagnostics_channel.tracingChannel('my-channel');\n\n// or...\n\nconst channelsByCollection = diagnostics_channel.tracingChannel({\n start: diagnostics_channel.channel('tracing:my-channel:start'),\n end: diagnostics_channel.channel('tracing:my-channel:end'),\n asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),\n asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),\n error: diagnostics_channel.channel('tracing:my-channel:error'),\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channelsByName = diagnostics_channel.tracingChannel('my-channel');\n\n// or...\n\nconst channelsByCollection = diagnostics_channel.tracingChannel({\n start: diagnostics_channel.channel('tracing:my-channel:start'),\n end: diagnostics_channel.channel('tracing:my-channel:end'),\n asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),\n asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),\n error: diagnostics_channel.channel('tracing:my-channel:error'),\n});\n"
}
],
"displayName": "Overview"
},
{
"textRaw": "TracingChannel Channels",
"name": "tracingchannel_channels",
"type": "module",
"desc": "A TracingChannel is a collection of several diagnostics_channels representing\nspecific points in the execution lifecycle of a single traceable action. The\nbehavior is split into five diagnostics_channels consisting of start,\nend, asyncStart, asyncEnd, and error. A single traceable action will\nshare the same event object between all events, this can be helpful for\nmanaging correlation through a weakmap.
These event objects will be extended with result or error values when\nthe task \"completes\". In the case of a synchronous task the result will be\nthe return value and the error will be anything thrown from the function.\nWith callback-based async functions the result will be the second argument\nof the callback while the error will either be a thrown error visible in the\nend event or the first callback argument in either of the asyncStart or\nasyncEnd events.
To ensure only correct trace graphs are formed, events should only be published\nif subscribers are present prior to starting the trace. Subscriptions which are\nadded after the trace begins should not receive future events from that trace,\nonly future traces will be seen.
\nTracing channels should follow a naming pattern of:
\ntracing:module.class.method:start or tracing:module.function:starttracing:module.class.method:end or tracing:module.function:endtracing:module.class.method:asyncStart or tracing:module.function:asyncStarttracing:module.class.method:asyncEnd or tracing:module.function:asyncEndtracing:module.class.method:error or tracing:module.function:errortracing:${name}:startThe start event represents the point at which a function is called. At this\npoint the event data may contain function arguments or anything else available\nat the very start of the execution of the function.
tracing:${name}:endThe end event represents the point at which a function call returns a value.\nIn the case of an async function this is when the promise returned not when the\nfunction itself makes a return statement internally. At this point, if the\ntraced function was synchronous the result field will be set to the return\nvalue of the function. Alternatively, the error field may be present to\nrepresent any thrown errors.
It is recommended to listen specifically to the error event to track errors\nas it may be possible for a traceable action to produce multiple errors. For\nexample, an async task which fails may be started internally before the sync\npart of the task then throws an error.
tracing:${name}:asyncStartThe asyncStart event represents the callback or continuation of a traceable\nfunction being reached. At this point things like callback arguments may be\navailable, or anything else expressing the \"result\" of the action.
For callbacks-based functions, the first argument of the callback will be\nassigned to the error field, if not undefined or null, and the second\nargument will be assigned to the result field.
For promises, the argument to the resolve path will be assigned to result\nor the argument to the reject path will be assign to error.
It is recommended to listen specifically to the error event to track errors\nas it may be possible for a traceable action to produce multiple errors. For\nexample, an async task which fails may be started internally before the sync\npart of the task then throws an error.
tracing:${name}:asyncEndThe asyncEnd event represents the callback of an asynchronous function\nreturning. It's not likely event data will change after the asyncStart event,\nhowever it may be useful to see the point where the callback completes.
tracing:${name}:errorThe error event represents any error produced by the traceable function\neither synchronously or asynchronously. If an error is thrown in the\nsynchronous portion of the traced function the error will be assigned to the\nerror field of the event and the error event will be triggered. If an error\nis received asynchronously through a callback or promise rejection it will also\nbe assigned to the error field of the event and trigger the error event.
It is possible for a single traceable function call to produce errors multiple\ntimes so this should be considered when consuming this event. For example, if\nanother async task is triggered internally which fails and then the sync part\nof the function then throws and error two error events will be emitted, one\nfor the sync error and one for the async error.
Emitted when console.log() is called. Receives and array of the arguments\npassed to console.log().
Emitted when console.info() is called. Receives and array of the arguments\npassed to console.info().
Emitted when console.debug() is called. Receives and array of the arguments\npassed to console.debug().
Emitted when console.warn() is called. Receives and array of the arguments\npassed to console.warn().
Emitted when console.error() is called. Receives and array of the arguments\npassed to console.error().
Emitted when client creates a request object.\nUnlike http.client.request.start, this event is emitted before the request has been sent.
Emitted when client starts a request.
" }, { "textRaw": "Event: `'http.client.request.error'`", "name": "http.client.request.error", "type": "event", "params": [ { "textRaw": "`request` {http.ClientRequest}", "name": "request", "type": "http.ClientRequest" }, { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "Emitted when an error occurs during a client request.
" }, { "textRaw": "Event: `'http.client.response.finish'`", "name": "http.client.response.finish", "type": "event", "params": [ { "textRaw": "`request` {http.ClientRequest}", "name": "request", "type": "http.ClientRequest" }, { "textRaw": "`response` {http.IncomingMessage}", "name": "response", "type": "http.IncomingMessage" } ], "desc": "Emitted when client receives a response.
" }, { "textRaw": "Event: `'http.server.request.start'`", "name": "http.server.request.start", "type": "event", "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" }, { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" }, { "textRaw": "`server` {http.Server}", "name": "server", "type": "http.Server" } ], "desc": "Emitted when server receives a request.
" }, { "textRaw": "Event: `'http.server.response.created'`", "name": "http.server.response.created", "type": "event", "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" } ], "desc": "Emitted when server creates a response.\nThe event is emitted before the response is sent.
" }, { "textRaw": "Event: `'http.server.response.finish'`", "name": "http.server.response.finish", "type": "event", "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" }, { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" }, { "textRaw": "`server` {http.Server}", "name": "server", "type": "http.Server" } ], "desc": "Emitted when server sends a response.
" } ], "displayName": "HTTP" }, { "textRaw": "HTTP/2", "name": "http/2", "type": "module", "stability": 1, "stabilityText": "Experimental", "events": [ { "textRaw": "Event: `'http2.client.stream.created'`", "name": "http2.client.stream.created", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ], "desc": "Emitted when a stream is created on the client.
" }, { "textRaw": "Event: `'http2.client.stream.start'`", "name": "http2.client.stream.start", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ], "desc": "Emitted when a stream is started on the client.
" }, { "textRaw": "Event: `'http2.client.stream.error'`", "name": "http2.client.stream.error", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" }, { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "Emitted when an error occurs during the processing of a stream on the client.
" }, { "textRaw": "Event: `'http2.client.stream.finish'`", "name": "http2.client.stream.finish", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`flags` {number}", "name": "flags", "type": "number" } ], "desc": "Emitted when a stream is received on the client.
" }, { "textRaw": "Event: `'http2.client.stream.bodyChunkSent'`", "name": "http2.client.stream.bodyChunkSent", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" }, { "textRaw": "`writev` {boolean}", "name": "writev", "type": "boolean" }, { "textRaw": "`data` {Buffer|string|Buffer[]|Object[]}", "name": "data", "type": "Buffer|string|Buffer[]|Object[]", "options": [ { "textRaw": "`chunk` {Buffer|string}", "name": "chunk", "type": "Buffer|string" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" } ] }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" } ], "desc": "Emitted when a chunk of the client stream body is being sent.
" }, { "textRaw": "Event: `'http2.client.stream.bodySent'`", "name": "http2.client.stream.bodySent", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" } ], "desc": "Emitted after the client stream body has been fully sent.
" }, { "textRaw": "Event: `'http2.client.stream.close'`", "name": "http2.client.stream.close", "type": "event", "params": [ { "textRaw": "`stream` {ClientHttp2Stream}", "name": "stream", "type": "ClientHttp2Stream" } ], "desc": "Emitted when a stream is closed on the client. The HTTP/2 error code used when\nclosing the stream can be retrieved using the stream.rstCode property.
Emitted when a stream is created on the server.
" }, { "textRaw": "Event: `'http2.server.stream.start'`", "name": "http2.server.stream.start", "type": "event", "params": [ { "textRaw": "`stream` {ServerHttp2Stream}", "name": "stream", "type": "ServerHttp2Stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ], "desc": "Emitted when a stream is started on the server.
" }, { "textRaw": "Event: `'http2.server.stream.error'`", "name": "http2.server.stream.error", "type": "event", "params": [ { "textRaw": "`stream` {ServerHttp2Stream}", "name": "stream", "type": "ServerHttp2Stream" }, { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "Emitted when an error occurs during the processing of a stream on the server.
" }, { "textRaw": "Event: `'http2.server.stream.finish'`", "name": "http2.server.stream.finish", "type": "event", "params": [ { "textRaw": "`stream` {ServerHttp2Stream}", "name": "stream", "type": "ServerHttp2Stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`flags` {number}", "name": "flags", "type": "number" } ], "desc": "Emitted when a stream is sent on the server.
" }, { "textRaw": "Event: `'http2.server.stream.close'`", "name": "http2.server.stream.close", "type": "event", "params": [ { "textRaw": "`stream` {ServerHttp2Stream}", "name": "stream", "type": "ServerHttp2Stream" } ], "desc": "Emitted when a stream is closed on the server. The HTTP/2 error code used when\nclosing the stream can be retrieved using the stream.rstCode property.
Emitted when require() is executed. See start event.
Emitted when a require() call returns. See end event.
Emitted when a require() throws an error. See error event.
Emitted when import() is invoked. See asyncStart event.
Emitted when import() has completed. See asyncEnd event.
Emitted when a import() throws an error. See error event.
Emitted when a new TCP or pipe client socket connection is created.
" }, { "textRaw": "Event: `'net.server.socket'`", "name": "net.server.socket", "type": "event", "params": [ { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" } ], "desc": "Emitted when a new TCP or pipe connection is received.
" }, { "textRaw": "Event: `'tracing:net.server.listen:asyncStart'`", "name": "tracing:net.server.listen:asyncStart", "type": "event", "params": [ { "textRaw": "`server` {net.Server}", "name": "server", "type": "net.Server" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object" } ], "desc": "Emitted when net.Server.listen() is invoked, before the port or pipe is actually setup.
Emitted when net.Server.listen() has completed and thus the server is ready to accept connection.
Emitted when net.Server.listen() is returning an error.
Emitted when a new UDP socket is created.
" } ], "displayName": "UDP" }, { "textRaw": "Process", "name": "process", "type": "module", "meta": { "added": [ "v16.18.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "events": [ { "textRaw": "Event: `'child_process'`", "name": "child_process", "type": "event", "params": [ { "textRaw": "`process` {ChildProcess}", "name": "process", "type": "ChildProcess" } ], "desc": "Emitted when a new process is created.
\ntracing:child_process.spawn:start
process <ChildProcess>options <Object>Emitted when child_process.spawn() is invoked, before the process is\nactually spawned.
tracing:child_process.spawn:end
process <ChildProcess>Emitted when child_process.spawn() has completed successfully and the\nprocess has been created.
tracing:child_process.spawn:error
process <ChildProcess>error <Error>Emitted when child_process.spawn() encounters an error.
Emitted when process.execve() is invoked.
Emitted when a new thread is created.
" } ], "displayName": "Worker Thread" } ], "displayName": "Built-in Channels" } ], "classes": [ { "textRaw": "Class: `Channel`", "name": "Channel", "type": "class", "meta": { "added": [ "v15.1.0", "v14.17.0" ], "changes": [] }, "desc": "The class Channel represents an individual named channel within the data\npipeline. It is used to track subscribers and to publish messages when there\nare subscribers present. It exists as a separate object to avoid channel\nlookups at publish time, enabling very fast publish speeds and allowing\nfor heavy use while incurring very minimal cost. Channels are created with\ndiagnostics_channel.channel(name), constructing a channel directly\nwith new Channel(name) is not supported.
Check if there are active subscribers to this channel. This is helpful if\nthe message you want to send might be expensive to prepare.
\nThis API is optional but helpful when trying to publish messages from very\nperformance-sensitive code.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nif (channel.hasSubscribers) {\n // There are subscribers, prepare and publish message\n}\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nif (channel.hasSubscribers) {\n // There are subscribers, prepare and publish message\n}\n",
"shortDesc": "If there are active subscribers"
}
],
"methods": [
{
"textRaw": "`channel.publish(message)`",
"name": "publish",
"type": "method",
"meta": {
"added": [
"v15.1.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`message` {any} The message to send to the channel subscribers",
"name": "message",
"type": "any",
"desc": "The message to send to the channel subscribers"
}
]
}
],
"desc": "Publish a message to any subscribers to the channel. This will trigger\nmessage handlers synchronously so they will execute within the same context.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.publish({\n some: 'message',\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.publish({\n some: 'message',\n});\n"
},
{
"textRaw": "`channel.subscribe(onMessage)`",
"name": "subscribe",
"type": "method",
"meta": {
"added": [
"v15.1.0",
"v14.17.0"
],
"changes": [
{
"version": [
"v24.8.0",
"v22.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/59758",
"description": "Deprecation revoked."
},
{
"version": [
"v18.7.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/44943",
"description": "Documentation-only deprecation."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`onMessage` {Function} The handler to receive channel messages",
"name": "onMessage",
"type": "Function",
"desc": "The handler to receive channel messages",
"options": [
{
"textRaw": "`message` {any} The message data",
"name": "message",
"type": "any",
"desc": "The message data"
},
{
"textRaw": "`name` {string|symbol} The name of the channel",
"name": "name",
"type": "string|symbol",
"desc": "The name of the channel"
}
]
}
]
}
],
"desc": "Register a message handler to subscribe to this channel. This message handler\nwill be run synchronously whenever a message is published to the channel. Any\nerrors thrown in the message handler will trigger an 'uncaughtException'.
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.subscribe((message, name) => {\n // Received data\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.subscribe((message, name) => {\n // Received data\n});\n"
},
{
"textRaw": "`channel.unsubscribe(onMessage)`",
"name": "unsubscribe",
"type": "method",
"meta": {
"added": [
"v15.1.0",
"v14.17.0"
],
"changes": [
{
"version": [
"v24.8.0",
"v22.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/59758",
"description": "Deprecation revoked."
},
{
"version": [
"v18.7.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/44943",
"description": "Documentation-only deprecation."
},
{
"version": [
"v17.1.0",
"v16.14.0",
"v14.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/40433",
"description": "Added return value. Added to channels without subscribers."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`onMessage` {Function} The previous subscribed handler to remove",
"name": "onMessage",
"type": "Function",
"desc": "The previous subscribed handler to remove"
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if the handler was found, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if the handler was found, `false` otherwise."
}
}
],
"desc": "Remove a message handler previously registered to this channel with\nchannel.subscribe(onMessage).
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nfunction onMessage(message, name) {\n // Received data\n}\n\nchannel.subscribe(onMessage);\n\nchannel.unsubscribe(onMessage);\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nfunction onMessage(message, name) {\n // Received data\n}\n\nchannel.subscribe(onMessage);\n\nchannel.unsubscribe(onMessage);\n"
},
{
"textRaw": "`channel.bindStore(store[, transform])`",
"name": "bindStore",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`store` {AsyncLocalStorage} The store to which to bind the context data",
"name": "store",
"type": "AsyncLocalStorage",
"desc": "The store to which to bind the context data"
},
{
"textRaw": "`transform` {Function} Transform context data before setting the store context",
"name": "transform",
"type": "Function",
"desc": "Transform context data before setting the store context",
"optional": true
}
]
}
],
"desc": "When channel.runStores(context, ...) is called, the given context data\nwill be applied to any store bound to the channel. If the store has already been\nbound the previous transform function will be replaced with the new one.\nThe transform function may be omitted to set the given context data as the\ncontext directly.
import diagnostics_channel from 'node:diagnostics_channel';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store, (data) => {\n return { data };\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store, (data) => {\n return { data };\n});\n"
},
{
"textRaw": "`channel.unbindStore(store)`",
"name": "unbindStore",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`store` {AsyncLocalStorage} The store to unbind from the channel.",
"name": "store",
"type": "AsyncLocalStorage",
"desc": "The store to unbind from the channel."
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if the store was found, `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if the store was found, `false` otherwise."
}
}
],
"desc": "Remove a message handler previously registered to this channel with\nchannel.bindStore(store).
import diagnostics_channel from 'node:diagnostics_channel';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store);\nchannel.unbindStore(store);\n\nconst diagnostics_channel = require('node:diagnostics_channel');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store);\nchannel.unbindStore(store);\n"
},
{
"textRaw": "`channel.runStores(context, fn[, thisArg[, ...args]])`",
"name": "runStores",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`context` {any} Message to send to subscribers and bind to stores",
"name": "context",
"type": "any",
"desc": "Message to send to subscribers and bind to stores"
},
{
"textRaw": "`fn` {Function} Handler to run within the entered storage context",
"name": "fn",
"type": "Function",
"desc": "Handler to run within the entered storage context"
},
{
"textRaw": "`thisArg` {any} The receiver to be used for the function call.",
"name": "thisArg",
"type": "any",
"desc": "The receiver to be used for the function call.",
"optional": true
},
{
"textRaw": "`...args` {any} Optional arguments to pass to the function.",
"name": "...args",
"type": "any",
"desc": "Optional arguments to pass to the function.",
"optional": true
}
]
}
],
"desc": "Applies the given data to any AsyncLocalStorage instances bound to the channel\nfor the duration of the given function, then publishes to the channel within\nthe scope of that data is applied to the stores.
\nIf a transform function was given to channel.bindStore(store) it will be\napplied to transform the message data before it becomes the context value for\nthe store. The prior storage context is accessible from within the transform\nfunction in cases where context linking is required.
The context applied to the store should be accessible in any async code which\ncontinues from execution which began during the given function, however\nthere are some situations in which context loss may occur.
\nimport diagnostics_channel from 'node:diagnostics_channel';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store, (message) => {\n const parent = store.getStore();\n return new Span(message, parent);\n});\nchannel.runStores({ some: 'message' }, () => {\n store.getStore(); // Span({ some: 'message' })\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst store = new AsyncLocalStorage();\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.bindStore(store, (message) => {\n const parent = store.getStore();\n return new Span(message, parent);\n});\nchannel.runStores({ some: 'message' }, () => {\n store.getStore(); // Span({ some: 'message' })\n});\n"
}
]
},
{
"textRaw": "Class: `TracingChannel`",
"name": "TracingChannel",
"type": "class",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"desc": "The class TracingChannel is a collection of TracingChannel Channels which\ntogether express a single traceable action. It is used to formalize and\nsimplify the process of producing events for tracing application flow.\ndiagnostics_channel.tracingChannel() is used to construct a\nTracingChannel. As with Channel it is recommended to create and reuse a\nsingle TracingChannel at the top-level of the file rather than creating them\ndynamically.
Helper to subscribe a collection of functions to the corresponding channels.\nThis is the same as calling channel.subscribe(onMessage) on each channel\nindividually.
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.subscribe({\n start(message) {\n // Handle start message\n },\n end(message) {\n // Handle end message\n },\n asyncStart(message) {\n // Handle asyncStart message\n },\n asyncEnd(message) {\n // Handle asyncEnd message\n },\n error(message) {\n // Handle error message\n },\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.subscribe({\n start(message) {\n // Handle start message\n },\n end(message) {\n // Handle end message\n },\n asyncStart(message) {\n // Handle asyncStart message\n },\n asyncEnd(message) {\n // Handle asyncEnd message\n },\n error(message) {\n // Handle error message\n },\n});\n"
},
{
"textRaw": "`tracingChannel.unsubscribe(subscribers)`",
"name": "unsubscribe",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`subscribers` {Object} Set of TracingChannel Channels subscribers",
"name": "subscribers",
"type": "Object",
"desc": "Set of TracingChannel Channels subscribers",
"options": [
{
"textRaw": "`start` {Function} The `start` event subscriber",
"name": "start",
"type": "Function",
"desc": "The `start` event subscriber"
},
{
"textRaw": "`end` {Function} The `end` event subscriber",
"name": "end",
"type": "Function",
"desc": "The `end` event subscriber"
},
{
"textRaw": "`asyncStart` {Function} The `asyncStart` event subscriber",
"name": "asyncStart",
"type": "Function",
"desc": "The `asyncStart` event subscriber"
},
{
"textRaw": "`asyncEnd` {Function} The `asyncEnd` event subscriber",
"name": "asyncEnd",
"type": "Function",
"desc": "The `asyncEnd` event subscriber"
},
{
"textRaw": "`error` {Function} The `error` event subscriber",
"name": "error",
"type": "Function",
"desc": "The `error` event subscriber"
}
]
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if all handlers were successfully unsubscribed, and `false` otherwise.",
"name": "return",
"type": "boolean",
"desc": "`true` if all handlers were successfully unsubscribed, and `false` otherwise."
}
}
],
"desc": "Helper to unsubscribe a collection of functions from the corresponding channels.\nThis is the same as calling channel.unsubscribe(onMessage) on each channel\nindividually.
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.unsubscribe({\n start(message) {\n // Handle start message\n },\n end(message) {\n // Handle end message\n },\n asyncStart(message) {\n // Handle asyncStart message\n },\n asyncEnd(message) {\n // Handle asyncEnd message\n },\n error(message) {\n // Handle error message\n },\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.unsubscribe({\n start(message) {\n // Handle start message\n },\n end(message) {\n // Handle end message\n },\n asyncStart(message) {\n // Handle asyncStart message\n },\n asyncEnd(message) {\n // Handle asyncEnd message\n },\n error(message) {\n // Handle error message\n },\n});\n"
},
{
"textRaw": "`tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])`",
"name": "traceSync",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function} Function to wrap a trace around",
"name": "fn",
"type": "Function",
"desc": "Function to wrap a trace around"
},
{
"textRaw": "`context` {Object} Shared object to correlate events through",
"name": "context",
"type": "Object",
"desc": "Shared object to correlate events through",
"optional": true
},
{
"textRaw": "`thisArg` {any} The receiver to be used for the function call",
"name": "thisArg",
"type": "any",
"desc": "The receiver to be used for the function call",
"optional": true
},
{
"textRaw": "`...args` {any} Optional arguments to pass to the function",
"name": "...args",
"type": "any",
"desc": "Optional arguments to pass to the function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {any} The return value of the given function",
"name": "return",
"type": "any",
"desc": "The return value of the given function"
}
}
],
"desc": "Trace a synchronous function call. This will always produce a start event\nand end event around the execution and may produce an error event\nif the given function throws an error. This will run the given function using\nchannel.runStores(context, ...) on the start channel which ensures all\nevents should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published\nif subscribers are present prior to starting the trace. Subscriptions which are\nadded after the trace begins will not receive future events from that trace,\nonly future traces will be seen.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.traceSync(() => {\n // Do something\n}, {\n some: 'thing',\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.traceSync(() => {\n // Do something\n}, {\n some: 'thing',\n});\n"
},
{
"textRaw": "`tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])`",
"name": "tracePromise",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function} Promise-returning function to wrap a trace around",
"name": "fn",
"type": "Function",
"desc": "Promise-returning function to wrap a trace around"
},
{
"textRaw": "`context` {Object} Shared object to correlate trace events through",
"name": "context",
"type": "Object",
"desc": "Shared object to correlate trace events through",
"optional": true
},
{
"textRaw": "`thisArg` {any} The receiver to be used for the function call",
"name": "thisArg",
"type": "any",
"desc": "The receiver to be used for the function call",
"optional": true
},
{
"textRaw": "`...args` {any} Optional arguments to pass to the function",
"name": "...args",
"type": "any",
"desc": "Optional arguments to pass to the function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Chained from promise returned by the given function",
"name": "return",
"type": "Promise",
"desc": "Chained from promise returned by the given function"
}
}
],
"desc": "Trace a promise-returning function call. This will always produce a\nstart event and end event around the synchronous portion of the\nfunction execution, and will produce an asyncStart event and\nasyncEnd event when a promise continuation is reached. It may also\nproduce an error event if the given function throws an error or the\nreturned promise rejects. This will run the given function using\nchannel.runStores(context, ...) on the start channel which ensures all\nevents should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published\nif subscribers are present prior to starting the trace. Subscriptions which are\nadded after the trace begins will not receive future events from that trace,\nonly future traces will be seen.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.tracePromise(async () => {\n // Do something\n}, {\n some: 'thing',\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.tracePromise(async () => {\n // Do something\n}, {\n some: 'thing',\n});\n"
},
{
"textRaw": "`tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])`",
"name": "traceCallback",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.19.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function} callback using function to wrap a trace around",
"name": "fn",
"type": "Function",
"desc": "callback using function to wrap a trace around"
},
{
"textRaw": "`position` {number} Zero-indexed argument position of expected callback (defaults to last argument if `undefined` is passed)",
"name": "position",
"type": "number",
"desc": "Zero-indexed argument position of expected callback (defaults to last argument if `undefined` is passed)",
"optional": true
},
{
"textRaw": "`context` {Object} Shared object to correlate trace events through (defaults to `{}` if `undefined` is passed)",
"name": "context",
"type": "Object",
"desc": "Shared object to correlate trace events through (defaults to `{}` if `undefined` is passed)",
"optional": true
},
{
"textRaw": "`thisArg` {any} The receiver to be used for the function call",
"name": "thisArg",
"type": "any",
"desc": "The receiver to be used for the function call",
"optional": true
},
{
"textRaw": "`...args` {any} arguments to pass to the function (must include the callback)",
"name": "...args",
"type": "any",
"desc": "arguments to pass to the function (must include the callback)",
"optional": true
}
],
"return": {
"textRaw": "Returns: {any} The return value of the given function",
"name": "return",
"type": "any",
"desc": "The return value of the given function"
}
}
],
"desc": "Trace a callback-receiving function call. The callback is expected to follow\nthe error as first arg convention typically used. This will always produce a\nstart event and end event around the synchronous portion of the\nfunction execution, and will produce a asyncStart event and\nasyncEnd event around the callback execution. It may also produce an\nerror event if the given function throws or the first argument passed to\nthe callback is set. This will run the given function using\nchannel.runStores(context, ...) on the start channel which ensures all\nevents should have any bound stores set to match this trace context.
To ensure only correct trace graphs are formed, events will only be published\nif subscribers are present prior to starting the trace. Subscriptions which are\nadded after the trace begins will not receive future events from that trace,\nonly future traces will be seen.
\nimport diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.traceCallback((arg1, callback) => {\n // Do something\n callback(null, 'result');\n}, 1, {\n some: 'thing',\n}, thisArg, arg1, callback);\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nchannels.traceCallback((arg1, callback) => {\n // Do something\n callback(null, 'result');\n}, 1, {\n some: 'thing',\n}, thisArg, arg1, callback);\n\nThe callback will also be run with channel.runStores(context, ...) which\nenables context loss recovery in some cases.
import diagnostics_channel from 'node:diagnostics_channel';\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\nconst myStore = new AsyncLocalStorage();\n\n// The start channel sets the initial store data to something\n// and stores that store data value on the trace context object\nchannels.start.bindStore(myStore, (data) => {\n const span = new Span(data);\n data.span = span;\n return span;\n});\n\n// Then asyncStart can restore from that data it stored previously\nchannels.asyncStart.bindStore(myStore, (data) => {\n return data.span;\n});\n\nconst diagnostics_channel = require('node:diagnostics_channel');\nconst { AsyncLocalStorage } = require('node:async_hooks');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\nconst myStore = new AsyncLocalStorage();\n\n// The start channel sets the initial store data to something\n// and stores that store data value on the trace context object\nchannels.start.bindStore(myStore, (data) => {\n const span = new Span(data);\n data.span = span;\n return span;\n});\n\n// Then asyncStart can restore from that data it stored previously\nchannels.asyncStart.bindStore(myStore, (data) => {\n return data.span;\n});\n"
}
],
"properties": [
{
"textRaw": "Returns: {boolean} `true` if any of the individual channels has a subscriber, `false` if not.",
"name": "hasSubscribers",
"type": "boolean",
"meta": {
"added": [
"v22.0.0",
"v20.13.0"
],
"changes": []
},
"desc": "This is a helper method available on a TracingChannel instance to check if\nany of the TracingChannel Channels have subscribers. A true is returned if\nany of them have at least one subscriber, a false is returned otherwise.
import diagnostics_channel from 'node:diagnostics_channel';\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nif (channels.hasSubscribers) {\n // Do something\n}\n\nconst diagnostics_channel = require('node:diagnostics_channel');\n\nconst channels = diagnostics_channel.tracingChannel('my-channel');\n\nif (channels.hasSubscribers) {\n // Do something\n}\n",
"shortDesc": "`true` if any of the individual channels has a subscriber, `false` if not."
}
]
}
],
"displayName": "Public API"
}
],
"displayName": "Diagnostics Channel",
"source": "doc/api/diagnostics_channel.md"
},
{
"textRaw": "DNS",
"name": "dns",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:dns module enables name resolution. For example, use it to look up IP\naddresses of host names.
Although named for the Domain Name System (DNS), it does not always use the\nDNS protocol for lookups. dns.lookup() uses the operating system\nfacilities to perform name resolution. It may not need to perform any network\ncommunication. To perform name resolution the way other applications on the same\nsystem do, use dns.lookup().
import dns from 'node:dns';\n\ndns.lookup('example.org', (err, address, family) => {\n console.log('address: %j family: IPv%s', address, family);\n});\n// address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n\nconst dns = require('node:dns');\n\ndns.lookup('example.org', (err, address, family) => {\n console.log('address: %j family: IPv%s', address, family);\n});\n// address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n\nAll other functions in the node:dns module connect to an actual DNS server to\nperform name resolution. They will always use the network to perform DNS\nqueries. These functions do not use the same set of configuration files used by\ndns.lookup() (e.g. /etc/hosts). Use these functions to always perform\nDNS queries, bypassing other name-resolution facilities.
import dns from 'node:dns';\n\ndns.resolve4('archive.org', (err, addresses) => {\n if (err) throw err;\n\n console.log(`addresses: ${JSON.stringify(addresses)}`);\n\n addresses.forEach((a) => {\n dns.reverse(a, (err, hostnames) => {\n if (err) {\n throw err;\n }\n console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);\n });\n });\n});\n\nconst dns = require('node:dns');\n\ndns.resolve4('archive.org', (err, addresses) => {\n if (err) throw err;\n\n console.log(`addresses: ${JSON.stringify(addresses)}`);\n\n addresses.forEach((a) => {\n dns.reverse(a, (err, hostnames) => {\n if (err) {\n throw err;\n }\n console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);\n });\n });\n});\n\nSee the Implementation considerations section for more information.
", "classes": [ { "textRaw": "Class: `dns.Resolver`", "name": "dns.Resolver", "type": "class", "meta": { "added": [ "v8.3.0" ], "changes": [] }, "desc": "An independent resolver for DNS requests.
\nCreating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:
import { Resolver } from 'node:dns';\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org', (err, addresses) => {\n // ...\n});\n\nconst { Resolver } = require('node:dns');\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org', (err, addresses) => {\n // ...\n});\n\nThe 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.resolveTlsa()resolver.resolveTxt()resolver.reverse()resolver.setServers()Create a new resolver.
" }, { "textRaw": "`resolver.cancel()`", "name": "cancel", "type": "method", "meta": { "added": [ "v8.3.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Cancel all outstanding DNS queries made by this resolver. The corresponding\ncallbacks will be called with an error with code ECANCELLED.
The resolver instance will send its requests from the specified IP address.\nThis allows programs to specify outbound interfaces when used on multi-homed\nsystems.
\nIf a v4 or v6 address is not specified, it is set to the default and the\noperating system will choose a local address automatically.
\nThe resolver will use the v4 local address when making requests to IPv4 DNS\nservers, and the v6 local address when making requests to IPv6 DNS servers.\nThe rrtype of resolution requests has no impact on the local address used.
Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.
\n[\n '8.8.8.8',\n '2001:4860:4860::8888',\n '8.8.8.8:1053',\n '[2001:4860:4860::8888]:1053',\n]\n"
},
{
"textRaw": "`dns.lookup(hostname[, options], callback)`",
"name": "lookup",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": [
"v22.1.0",
"v20.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/52492",
"description": "The `verbatim` option is now deprecated in favor of the new `order` option."
},
{
"version": "v18.4.0",
"pr-url": "https://github.com/nodejs/node/pull/43054",
"description": "For compatibility with `node:net`, when passing an option object the `family` option can be the string `'IPv4'` or the string `'IPv6'`."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v17.0.0",
"pr-url": "https://github.com/nodejs/node/pull/39987",
"description": "The `verbatim` options defaults to `true` now."
},
{
"version": "v8.5.0",
"pr-url": "https://github.com/nodejs/node/pull/14731",
"description": "The `verbatim` option is supported now."
},
{
"version": "v1.2.0",
"pr-url": "https://github.com/nodejs/node/pull/744",
"description": "The `all` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`options` {integer|Object}",
"name": "options",
"type": "integer|Object",
"options": [
{
"textRaw": "`family` {integer|string} The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons,`'IPv4'` and `'IPv6'` are interpreted as `4` and `6` respectively. The value `0` indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used with `{ all: true }` (see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. **Default:** `0`.",
"name": "family",
"type": "integer|string",
"default": "`0`",
"desc": "The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons,`'IPv4'` and `'IPv6'` are interpreted as `4` and `6` respectively. The value `0` indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used with `{ all: true }` (see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver."
},
{
"textRaw": "`hints` {number} One or more supported `getaddrinfo` flags. Multiple flags may be passed by bitwise `OR`ing their values.",
"name": "hints",
"type": "number",
"desc": "One or more supported `getaddrinfo` flags. Multiple flags may be passed by bitwise `OR`ing their values."
},
{
"textRaw": "`all` {boolean} When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. **Default:** `false`.",
"name": "all",
"type": "boolean",
"default": "`false`",
"desc": "When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address."
},
{
"textRaw": "`order` {string} When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 addresses before IPv4 addresses. **Default:** `verbatim` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`.",
"name": "order",
"type": "string",
"default": "`verbatim` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`",
"desc": "When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 addresses before IPv4 addresses."
},
{
"textRaw": "`verbatim` {boolean} When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, `order` has higher precedence. New code should only use `order`. **Default:** `true` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`.",
"name": "verbatim",
"type": "boolean",
"default": "`true` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`",
"desc": "When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, `order` has higher precedence. New code should only use `order`."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`address` {string} A string representation of an IPv4 or IPv6 address.",
"name": "address",
"type": "string",
"desc": "A string representation of an IPv4 or IPv6 address."
},
{
"textRaw": "`family` {integer} `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system.",
"name": "family",
"type": "integer",
"desc": "`4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a bug in the name resolution service used by the operating system."
}
]
}
]
}
],
"desc": "Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then\neither IPv4 or IPv6 addresses, or both, are returned if found.
With the all option set to true, the arguments for callback change to\n(err, addresses), with addresses being an array of objects with the\nproperties address and family.
On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.
dns.lookup() does not necessarily have anything to do with the DNS protocol.\nThe implementation uses an operating system facility that can associate names\nwith addresses and vice versa. This implementation can have subtle but\nimportant consequences on the behavior of any Node.js program. Please take some\ntime to consult the Implementation considerations section before using\ndns.lookup().
Example usage:
\nimport dns from 'node:dns';\nconst options = {\n family: 6,\n hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\ndns.lookup('example.org', options, (err, address, family) =>\n console.log('address: %j family: IPv%s', address, family));\n// address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndns.lookup('example.org', options, (err, addresses) =>\n console.log('addresses: %j', addresses));\n// addresses: [{\"address\":\"2606:2800:21f:cb07:6820:80da:af6b:8b2c\",\"family\":6}]\n\nconst dns = require('node:dns');\nconst options = {\n family: 6,\n hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\ndns.lookup('example.org', options, (err, address, family) =>\n console.log('address: %j family: IPv%s', address, family));\n// address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndns.lookup('example.org', options, (err, addresses) =>\n console.log('addresses: %j', addresses));\n// addresses: [{\"address\":\"2606:2800:21f:cb07:6820:80da:af6b:8b2c\",\"family\":6}]\n\nIf this method is invoked as its util.promisify()ed version, and all\nis not set to true, it returns a Promise for an Object with address and\nfamily properties.
The following flags can be passed as hints to dns.lookup().
dns.ADDRCONFIG: Limits returned address types to the types of non-loopback\naddresses configured on the system. For example, IPv4 addresses are only\nreturned if the current system has at least one IPv4 address configured.dns.V4MAPPED: If the IPv6 family was specified, but no IPv6 addresses were\nfound, then return IPv4 mapped IPv6 addresses. It is not supported\non some operating systems (e.g. FreeBSD 10.1).dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as\nwell as IPv4 mapped IPv6 addresses.Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.
If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.
On an error, err is an Error object, where err.code is the error code.
import dns from 'node:dns';\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n console.log(hostname, service);\n // Prints: localhost ssh\n});\n\nconst dns = require('node:dns');\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n console.log(hostname, service);\n // Prints: localhost ssh\n});\n\nIf this method is invoked as its util.promisify()ed version, it returns a\nPromise for an Object with hostname and service properties.
Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. The callback function has arguments\n(err, records). When successful, records will be an array of resource\nrecords. The type and structure of individual results varies based on rrtype:
rrtype | records contains | Result type | Shorthand method |
|---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dns.resolve4() |
'AAAA' | IPv6 addresses | <string> | dns.resolve6() |
'ANY' | any records | <Object> | dns.resolveAny() |
'CAA' | CA authorization records | <Object> | dns.resolveCaa() |
'CNAME' | canonical name records | <string> | dns.resolveCname() |
'MX' | mail exchange records | <Object> | dns.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dns.resolveNaptr() |
'NS' | name server records | <string> | dns.resolveNs() |
'PTR' | pointer records | <string> | dns.resolvePtr() |
'SOA' | start of authority records | <Object> | dns.resolveSoa() |
'SRV' | service records | <Object> | dns.resolveSrv() |
'TLSA' | certificate associations | <Object> | dns.resolveTlsa() |
'TXT' | text records | <string[]> | dns.resolveTxt() |
On error, err is an Error object, where err.code is one of the\nDNS error codes.
Uses the DNS protocol to resolve a IPv4 addresses (A records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv6 addresses.
Uses the DNS protocol to resolve all records (also known as ANY or * query).\nThe ret argument passed to the callback function will be an array containing\nvarious types of records. Each object has a property type that indicates the\ntype of the current record. And depending on the type, additional properties\nwill be present on the object:
| Type | Properties |
|---|---|
'A' | address/ttl |
'AAAA' | address/ttl |
'CAA' | Refer to dns.resolveCaa() |
'CNAME' | value |
'MX' | Refer to dns.resolveMx() |
'NAPTR' | Refer to dns.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dns.resolveSoa() |
'SRV' | Refer to dns.resolveSrv() |
'TLSA' | Refer to dns.resolveTlsa() |
'TXT' | This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' } |
Here is an example of the ret object passed to the callback:
[ { type: 'A', address: '127.0.0.1', ttl: 299 },\n { type: 'CNAME', value: 'example.com' },\n { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n { type: 'NS', value: 'ns1.example.com' },\n { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n { type: 'SOA',\n nsname: 'ns1.example.com',\n hostmaster: 'admin.example.com',\n serial: 156696742,\n refresh: 900,\n retry: 900,\n expire: 1800,\n minttl: 60 } ]\n\nDNS server operators may choose not to respond to ANY\nqueries. It may be better to call individual methods like dns.resolve4(),\ndns.resolveMx(), and so on. For more details, see RFC 8482.
Uses the DNS protocol to resolve CNAME records for the hostname. The\naddresses argument passed to the callback function\nwill contain an array of canonical name records available for the hostname\n(e.g. ['bar.example.com']).
Uses the DNS protocol to resolve CAA records for the hostname. The\naddresses argument passed to the callback function\nwill contain an array of certification authority authorization records\navailable for the hostname (e.g. [{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]).
Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of objects containing both a priority and exchange\nproperty (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]).
Uses the DNS protocol to resolve regular expression-based records (NAPTR\nrecords) for the hostname. The addresses argument passed to the callback\nfunction will contain an array of objects with the following properties:
flagsserviceregexpreplacementorderpreference{\n flags: 's',\n service: 'SIP+D2U',\n regexp: '',\n replacement: '_sip._udp.example.com',\n order: 30,\n preference: 100\n}\n"
},
{
"textRaw": "`dns.resolveNs(hostname, callback)`",
"name": "resolveNs",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`addresses` {string[]}",
"name": "addresses",
"type": "string[]"
}
]
}
]
}
],
"desc": "Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. The addresses argument passed to the callback function will\ncontain an array of name server records available for hostname\n(e.g. ['ns1.example.com', 'ns2.example.com']).
Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of strings containing the reply records.
Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. The address argument passed to the callback function will\nbe an object with the following properties:
nsnamehostmasterserialrefreshretryexpireminttl{\n nsname: 'ns.example.com',\n hostmaster: 'root.example.com',\n serial: 2013101809,\n refresh: 10000,\n retry: 2400,\n expire: 604800,\n minttl: 3600\n}\n"
},
{
"textRaw": "`dns.resolveSrv(hostname, callback)`",
"name": "resolveSrv",
"type": "method",
"meta": {
"added": [
"v0.1.27"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`addresses` {Object[]}",
"name": "addresses",
"type": "Object[]"
}
]
}
]
}
],
"desc": "Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. The addresses argument passed to the callback function will\nbe an array of objects with the following properties:
priorityweightportname{\n priority: 10,\n weight: 5,\n port: 21223,\n name: 'service.example.com'\n}\n"
},
{
"textRaw": "`dns.resolveTlsa(hostname, callback)`",
"name": "resolveTlsa",
"type": "method",
"meta": {
"added": [
"v23.9.0",
"v22.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`records` {Object[]}",
"name": "records",
"type": "Object[]"
}
]
}
]
}
],
"desc": "Uses the DNS protocol to resolve certificate associations (TLSA records) for\nthe hostname. The records argument passed to the callback function is an\narray of objects with these properties:
certUsageselectormatchdata{\n certUsage: 3,\n selector: 1,\n match: 1,\n data: [ArrayBuffer]\n}\n"
},
{
"textRaw": "`dns.resolveTxt(hostname, callback)`",
"name": "resolveTxt",
"type": "method",
"meta": {
"added": [
"v0.1.27"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`records` {string[]}",
"name": "records",
"type": "string[]"
}
]
}
]
}
],
"desc": "Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. The records argument passed to the callback function is a\ntwo-dimensional array of the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.
\nOn error, err is an Error object, where err.code is\none of the DNS error codes.
Set the default value of order in dns.lookup() and\ndnsPromises.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 dns.setDefaultResultOrder() have higher\npriority than --dns-result-order. When using worker threads,\ndns.setDefaultResultOrder() from the main thread won't affect the default\ndns orders in workers.
Get the default value for order in dns.lookup() and\ndnsPromises.lookup(). The value could be:
ipv4first: for order defaulting to ipv4first.ipv6first: for order defaulting to ipv6first.verbatim: for order defaulting to verbatim.Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.
dns.setServers([\n '8.8.8.8',\n '[2001:4860:4860::8888]',\n '8.8.8.8:1053',\n '[2001:4860:4860::8888]:1053',\n]);\n\nAn error will be thrown if an invalid address is provided.
\nThe dns.setServers() method must not be called while a DNS query is in\nprogress.
The dns.setServers() method affects only dns.resolve(),\ndns.resolve*() and dns.reverse() (and specifically not\ndns.lookup()).
This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.
The dns.promises API provides an alternative set of asynchronous DNS methods\nthat return Promise objects rather than using callbacks. The API is accessible\nvia require('node:dns').promises or require('node:dns/promises').
An independent resolver for DNS requests.
\nCreating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:
import { Resolver } from 'node:dns/promises';\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nconst addresses = await resolver.resolve4('example.org');\n\nconst { Resolver } = require('node:dns').promises;\nconst resolver = new Resolver();\nresolver.setServers(['4.4.4.4']);\n\n// This request will use the server at 4.4.4.4, independent of global settings.\nresolver.resolve4('example.org').then((addresses) => {\n // ...\n});\n\n// Alternatively, the same code can be written using async-await style.\n(async function() {\n const addresses = await resolver.resolve4('example.org');\n})();\n\nThe 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.resolveTlsa()resolver.resolveTxt()resolver.reverse()resolver.setServers()Cancel all outstanding DNS queries made by this resolver. The corresponding\npromises will be rejected with an error with the code ECANCELLED.
Returns an array of IP address strings, formatted according to RFC 5952,\nthat are currently configured for DNS resolution. A string will include a port\nsection if a custom port is used.
\n[\n '8.8.8.8',\n '2001:4860:4860::8888',\n '8.8.8.8:1053',\n '[2001:4860:4860::8888]:1053',\n]\n"
},
{
"textRaw": "`dnsPromises.lookup(hostname[, options])`",
"name": "lookup",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": [
{
"version": [
"v22.1.0",
"v20.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/52492",
"description": "The `verbatim` option is now deprecated in favor of the new `order` option."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
},
{
"textRaw": "`options` {integer|Object}",
"name": "options",
"type": "integer|Object",
"options": [
{
"textRaw": "`family` {integer} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used with `{ all: true }` (see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver. **Default:** `0`.",
"name": "family",
"type": "integer",
"default": "`0`",
"desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used with `{ all: true }` (see below), either one of or both IPv4 and IPv6 addresses are returned, depending on the system's DNS resolver."
},
{
"textRaw": "`hints` {number} One or more supported `getaddrinfo` flags. Multiple flags may be passed by bitwise `OR`ing their values.",
"name": "hints",
"type": "number",
"desc": "One or more supported `getaddrinfo` flags. Multiple flags may be passed by bitwise `OR`ing their values."
},
{
"textRaw": "`all` {boolean} When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address. **Default:** `false`.",
"name": "all",
"type": "boolean",
"default": "`false`",
"desc": "When `true`, the `Promise` is resolved with all addresses in an array. Otherwise, returns a single address."
},
{
"textRaw": "`order` {string} When `verbatim`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `ipv4first`, IPv4 addresses are placed before IPv6 addresses. When `ipv6first`, IPv6 addresses are placed before IPv4 addresses. **Default:** `verbatim` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`. New code should use `{ order: 'verbatim' }`.",
"name": "order",
"type": "string",
"default": "`verbatim` (addresses are not reordered). Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`. New code should use `{ order: 'verbatim' }`",
"desc": "When `verbatim`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `ipv4first`, IPv4 addresses are placed before IPv6 addresses. When `ipv6first`, IPv6 addresses are placed before IPv4 addresses."
},
{
"textRaw": "`verbatim` {boolean} When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, `order` has higher precedence. New code should only use `order`. **Default:** currently `false` (addresses are reordered) but this is expected to change in the not too distant future. Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`.",
"name": "verbatim",
"type": "boolean",
"default": "currently `false` (addresses are reordered) but this is expected to change in the not too distant future. Default value is configurable using `dns.setDefaultResultOrder()` or `--dns-result-order`",
"desc": "When `true`, the `Promise` is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, `order` has higher precedence. New code should only use `order`."
}
],
"optional": true
}
]
}
],
"desc": "Resolves a host name (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. All option properties are optional. If options is an\ninteger, then it must be 4 or 6 – if options is not provided, then\neither IPv4 or IPv6 addresses, or both, are returned if found.
With the all option set to true, the Promise is resolved with addresses\nbeing an array of objects with the properties address and family.
On error, the Promise is rejected with an Error object, where err.code\nis the error code.\nKeep in mind that err.code will be set to 'ENOTFOUND' not only when\nthe host name does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.
dnsPromises.lookup() does not necessarily have anything to do with the DNS\nprotocol. The implementation uses an operating system facility that can\nassociate names with addresses and vice versa. This implementation can have\nsubtle but important consequences on the behavior of any Node.js program. Please\ntake some time to consult the Implementation considerations section before\nusing dnsPromises.lookup().
Example usage:
\nimport dns from 'node:dns';\nconst dnsPromises = dns.promises;\nconst options = {\n family: 6,\n hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\n\nawait dnsPromises.lookup('example.org', options).then((result) => {\n console.log('address: %j family: IPv%s', result.address, result.family);\n // address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n});\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\nawait dnsPromises.lookup('example.org', options).then((result) => {\n console.log('addresses: %j', result);\n // addresses: [{\"address\":\"2606:2800:21f:cb07:6820:80da:af6b:8b2c\",\"family\":6}]\n});\n\nconst dns = require('node:dns');\nconst dnsPromises = dns.promises;\nconst options = {\n family: 6,\n hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\n\ndnsPromises.lookup('example.org', options).then((result) => {\n console.log('address: %j family: IPv%s', result.address, result.family);\n // address: \"2606:2800:21f:cb07:6820:80da:af6b:8b2c\" family: IPv6\n});\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndnsPromises.lookup('example.org', options).then((result) => {\n console.log('addresses: %j', result);\n // addresses: [{\"address\":\"2606:2800:21f:cb07:6820:80da:af6b:8b2c\",\"family\":6}]\n});\n"
},
{
"textRaw": "`dnsPromises.lookupService(address, port)`",
"name": "lookupService",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`address` {string}",
"name": "address",
"type": "string"
},
{
"textRaw": "`port` {number}",
"name": "port",
"type": "number"
}
]
}
],
"desc": "Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.
If address is not a valid IP address, a TypeError will be thrown.\nThe port will be coerced to a number. If it is not a legal port, a TypeError\nwill be thrown.
On error, the Promise is rejected with an Error object, where err.code\nis the error code.
import dnsPromises from 'node:dns/promises';\nconst result = await dnsPromises.lookupService('127.0.0.1', 22);\n\nconsole.log(result.hostname, result.service); // Prints: localhost ssh\n\nconst dnsPromises = require('node:dns').promises;\ndnsPromises.lookupService('127.0.0.1', 22).then((result) => {\n console.log(result.hostname, result.service);\n // Prints: localhost ssh\n});\n"
},
{
"textRaw": "`dnsPromises.resolve(hostname[, rrtype])`",
"name": "resolve",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string} Host name to resolve.",
"name": "hostname",
"type": "string",
"desc": "Host name to resolve."
},
{
"textRaw": "`rrtype` {string} Resource record type. **Default:** `'A'`.",
"name": "rrtype",
"type": "string",
"default": "`'A'`",
"desc": "Resource record type.",
"optional": true
}
]
}
],
"desc": "Uses the DNS protocol to resolve a host name (e.g. 'nodejs.org') into an array\nof the resource records. When successful, the Promise is resolved with an\narray of resource records. The type and structure of individual results vary\nbased on rrtype:
rrtype | records contains | Result type | Shorthand method |
|---|---|---|---|
'A' | IPv4 addresses (default) | <string> | dnsPromises.resolve4() |
'AAAA' | IPv6 addresses | <string> | dnsPromises.resolve6() |
'ANY' | any records | <Object> | dnsPromises.resolveAny() |
'CAA' | CA authorization records | <Object> | dnsPromises.resolveCaa() |
'CNAME' | canonical name records | <string> | dnsPromises.resolveCname() |
'MX' | mail exchange records | <Object> | dnsPromises.resolveMx() |
'NAPTR' | name authority pointer records | <Object> | dnsPromises.resolveNaptr() |
'NS' | name server records | <string> | dnsPromises.resolveNs() |
'PTR' | pointer records | <string> | dnsPromises.resolvePtr() |
'SOA' | start of authority records | <Object> | dnsPromises.resolveSoa() |
'SRV' | service records | <Object> | dnsPromises.resolveSrv() |
'TLSA' | certificate associations | <Object> | dnsPromises.resolveTlsa() |
'TXT' | text records | <string[]> | dnsPromises.resolveTxt() |
On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.
Uses the DNS protocol to resolve IPv4 addresses (A records) for the\nhostname. On success, the Promise is resolved with an array of IPv4\naddresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
Uses the DNS protocol to resolve IPv6 addresses (AAAA records) for the\nhostname. On success, the Promise is resolved with an array of IPv6\naddresses.
Uses the DNS protocol to resolve all records (also known as ANY or * query).\nOn success, the Promise is resolved with an array containing various types of\nrecords. Each object has a property type that indicates the type of the\ncurrent record. And depending on the type, additional properties will be\npresent on the object:
| Type | Properties |
|---|---|
'A' | address/ttl |
'AAAA' | address/ttl |
'CAA' | Refer to dnsPromises.resolveCaa() |
'CNAME' | value |
'MX' | Refer to dnsPromises.resolveMx() |
'NAPTR' | Refer to dnsPromises.resolveNaptr() |
'NS' | value |
'PTR' | value |
'SOA' | Refer to dnsPromises.resolveSoa() |
'SRV' | Refer to dnsPromises.resolveSrv() |
'TLSA' | Refer to dnsPromises.resolveTlsa() |
'TXT' | This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' } |
Here is an example of the result object:
\n[ { type: 'A', address: '127.0.0.1', ttl: 299 },\n { type: 'CNAME', value: 'example.com' },\n { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },\n { type: 'NS', value: 'ns1.example.com' },\n { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },\n { type: 'SOA',\n nsname: 'ns1.example.com',\n hostmaster: 'admin.example.com',\n serial: 156696742,\n refresh: 900,\n retry: 900,\n expire: 1800,\n minttl: 60 } ]\n"
},
{
"textRaw": "`dnsPromises.resolveCaa(hostname)`",
"name": "resolveCaa",
"type": "method",
"meta": {
"added": [
"v15.0.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
}
]
}
],
"desc": "Uses the DNS protocol to resolve CAA records for the hostname. On success,\nthe Promise is resolved with an array of objects containing available\ncertification authority authorization records available for the hostname\n(e.g. [{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]).
Uses the DNS protocol to resolve CNAME records for the hostname. On success,\nthe Promise is resolved with an array of canonical name records available for\nthe hostname (e.g. ['bar.example.com']).
Uses the DNS protocol to resolve mail exchange records (MX records) for the\nhostname. On success, the Promise is resolved with an array of objects\ncontaining both a priority and exchange property (e.g.\n[{priority: 10, exchange: 'mx.example.com'}, ...]).
Uses the DNS protocol to resolve regular expression-based records (NAPTR\nrecords) for the hostname. On success, the Promise is resolved with an array\nof objects with the following properties:
flagsserviceregexpreplacementorderpreference{\n flags: 's',\n service: 'SIP+D2U',\n regexp: '',\n replacement: '_sip._udp.example.com',\n order: 30,\n preference: 100\n}\n"
},
{
"textRaw": "`dnsPromises.resolveNs(hostname)`",
"name": "resolveNs",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
}
]
}
],
"desc": "Uses the DNS protocol to resolve name server records (NS records) for the\nhostname. On success, the Promise is resolved with an array of name server\nrecords available for hostname (e.g.\n['ns1.example.com', 'ns2.example.com']).
Uses the DNS protocol to resolve pointer records (PTR records) for the\nhostname. On success, the Promise is resolved with an array of strings\ncontaining the reply records.
Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. On success, the Promise is resolved with an object with the\nfollowing properties:
nsnamehostmasterserialrefreshretryexpireminttl{\n nsname: 'ns.example.com',\n hostmaster: 'root.example.com',\n serial: 2013101809,\n refresh: 10000,\n retry: 2400,\n expire: 604800,\n minttl: 3600\n}\n"
},
{
"textRaw": "`dnsPromises.resolveSrv(hostname)`",
"name": "resolveSrv",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
}
]
}
],
"desc": "Uses the DNS protocol to resolve service records (SRV records) for the\nhostname. On success, the Promise is resolved with an array of objects with\nthe following properties:
priorityweightportname{\n priority: 10,\n weight: 5,\n port: 21223,\n name: 'service.example.com'\n}\n"
},
{
"textRaw": "`dnsPromises.resolveTlsa(hostname)`",
"name": "resolveTlsa",
"type": "method",
"meta": {
"added": [
"v23.9.0",
"v22.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
}
]
}
],
"desc": "Uses the DNS protocol to resolve certificate associations (TLSA records) for\nthe hostname. On success, the Promise is resolved with an array of objects\nwith these properties:
certUsageselectormatchdata{\n certUsage: 3,\n selector: 1,\n match: 1,\n data: [ArrayBuffer]\n}\n"
},
{
"textRaw": "`dnsPromises.resolveTxt(hostname)`",
"name": "resolveTxt",
"type": "method",
"meta": {
"added": [
"v10.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`hostname` {string}",
"name": "hostname",
"type": "string"
}
]
}
],
"desc": "Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. On success, the Promise is resolved with a two-dimensional array\nof the text records available for hostname (e.g.\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.
\nOn error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.
Set the default value of order in dns.lookup() and\ndnsPromises.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() have\nhigher priority than --dns-result-order. When using worker threads,\ndnsPromises.setDefaultResultOrder() from the main thread won't affect the\ndefault dns orders in workers.
Get the value of dnsOrder.
Sets the IP address and port of servers to be used when performing DNS\nresolution. The servers argument is an array of RFC 5952 formatted\naddresses. If the port is the IANA default DNS port (53) it can be omitted.
dnsPromises.setServers([\n '8.8.8.8',\n '[2001:4860:4860::8888]',\n '8.8.8.8:1053',\n '[2001:4860:4860::8888]:1053',\n]);\n\nAn error will be thrown if an invalid address is provided.
\nThe dnsPromises.setServers() method must not be called while a DNS query is in\nprogress.
This method works much like\nresolve.conf.\nThat is, if attempting to resolve with the first server provided results in a\nNOTFOUND error, the resolve() method will not attempt to resolve with\nsubsequent servers provided. Fallback DNS servers will only be used if the\nearlier ones time out or result in some other error.
Each DNS query can return one of the following error codes:
\ndns.NODATA: DNS server returned an answer with no data.dns.FORMERR: DNS server claims query was misformatted.dns.SERVFAIL: DNS server returned general failure.dns.NOTFOUND: Domain name not found.dns.NOTIMP: DNS server does not implement the requested operation.dns.REFUSED: DNS server refused query.dns.BADQUERY: Misformatted DNS query.dns.BADNAME: Misformatted host name.dns.BADFAMILY: Unsupported address family.dns.BADRESP: Misformatted DNS reply.dns.CONNREFUSED: Could not contact DNS servers.dns.TIMEOUT: Timeout while contacting DNS servers.dns.EOF: End of file.dns.FILE: Error reading file.dns.NOMEM: Out of memory.dns.DESTRUCTION: Channel is being destroyed.dns.BADSTR: Misformatted string.dns.BADFLAGS: Illegal flags specified.dns.NONAME: Given host name is not numeric.dns.BADHINTS: Illegal hints flags specified.dns.NOTINITIALIZED: c-ares library initialization not yet performed.dns.LOADIPHLPAPI: Error loading iphlpapi.dll.dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.dns.CANCELLED: DNS query cancelled.The dnsPromises API also exports the above error codes, e.g., dnsPromises.NODATA.
Although dns.lookup() and the various dns.resolve*()/dns.reverse()\nfunctions have the same goal of associating a network name with a network\naddress (or vice versa), their behavior is quite different. These differences\ncan have subtle but significant consequences on the behavior of Node.js\nprograms.
Under the hood, dns.lookup() uses the same operating system facilities\nas most other programs. For instance, dns.lookup() will almost always\nresolve a given name the same way as the ping command. On most POSIX-like\noperating systems, the behavior of the dns.lookup() function can be\nmodified by changing settings in nsswitch.conf(5) and/or resolv.conf(5),\nbut changing these files will change the behavior of all other\nprograms running on the same operating system.
Though the call to dns.lookup() will be asynchronous from JavaScript's\nperspective, it is implemented as a synchronous call to getaddrinfo(3) that runs\non libuv's threadpool. This can have surprising negative performance\nimplications for some applications, see the UV_THREADPOOL_SIZE\ndocumentation for more information.
Various networking APIs will call dns.lookup() internally to resolve\nhost names. If that is an issue, consider resolving the host name to an address\nusing dns.resolve() and using the address instead of a host name. Also, some\nnetworking APIs (such as socket.connect() and dgram.createSocket())\nallow the default resolver, dns.lookup(), to be replaced.
These functions are implemented quite differently than dns.lookup(). They\ndo not use getaddrinfo(3) and they always perform a DNS query on the\nnetwork. This network communication is always done asynchronously and does not\nuse libuv's threadpool.
As a result, these functions cannot have the same negative impact on other\nprocessing that happens on libuv's threadpool that dns.lookup() can have.
They do not use the same set of configuration files that dns.lookup()\nuses. For instance, they do not use the configuration from /etc/hosts.
This module is pending deprecation. Once a replacement API has been\nfinalized, this module will be fully deprecated. Most developers should\nnot have cause to use this module. Users who absolutely must have\nthe functionality that domains provide may rely on it for the time being\nbut should expect to have to migrate to a different solution\nin the future.
\nDomains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an 'error' event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.
Domain error handlers are not a substitute for closing down a\nprocess when an error occurs.
\nBy the very nature of how throw works in JavaScript, there is almost\nnever any way to safely \"pick up where it left off\", without leaking\nreferences, or creating some other sort of undefined brittle state.
The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, there may be many\nopen connections, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.
\nThe better approach is to send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.
\nIn this way, domain usage goes hand-in-hand with the cluster module,\nsince the primary process can fork a new worker when a worker\nencounters an error. For Node.js programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.
For example, this is not a good idea:
\n// XXX WARNING! BAD IDEA!\n\nconst d = require('node:domain').create();\nd.on('error', (er) => {\n // The error won't crash the process, but what it does is worse!\n // Though we've prevented abrupt process restarting, we are leaking\n // a lot of resources if this ever happens.\n // This is no better than process.on('uncaughtException')!\n console.log(`error, but oh well ${er.message}`);\n});\nd.run(() => {\n require('node:http').createServer((req, res) => {\n handleRequest(req, res);\n }).listen(PORT);\n});\n\nBy using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.
\n// Much better!\n\nconst cluster = require('node:cluster');\nconst PORT = +process.env.PORT || 1337;\n\nif (cluster.isPrimary) {\n // A more realistic scenario would have more than 2 workers,\n // and perhaps not put the primary and worker in the same file.\n //\n // It is also possible to get a bit fancier about logging, and\n // implement whatever custom logic is needed to prevent DoS\n // attacks and other bad behavior.\n //\n // See the options in the cluster documentation.\n //\n // The important thing is that the primary does very little,\n // increasing our resilience to unexpected errors.\n\n cluster.fork();\n cluster.fork();\n\n cluster.on('disconnect', (worker) => {\n console.error('disconnect!');\n cluster.fork();\n });\n\n} else {\n // the worker\n //\n // This is where we put our bugs!\n\n const domain = require('node:domain');\n\n // See the cluster documentation for more details about using\n // worker processes to serve requests. How it works, caveats, etc.\n\n const server = require('node:http').createServer((req, res) => {\n const d = domain.create();\n d.on('error', (er) => {\n console.error(`error ${er.stack}`);\n\n // We're in dangerous territory!\n // By definition, something unexpected occurred,\n // which we probably didn't want.\n // Anything can happen now! Be very careful!\n\n try {\n // Make sure we close down within 30 seconds\n const killtimer = setTimeout(() => {\n process.exit(1);\n }, 30000);\n // But don't keep the process open just for that!\n killtimer.unref();\n\n // Stop taking new requests.\n server.close();\n\n // Let the primary know we're dead. This will trigger a\n // 'disconnect' in the cluster primary, and then it will fork\n // a new worker.\n cluster.worker.disconnect();\n\n // Try to send an error to the request that triggered the problem\n res.statusCode = 500;\n res.setHeader('content-type', 'text/plain');\n res.end('Oops, there was a problem!\\n');\n } catch (er2) {\n // Oh well, not much we can do at this point.\n console.error(`Error sending 500! ${er2.stack}`);\n }\n });\n\n // Because req and res were created before this domain existed,\n // we need to explicitly add them.\n // See the explanation of implicit vs explicit binding below.\n d.add(req);\n d.add(res);\n\n // Now run the handler function in the domain.\n d.run(() => {\n handleRequest(req, res);\n });\n });\n server.listen(PORT);\n}\n\n// This part is not important. Just an example routing thing.\n// Put fancy application logic here.\nfunction handleRequest(req, res) {\n switch (req.url) {\n case '/error':\n // We do some async stuff, and then...\n setTimeout(() => {\n // Whoops!\n flerb.bark();\n }, timeout);\n break;\n default:\n res.end('ok');\n }\n}\n"
},
{
"textRaw": "Additions to `Error` objects",
"name": "Additions to `Error` objects",
"type": "misc",
"desc": "Any time an Error object is routed through a domain, a few extra fields\nare added to it.
error.domain The domain that first handled the error.error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.
Additionally, callbacks passed to low-level event loop requests (such as\nto fs.open(), or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.
In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.
To nest Domain objects as children of a parent Domain they must be\nexplicitly added.
Implicit binding routes thrown errors and 'error' events to the\nDomain's 'error' event, but does not register the EventEmitter on the\nDomain.\nImplicit binding only takes care of thrown errors and 'error' events.
Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.
\nFor example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.
\nThat is possible via explicit binding.
\n// Create a top-level domain for the server\nconst domain = require('node:domain');\nconst http = require('node:http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n // Server is created in the scope of serverDomain\n http.createServer((req, res) => {\n // Req and res are also created in the scope of serverDomain\n // however, we'd prefer to have a separate domain for each request.\n // create it first thing, and add req and res to it.\n const reqd = domain.create();\n reqd.add(req);\n reqd.add(res);\n reqd.on('error', (er) => {\n console.error('Error', er, req.url);\n try {\n res.writeHead(500);\n res.end('Error occurred, sorry.');\n } catch (er2) {\n console.error('Error sending 500', er2, req.url);\n }\n });\n }).listen(1337);\n});\n"
}
],
"methods": [
{
"textRaw": "`domain.create()`",
"name": "create",
"type": "method",
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Domain}",
"name": "return",
"type": "Domain"
}
}
]
}
],
"classes": [
{
"textRaw": "Class: `Domain`",
"name": "Domain",
"type": "class",
"desc": "<EventEmitter>The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.
To handle the errors that it catches, listen to its 'error' event.
An array of event emitters that have been explicitly added to the domain.
" } ], "methods": [ { "textRaw": "`domain.add(emitter)`", "name": "add", "type": "method", "meta": { "changes": [ { "version": "v9.3.0", "pr-url": "https://github.com/nodejs/node/pull/16222", "description": "No longer accepts timer objects." } ] }, "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter} emitter to be added to the domain", "name": "emitter", "type": "EventEmitter", "desc": "emitter to be added to the domain" } ] } ], "desc": "Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an 'error' event, it\nwill be routed to the domain's 'error' event, just like with implicit\nbinding.
If the EventEmitter was already bound to a domain, it is removed from that\none, and bound to this one instead.
The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's 'error' event.
const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n fs.readFile(filename, 'utf8', d.bind((er, data) => {\n // If this throws, it will also be passed to the domain.\n return cb(er, data ? JSON.parse(data) : null);\n }));\n}\n\nd.on('error', (er) => {\n // An error occurred somewhere. If we throw it now, it will crash the program\n // with the normal line number and stack message.\n});\n"
},
{
"textRaw": "`domain.enter()`",
"name": "enter",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "The enter() method is plumbing used by the run(), bind(), and\nintercept() methods to set the active domain. It sets domain.active and\nprocess.domain to the domain, and implicitly pushes the domain onto the domain\nstack managed by the domain module (see domain.exit() for details on the\ndomain stack). The call to enter() delimits the beginning of a chain of\nasynchronous calls and I/O operations bound to a domain.
Calling enter() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.
The exit() method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit() delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.
If there are multiple, nested domains bound to the current execution context,\nexit() will exit any domains nested within this domain.
Calling exit() changes only the active domain, and does not alter the domain\nitself. enter() and exit() can be called an arbitrary number of times on a\nsingle domain.
This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.
In this way, the common if (err) return callback(err); pattern can be replaced\nwith a single error handler in a single place.
const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n fs.readFile(filename, 'utf8', d.intercept((data) => {\n // Note, the first argument is never passed to the\n // callback since it is assumed to be the 'Error' argument\n // and thus intercepted by the domain.\n\n // If this throws, it will also be passed to the domain\n // so the error-handling logic can be moved to the 'error'\n // event on the domain instead of being repeated throughout\n // the program.\n return cb(null, JSON.parse(data));\n }));\n}\n\nd.on('error', (er) => {\n // An error occurred somewhere. If we throw it now, it will crash the program\n // with the normal line number and stack message.\n});\n"
},
{
"textRaw": "`domain.remove(emitter)`",
"name": "remove",
"type": "method",
"signatures": [
{
"params": [
{
"textRaw": "`emitter` {EventEmitter} emitter to be removed from the domain",
"name": "emitter",
"type": "EventEmitter",
"desc": "emitter to be removed from the domain"
}
]
}
],
"desc": "The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.
Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and low-level requests that are\ncreated in that context. Optionally, arguments can be passed to\nthe function.
\nThis is the most basic way to use a domain.
\nconst domain = require('node:domain');\nconst fs = require('node:fs');\nconst d = domain.create();\nd.on('error', (er) => {\n console.error('Caught error!', er);\n});\nd.run(() => {\n process.nextTick(() => {\n setTimeout(() => { // Simulating some various async stuff\n fs.open('non-existent file', 'r', (er, fd) => {\n if (er) throw er;\n // proceed...\n });\n }, 100);\n });\n});\n\nIn this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.
As of Node.js 8.0.0, the handlers of promises are run inside the domain in\nwhich the call to .then() or .catch() itself was made:
const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n p = Promise.resolve(42);\n});\n\nd2.run(() => {\n p.then((v) => {\n // running in d2\n });\n});\n\nA callback may be bound to a specific domain using domain.bind(callback):
const d1 = domain.create();\nconst d2 = domain.create();\n\nlet p;\nd1.run(() => {\n p = Promise.resolve(42);\n});\n\nd2.run(() => {\n p.then(p.domain.bind((v) => {\n // running in d1\n }));\n});\n\nDomains will not interfere with the error handling mechanisms for\npromises. In other words, no 'error' event will be emitted for unhandled\nPromise rejections.
Environment variables are variables associated to the environment the Node.js process runs in.
", "modules": [ { "textRaw": "CLI Environment Variables", "name": "cli_environment_variables", "type": "module", "desc": "There is a set of environment variables that can be defined to customize the behavior of Node.js,\nfor more details refer to the CLI Environment Variables documentation.
", "displayName": "CLI Environment Variables" }, { "textRaw": "DotEnv", "name": "dotenv", "type": "module", "stability": 2, "stabilityText": "Stable", "desc": "Set of utilities for dealing with additional environment variables defined in .env files.
.env files (also known as dotenv files) are files that define environment variables,\nwhich Node.js applications can then interact with (popularized by the dotenv package).
The following is an example of the content of a basic .env file:
MY_VAR_A = \"my variable A\"\nMY_VAR_B = \"my variable B\"\n\nThis type of file is used in various different programming languages and platforms but there\nis no formal specification for it, therefore Node.js defines its own specification described below.
\nA .env file is a file that contains key-value pairs, each pair is represented by a variable name\nfollowed by the equal sign (=) followed by a variable value.
The name of such files is usually .env or it starts with .env (like for example .env.dev where\ndev indicates a specific target environment). This is the recommended naming scheme but it is not\nmandatory and dotenv files can have any arbitrary file name.
A valid variable name must contain only letters (uppercase or lowercase), digits and underscores\n(_) and it can't begin with a digit.
More specifically a valid variable name must match the following regular expression:
\n^[a-zA-Z_]+[a-zA-Z0-9_]*$\n\nThe recommended convention is to use capital letters with underscores and digits when necessary,\nbut any variable name respecting the above definition will work just fine.
\nFor example, the following are some valid variable names: MY_VAR, MY_VAR_1, my_var, my_var_1,\nmyVar, My_Var123, while these are instead not valid: 1_VAR, 'my-var', \"my var\", VAR_#1.
Variable values are comprised by any arbitrary text, which can optionally be wrapped inside\nsingle (') or double (\") quotes.
Quoted variables can span across multiple lines, while non quoted ones are restricted to a single line.
\nNoting that when parsed by Node.js all values are interpreted as text, meaning that any value will\nresult in a JavaScript string inside Node.js. For example the following values: 0, true and\n{ \"hello\": \"world\" } will result in the literal strings '0', 'true' and '{ \"hello\": \"world\" }'\ninstead of the number zero, the boolean true and an object with the hello property respectively.
Examples of valid variables:
\nMY_SIMPLE_VAR = a simple single line variable\nMY_EQUALS_VAR = \"this variable contains an = sign!\"\nMY_HASH_VAR = 'this variable contains a # symbol!'\nMY_MULTILINE_VAR = '\nthis is a multiline variable containing\ntwo separate lines\\nSorry, I meant three lines'\n",
"displayName": "Variable Values"
},
{
"textRaw": "Spacing",
"name": "spacing",
"type": "module",
"desc": "Leading and trailing whitespace characters around variable keys and values are ignored unless they\nare enclosed within quotes.
\nFor example:
\n MY_VAR_A = my variable a\n MY_VAR_B = ' my variable b '\n\nwill be treated identically to:
\nMY_VAR_A = my variable a\nMY_VAR_B = ' my variable b '\n",
"displayName": "Spacing"
},
{
"textRaw": "Comments",
"name": "comments",
"type": "module",
"desc": "Hash-tag (#) characters denote the beginning of a comment, meaning that the rest of the line\nwill be completely ignored.
Hash-tags found within quotes are however treated as any other standard character.
\nFor example:
\n# This is a comment\nMY_VAR = my variable # This is also a comment\nMY_VAR_A = \"# this is NOT a comment\"\n",
"displayName": "Comments"
},
{
"textRaw": "`export` prefixes",
"name": "`export`_prefixes",
"type": "module",
"desc": "The export keyword can optionally be added in front of variable declarations, such keyword will be completely ignored\nby all processing done on the file.
This is useful so that the file can be sourced, without modifications, in shell terminals.
\nExample:
\nexport MY_VAR = my variable\n",
"displayName": "`export` prefixes"
}
],
"displayName": ".env files"
},
{
"textRaw": "CLI Options",
"name": "cli_options",
"type": "module",
"desc": ".env files can be used to populate the process.env object via one the following CLI options:
There following two functions allow you to directly interact with .env files:
process.loadEnvFile loads an .env file and populates process.env with its variables
util.parseEnv parses the row content of an .env file and returns its value in an object
The basic API for interacting with environment variables is process.env, it consists of an object\nwith pre-populated user environment variables that can be modified and expanded.
For more details refer to the process.env documentation.
Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called \"emitters\")\nemit named events that cause Function objects (\"listeners\") to be called.
For instance: a net.Server object emits an event each time a peer\nconnects to it; a fs.ReadStream emits an event when the file is opened;\na stream emits an event whenever data is available to be read.
All objects that emit events are instances of the EventEmitter class. These\nobjects expose an eventEmitter.on() function that allows one or more\nfunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.
When the EventEmitter object emits an event, all of the functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and discarded.
The following example shows a simple EventEmitter instance with a single\nlistener. The eventEmitter.on() method is used to register listeners, while\nthe eventEmitter.emit() method is used to trigger the event.
import { EventEmitter } from 'node:events';\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n\nconst EventEmitter = require('node:events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n",
"modules": [
{
"textRaw": "Passing arguments and `this` to listeners",
"name": "passing_arguments_and_`this`_to_listeners",
"type": "module",
"desc": "The eventEmitter.emit() method allows an arbitrary set of arguments to be\npassed to the listener functions. Keep in mind that when\nan ordinary listener function is called, the standard this keyword\nis intentionally set to reference the EventEmitter instance to which the\nlistener is attached.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n console.log(a, b, this, this === myEmitter);\n // Prints:\n // a b MyEmitter {\n // _events: [Object: null prototype] { event: [Function (anonymous)] },\n // _eventsCount: 1,\n // _maxListeners: undefined,\n // Symbol(shapeMode): false,\n // Symbol(kCapture): false\n // } true\n});\nmyEmitter.emit('event', 'a', 'b');\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n console.log(a, b, this, this === myEmitter);\n // Prints:\n // a b MyEmitter {\n // _events: [Object: null prototype] { event: [Function (anonymous)] },\n // _eventsCount: 1,\n // _maxListeners: undefined,\n // Symbol(shapeMode): false,\n // Symbol(kCapture): false\n // } true\n});\nmyEmitter.emit('event', 'a', 'b');\n\nIt is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n console.log(a, b, this);\n // Prints: a b undefined\n});\nmyEmitter.emit('event', 'a', 'b');\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n console.log(a, b, this);\n // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n",
"displayName": "Passing arguments and `this` to listeners"
},
{
"textRaw": "Asynchronous vs. synchronous",
"name": "asynchronous_vs._synchronous",
"type": "module",
"desc": "The EventEmitter calls all listeners synchronously in the order in which\nthey were registered. This ensures the proper sequencing of\nevents and helps avoid race conditions and logic errors. When appropriate,\nlistener functions can switch to an asynchronous mode of operation using\nthe setImmediate() or process.nextTick() methods:
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n setImmediate(() => {\n console.log('this happens asynchronously');\n });\n});\nmyEmitter.emit('event', 'a', 'b');\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n setImmediate(() => {\n console.log('this happens asynchronously');\n });\n});\nmyEmitter.emit('event', 'a', 'b');\n",
"displayName": "Asynchronous vs. synchronous"
},
{
"textRaw": "Handling events only once",
"name": "handling_events_only_once",
"type": "module",
"desc": "When a listener is registered using the eventEmitter.on() method, that\nlistener is invoked every time the named event is emitted.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.on('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Prints: 2\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.on('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Prints: 2\n\nUsing the eventEmitter.once() method, it is possible to register a listener\nthat is called at most once for a particular event. Once the event is emitted,\nthe listener is unregistered and then called.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.once('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Ignored\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nlet m = 0;\nmyEmitter.once('event', () => {\n console.log(++m);\n});\nmyEmitter.emit('event');\n// Prints: 1\nmyEmitter.emit('event');\n// Ignored\n",
"displayName": "Handling events only once"
},
{
"textRaw": "Error events",
"name": "error_events",
"type": "module",
"desc": "When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as special cases\nwithin Node.js.
If an EventEmitter does not have at least one listener registered for the\n'error' event, and an 'error' event is emitted, the error is thrown, a\nstack trace is printed, and the Node.js process exits.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n\nTo guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the node:domain module is deprecated.)
As a best practice, listeners should always be added for the 'error' events.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n console.error('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n console.error('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n\nIt is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol events.errorMonitor.
import { EventEmitter, errorMonitor } from 'node:events';\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on(errorMonitor, (err) => {\n MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n\nconst { EventEmitter, errorMonitor } = require('node:events');\n\nconst myEmitter = new EventEmitter();\nmyEmitter.on(errorMonitor, (err) => {\n MyMonitoringTool.log(err);\n});\nmyEmitter.emit('error', new Error('whoops!'));\n// Still throws and crashes Node.js\n",
"displayName": "Error events"
},
{
"textRaw": "Capture rejections of promises",
"name": "capture_rejections_of_promises",
"type": "module",
"desc": "Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:
import { EventEmitter } from 'node:events';\nconst ee = new EventEmitter();\nee.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nconst EventEmitter = require('node:events');\nconst ee = new EventEmitter();\nee.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nThe captureRejections option in the EventEmitter constructor or the global\nsetting change this behavior, installing a .then(undefined, handler)\nhandler on the Promise. This handler routes the exception\nasynchronously to the Symbol.for('nodejs.rejection') method\nif there is one, or to 'error' event handler if there is none.
import { EventEmitter } from 'node:events';\nconst ee1 = new EventEmitter({ captureRejections: true });\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst ee2 = new EventEmitter({ captureRejections: true });\nee2.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee2[Symbol.for('nodejs.rejection')] = console.log;\n\nconst EventEmitter = require('node:events');\nconst ee1 = new EventEmitter({ captureRejections: true });\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst ee2 = new EventEmitter({ captureRejections: true });\nee2.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee2[Symbol.for('nodejs.rejection')] = console.log;\n\nSetting events.captureRejections = true will change the default for all\nnew instances of EventEmitter.
import { EventEmitter } from 'node:events';\n\nEventEmitter.captureRejections = true;\nconst ee1 = new EventEmitter();\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nconst events = require('node:events');\nevents.captureRejections = true;\nconst ee1 = new events.EventEmitter();\nee1.on('something', async (value) => {\n throw new Error('kaboom');\n});\n\nee1.on('error', console.log);\n\nThe 'error' events that are generated by the captureRejections behavior\ndo not have a catch handler to avoid infinite error loops: the\nrecommendation is to not use async functions as 'error' event handlers.
The EventTarget and Event objects are a Node.js-specific implementation\nof the EventTarget Web API that are exposed by some Node.js core APIs.
const target = new EventTarget();\n\ntarget.addEventListener('foo', (event) => {\n console.log('foo event happened!');\n});\n",
"modules": [
{
"textRaw": "Node.js `EventTarget` vs. DOM `EventTarget`",
"name": "node.js_`eventtarget`_vs._dom_`eventtarget`",
"type": "module",
"desc": "There are two key differences between the Node.js EventTarget and the\nEventTarget Web API:
EventTarget instances may be hierarchical, there is no\nconcept of hierarchy and event propagation in Node.js. That is, an event\ndispatched to an EventTarget does not propagate through a hierarchy of\nnested target objects that may each have their own set of handlers for the\nevent.EventTarget, if an event listener is an async function\nor returns a Promise, and the returned Promise rejects, the rejection\nis automatically captured and handled the same way as a listener that\nthrows synchronously (see EventTarget error handling for details).The NodeEventTarget object implements a modified subset of the\nEventEmitter API that allows it to closely emulate an EventEmitter in\ncertain situations. A NodeEventTarget is not an instance of EventEmitter\nand cannot be used in place of an EventEmitter in most cases.
EventEmitter, any given listener can be registered at most once\nper event type. Attempts to register a listener multiple times are\nignored.NodeEventTarget does not emulate the full EventEmitter API.\nSpecifically the prependListener(), prependOnceListener(),\nrawListeners(), and errorMonitor APIs are not emulated.\nThe 'newListener' and 'removeListener' events will also not be emitted.NodeEventTarget does not implement any special default behavior\nfor events with type 'error'.NodeEventTarget supports EventListener objects as well as\nfunctions as handlers for all event types.Event listeners registered for an event type may either be JavaScript\nfunctions or objects with a handleEvent property whose value is a function.
In either case, the handler function is invoked with the event argument\npassed to the eventTarget.dispatchEvent() function.
Async functions may be used as event listeners. If an async handler function\nrejects, the rejection is captured and handled as described in\nEventTarget error handling.
An error thrown by one handler function does not prevent the other handlers\nfrom being invoked.
\nThe return value of a handler function is ignored.
\nHandlers are always invoked in the order they were added.
\nHandler functions may mutate the event object.
function handler1(event) {\n console.log(event.type); // Prints 'foo'\n event.a = 1;\n}\n\nasync function handler2(event) {\n console.log(event.type); // Prints 'foo'\n console.log(event.a); // Prints 1\n}\n\nconst handler3 = {\n handleEvent(event) {\n console.log(event.type); // Prints 'foo'\n },\n};\n\nconst handler4 = {\n async handleEvent(event) {\n console.log(event.type); // Prints 'foo'\n },\n};\n\nconst target = new EventTarget();\n\ntarget.addEventListener('foo', handler1);\ntarget.addEventListener('foo', handler2);\ntarget.addEventListener('foo', handler3);\ntarget.addEventListener('foo', handler4, { once: true });\n",
"displayName": "Event listener"
},
{
"textRaw": "`EventTarget` error handling",
"name": "`eventtarget`_error_handling",
"type": "module",
"desc": "When a registered event listener throws (or returns a Promise that rejects),\nby default the error is treated as an uncaught exception on\nprocess.nextTick(). This means uncaught exceptions in EventTargets will\nterminate the Node.js process by default.
Throwing within an event listener will not stop the other registered handlers\nfrom being invoked.
\nThe EventTarget does not implement any special default handling for 'error'\ntype events like EventEmitter.
Currently errors are first forwarded to the process.on('error') event\nbefore reaching process.on('uncaughtException'). This behavior is\ndeprecated and will change in a future release to align EventTarget with\nother Node.js APIs. Any code relying on the process.on('error') event should\nbe aligned with the new behavior.
The Event object is an adaptation of the Event Web API. Instances\nare created internally by Node.js.
This is not used in Node.js and is provided purely for completeness.
", "shortDesc": "Always returns `false`." }, { "textRaw": "Type: {boolean}", "name": "cancelBubble", "type": "boolean", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy: Use `event.stopPropagation()` instead.", "desc": "Alias for event.stopPropagation() if set to true. This is not used\nin Node.js and is provided purely for completeness.
This is not used in Node.js and is provided purely for completeness.
", "shortDesc": "Always returns `false`." }, { "textRaw": "Type: {EventTarget} The `EventTarget` dispatching the event.", "name": "currentTarget", "type": "EventTarget", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "Alias for event.target.
Is true if cancelable is true and event.preventDefault() has been\ncalled.
This is not used in Node.js and is provided purely for completeness.
", "shortDesc": "Returns `0` while an event is not being dispatched, `2` while it is being dispatched." }, { "textRaw": "Type: {boolean}", "name": "isTrusted", "type": "boolean", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "The <AbortSignal> \"abort\" event is emitted with isTrusted set to true. The\nvalue is false in all other cases.
The value of event.returnValue is always the opposite of event.defaultPrevented.\nThis is not used in Node.js and is provided purely for completeness.
Alias for event.target.
The millisecond timestamp when the Event object was created.
The event type identifier.
" } ], "methods": [ { "textRaw": "`event.composedPath()`", "name": "composedPath", "type": "method", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Returns an array containing the current EventTarget as the only entry or\nempty if the event is not being dispatched. This is not used in\nNode.js and is provided purely for completeness.
Redundant with event constructors and incapable of setting composed.\nThis is not used in Node.js and is provided purely for completeness.
Sets the defaultPrevented property to true if cancelable is true.
Stops the invocation of event listeners after the current one completes.
" }, { "textRaw": "`event.stopPropagation()`", "name": "stopPropagation", "type": "method", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "This is not used in Node.js and is provided purely for completeness.
" } ] }, { "textRaw": "Class: `EventTarget`", "name": "EventTarget", "type": "class", "meta": { "added": [ "v14.5.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35496", "description": "The `EventTarget` class is now available through the global object." } ] }, "methods": [ { "textRaw": "`eventTarget.addEventListener(type, listener[, options])`", "name": "addEventListener", "type": "method", "meta": { "added": [ "v14.5.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/36258", "description": "add support for `signal` option." } ] }, "signatures": [ { "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`once` {boolean} When `true`, the listener is automatically removed when it is first invoked. **Default:** `false`.", "name": "once", "type": "boolean", "default": "`false`", "desc": "When `true`, the listener is automatically removed when it is first invoked." }, { "textRaw": "`passive` {boolean} When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. **Default:** `false`.", "name": "passive", "type": "boolean", "default": "`false`", "desc": "When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method." }, { "textRaw": "`capture` {boolean} Not directly used by Node.js. Added for API completeness. **Default:** `false`.", "name": "capture", "type": "boolean", "default": "`false`", "desc": "Not directly used by Node.js. Added for API completeness." }, { "textRaw": "`signal` {AbortSignal} The listener will be removed when the given AbortSignal object's `abort()` method is called.", "name": "signal", "type": "AbortSignal", "desc": "The listener will be removed when the given AbortSignal object's `abort()` method is called." } ], "optional": true } ] } ], "desc": "Adds a new handler for the type event. Any given listener is added\nonly once per type and per capture option value.
If the once option is true, the listener is removed after the\nnext time a type event is dispatched.
The capture option is not used by Node.js in any functional way other than\ntracking registered event listeners per the EventTarget specification.\nSpecifically, the capture option is used as part of the key when registering\na listener. Any individual listener may be added once with\ncapture = false, and once with capture = true.
function handler(event) {}\n\nconst target = new EventTarget();\ntarget.addEventListener('foo', handler, { capture: true }); // first\ntarget.addEventListener('foo', handler, { capture: false }); // second\n\n// Removes the second instance of handler\ntarget.removeEventListener('foo', handler);\n\n// Removes the first instance of handler\ntarget.removeEventListener('foo', handler, { capture: true });\n"
},
{
"textRaw": "`eventTarget.dispatchEvent(event)`",
"name": "dispatchEvent",
"type": "method",
"meta": {
"added": [
"v14.5.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`event` {Event}",
"name": "event",
"type": "Event"
}
],
"return": {
"textRaw": "Returns: {boolean} `true` if either event's `cancelable` attribute value is false or its `preventDefault()` method was not invoked, otherwise `false`.",
"name": "return",
"type": "boolean",
"desc": "`true` if either event's `cancelable` attribute value is false or its `preventDefault()` method was not invoked, otherwise `false`."
}
}
],
"desc": "Dispatches the event to the list of handlers for event.type.
The registered event listeners is synchronously invoked in the order they\nwere registered.
" }, { "textRaw": "`eventTarget.removeEventListener(type, listener[, options])`", "name": "removeEventListener", "type": "method", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`capture` {boolean}", "name": "capture", "type": "boolean" } ], "optional": true } ] } ], "desc": "Removes the listener from the list of handlers for event type.
<Event>The CustomEvent object is an adaptation of the CustomEvent Web API.\nInstances are created internally by Node.js.
Read-only.
", "shortDesc": "Returns custom data passed when initializing." } ] }, { "textRaw": "Class: `NodeEventTarget`", "name": "NodeEventTarget", "type": "class", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "<EventTarget>The NodeEventTarget is a Node.js-specific extension to EventTarget\nthat emulates a subset of the EventEmitter API.
Node.js-specific extension to the EventTarget class that emulates the\nequivalent EventEmitter API. The only difference between addListener() and\naddEventListener() is that addListener() will return a reference to the\nEventTarget.
Node.js-specific extension to the EventTarget class that dispatches the\narg to the list of handlers for type.
Node.js-specific extension to the EventTarget class that returns an array\nof event type names for which event listeners are registered.
Node.js-specific extension to the EventTarget class that returns the number\nof event listeners registered for the type.
Node.js-specific extension to the EventTarget class that sets the number\nof max event listeners as n.
Node.js-specific extension to the EventTarget class that returns the number\nof max event listeners.
Node.js-specific alias for eventTarget.removeEventListener().
Node.js-specific alias for eventTarget.addEventListener().
Node.js-specific extension to the EventTarget class that adds a once\nlistener for the given event type. This is equivalent to calling on\nwith the once option set to true.
Node.js-specific extension to the EventTarget class. If type is specified,\nremoves all registered listeners for type, otherwise removes all registered\nlisteners.
Node.js-specific extension to the EventTarget class that removes the\nlistener for the given type. The only difference between removeListener()\nand removeEventListener() is that removeListener() will return a reference\nto the EventTarget.
The EventEmitter class is defined and exposed by the node:events module:
import { EventEmitter } from 'node:events';\n\nconst EventEmitter = require('node:events');\n\nAll EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.
It supports the following option:
\ncaptureRejections <boolean> It enables automatic capturing of promise rejection.\nDefault: false.The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.
Listeners registered for the 'newListener' event are passed the event\nname and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname within the 'newListener' callback are inserted before the\nlistener that is in the process of being added.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n if (event === 'event') {\n // Insert a new listener in front\n myEmitter.on('event', () => {\n console.log('B');\n });\n }\n});\nmyEmitter.on('event', () => {\n console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n// B\n// A\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n if (event === 'event') {\n // Insert a new listener in front\n myEmitter.on('event', () => {\n console.log('B');\n });\n }\n});\nmyEmitter.on('event', () => {\n console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n// B\n// A\n"
},
{
"textRaw": "Event: `'removeListener'`",
"name": "removeListener",
"type": "event",
"meta": {
"added": [
"v0.9.3"
],
"changes": [
{
"version": [
"v6.1.0",
"v4.7.0"
],
"pr-url": "https://github.com/nodejs/node/pull/6394",
"description": "For listeners attached using `.once()`, the `listener` argument now yields the original listener function."
}
]
},
"params": [
{
"textRaw": "`eventName` {string|symbol} The event name",
"name": "eventName",
"type": "string|symbol",
"desc": "The event name"
},
{
"textRaw": "`listener` {Function} The event handler function",
"name": "listener",
"type": "Function",
"desc": "The event handler function"
}
],
"desc": "The 'removeListener' event is emitted after the listener is removed.
Alias for emitter.on(eventName, listener).
Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.
Returns true if the event had listeners, false otherwise.
import { EventEmitter } from 'node:events';\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n\nconst EventEmitter = require('node:events');\nconst myEmitter = new EventEmitter();\n\n// First listener\nmyEmitter.on('event', function firstListener() {\n console.log('Helloooo! first listener');\n});\n// Second listener\nmyEmitter.on('event', function secondListener(arg1, arg2) {\n console.log(`event with parameters ${arg1}, ${arg2} in second listener`);\n});\n// Third listener\nmyEmitter.on('event', function thirdListener(...args) {\n const parameters = args.join(', ');\n console.log(`event with parameters ${parameters} in third listener`);\n});\n\nconsole.log(myEmitter.listeners('event'));\n\nmyEmitter.emit('event', 1, 2, 3, 4, 5);\n\n// Prints:\n// [\n// [Function: firstListener],\n// [Function: secondListener],\n// [Function: thirdListener]\n// ]\n// Helloooo! first listener\n// event with parameters 1, 2 in second listener\n// event with parameters 1, 2, 3, 4, 5 in third listener\n"
},
{
"textRaw": "`emitter.eventNames()`",
"name": "eventNames",
"type": "method",
"meta": {
"added": [
"v6.0.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]|symbol[]}",
"name": "return",
"type": "string[]|symbol[]"
}
}
],
"desc": "Returns an array listing the events for which the emitter has registered\nlisteners.
\nimport { EventEmitter } from 'node:events';\n\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n\nconst EventEmitter = require('node:events');\n\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n"
},
{
"textRaw": "`emitter.getMaxListeners()`",
"name": "getMaxListeners",
"type": "method",
"meta": {
"added": [
"v1.0.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nevents.defaultMaxListeners.
Returns the number of listeners listening for the event named eventName.\nIf listener is provided, it will return how many times the listener is found\nin the list of the listeners of the event.
Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n"
},
{
"textRaw": "`emitter.off(eventName, listener)`",
"name": "off",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {string|symbol}",
"name": "eventName",
"type": "string|symbol"
},
{
"textRaw": "`listener` {Function}",
"name": "listener",
"type": "Function"
}
],
"return": {
"textRaw": "Returns: {EventEmitter}",
"name": "return",
"type": "EventEmitter"
}
}
],
"desc": "Alias for emitter.removeListener().
Adds the listener function to the end of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\n\nReturns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The\nemitter.prependListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n\nconst EventEmitter = require('node:events');\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n"
},
{
"textRaw": "`emitter.once(eventName, listener)`",
"name": "once",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {string|symbol} The name of the event.",
"name": "eventName",
"type": "string|symbol",
"desc": "The name of the event."
},
{
"textRaw": "`listener` {Function} The callback function",
"name": "listener",
"type": "Function",
"desc": "The callback function"
}
],
"return": {
"textRaw": "Returns: {EventEmitter}",
"name": "return",
"type": "EventEmitter"
}
}
],
"desc": "Adds a one-time listener function for the event named eventName. The\nnext time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n\nReturns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The\nemitter.prependOnceListener() method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
import { EventEmitter } from 'node:events';\nconst myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n\nconst EventEmitter = require('node:events');\nconst myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n"
},
{
"textRaw": "`emitter.prependListener(eventName, listener)`",
"name": "prependListener",
"type": "method",
"meta": {
"added": [
"v6.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {string|symbol} The name of the event.",
"name": "eventName",
"type": "string|symbol",
"desc": "The name of the event."
},
{
"textRaw": "`listener` {Function} The callback function",
"name": "listener",
"type": "Function",
"desc": "The callback function"
}
],
"return": {
"textRaw": "Returns: {EventEmitter}",
"name": "return",
"type": "EventEmitter"
}
}
],
"desc": "Adds the listener function to the beginning of the listeners array for the\nevent named eventName. No checks are made to see if the listener has\nalready been added. Multiple calls passing the same combination of eventName\nand listener will result in the listener being added, and called, multiple\ntimes.
server.prependListener('connection', (stream) => {\n console.log('someone connected!');\n});\n\nReturns a reference to the EventEmitter, so that calls can be chained.
Adds a one-time listener function for the event named eventName to the\nbeginning of the listeners array. The next time eventName is triggered, this\nlistener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n\nReturns a reference to the EventEmitter, so that calls can be chained.
Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,\nparticularly when the EventEmitter instance was created by some other\ncomponent or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Removes the specified listener from the listener array for the event named\neventName.
const callback = (stream) => {\n console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n\nremoveListener() will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified eventName, then removeListener() must be\ncalled multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the\ntime of emitting are called in order. This implies that any\nremoveListener() or removeAllListeners() calls after emitting and\nbefore the last listener finishes execution will not remove them from\nemit() in progress. Subsequent events behave as expected.
import { EventEmitter } from 'node:events';\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\n\nconst callbackA = () => {\n console.log('A');\n myEmitter.removeListener('event', callbackB);\n};\n\nconst callbackB = () => {\n console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n// Prints:\n// A\n// B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n// Prints:\n// A\n\nconst EventEmitter = require('node:events');\nclass MyEmitter extends EventEmitter {}\nconst myEmitter = new MyEmitter();\n\nconst callbackA = () => {\n console.log('A');\n myEmitter.removeListener('event', callbackB);\n};\n\nconst callbackB = () => {\n console.log('B');\n};\n\nmyEmitter.on('event', callbackA);\n\nmyEmitter.on('event', callbackB);\n\n// callbackA removes listener callbackB but it will still be called.\n// Internal listener array at time of emit [callbackA, callbackB]\nmyEmitter.emit('event');\n// Prints:\n// A\n// B\n\n// callbackB is now removed.\n// Internal listener array [callbackA]\nmyEmitter.emit('event');\n// Prints:\n// A\n\nBecause listeners are managed using an internal array, calling this will\nchange the position indexes of any listener registered after the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it means that any copies of the listener array as returned by\nthe emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single\nevent (as in the example below), removeListener() will remove the most\nrecently added instance. In the example the once('ping')\nlistener is removed:
import { EventEmitter } from 'node:events';\nconst ee = new EventEmitter();\n\nfunction pong() {\n console.log('pong');\n}\n\nee.on('ping', pong);\nee.once('ping', pong);\nee.removeListener('ping', pong);\n\nee.emit('ping');\nee.emit('ping');\n\nconst EventEmitter = require('node:events');\nconst ee = new EventEmitter();\n\nfunction pong() {\n console.log('pong');\n}\n\nee.on('ping', pong);\nee.once('ping', pong);\nee.removeListener('ping', pong);\n\nee.emit('ping');\nee.emit('ping');\n\nReturns a reference to the EventEmitter, so that calls can be chained.
By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. The emitter.setMaxListeners() method allows the limit to be\nmodified for this specific EventEmitter instance. The value can be set to\nInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).
import { EventEmitter } from 'node:events';\nconst emitter = new EventEmitter();\nemitter.once('log', () => console.log('log once'));\n\n// Returns a new Array with a function `onceWrapper` which has a property\n// `listener` which contains the original listener bound above\nconst listeners = emitter.rawListeners('log');\nconst logFnWrapper = listeners[0];\n\n// Logs \"log once\" to the console and does not unbind the `once` event\nlogFnWrapper.listener();\n\n// Logs \"log once\" to the console and removes the listener\nlogFnWrapper();\n\nemitter.on('log', () => console.log('log persistently'));\n// Will return a new Array with a single function bound by `.on()` above\nconst newListeners = emitter.rawListeners('log');\n\n// Logs \"log persistently\" twice\nnewListeners[0]();\nemitter.emit('log');\n\nconst EventEmitter = require('node:events');\nconst emitter = new EventEmitter();\nemitter.once('log', () => console.log('log once'));\n\n// Returns a new Array with a function `onceWrapper` which has a property\n// `listener` which contains the original listener bound above\nconst listeners = emitter.rawListeners('log');\nconst logFnWrapper = listeners[0];\n\n// Logs \"log once\" to the console and does not unbind the `once` event\nlogFnWrapper.listener();\n\n// Logs \"log once\" to the console and removes the listener\nlogFnWrapper();\n\nemitter.on('log', () => console.log('log persistently'));\n// Will return a new Array with a single function bound by `.on()` above\nconst newListeners = emitter.rawListeners('log');\n\n// Logs \"log persistently\" twice\nnewListeners[0]();\nemitter.emit('log');\n"
},
{
"textRaw": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`",
"name": "[Symbol.for('nodejs.rejection')]",
"type": "method",
"meta": {
"added": [
"v13.4.0",
"v12.16.0"
],
"changes": [
{
"version": [
"v17.4.0",
"v16.14.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41267",
"description": "No longer experimental."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`eventName` {string|symbol}",
"name": "eventName",
"type": "string|symbol"
},
{
"textRaw": "`...args` {any}",
"name": "...args",
"type": "any",
"optional": true
}
]
}
],
"desc": "The Symbol.for('nodejs.rejection') method is called in case a\npromise rejection happens when emitting an event and\ncaptureRejections is enabled on the emitter.\nIt is possible to use events.captureRejectionSymbol in\nplace of Symbol.for('nodejs.rejection').
import { EventEmitter, captureRejectionSymbol } from 'node:events';\n\nclass MyClass extends EventEmitter {\n constructor() {\n super({ captureRejections: true });\n }\n\n [captureRejectionSymbol](err, event, ...args) {\n console.log('rejection happened for', event, 'with', err, ...args);\n this.destroy(err);\n }\n\n destroy(err) {\n // Tear the resource down here.\n }\n}\n\nconst { EventEmitter, captureRejectionSymbol } = require('node:events');\n\nclass MyClass extends EventEmitter {\n constructor() {\n super({ captureRejections: true });\n }\n\n [captureRejectionSymbol](err, event, ...args) {\n console.log('rejection happened for', event, 'with', err, ...args);\n this.destroy(err);\n }\n\n destroy(err) {\n // Tear the resource down here.\n }\n}\n"
}
]
},
{
"textRaw": "Class: `events.EventEmitterAsyncResource extends EventEmitter`",
"name": "events.EventEmitterAsyncResource extends EventEmitter",
"type": "class",
"meta": {
"added": [
"v17.4.0",
"v16.14.0"
],
"changes": []
},
"desc": "Integrates EventEmitter with <AsyncResource> for EventEmitters that\nrequire manual async tracking. Specifically, all events emitted by instances\nof events.EventEmitterAsyncResource will run within its async context.
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';\nimport { notStrictEqual, strictEqual } from 'node:assert';\nimport { executionAsyncId, triggerAsyncId } from 'node:async_hooks';\n\n// Async tracking tooling will identify this as 'Q'.\nconst ee1 = new EventEmitterAsyncResource({ name: 'Q' });\n\n// 'foo' listeners will run in the EventEmitters async context.\nee1.on('foo', () => {\n strictEqual(executionAsyncId(), ee1.asyncId);\n strictEqual(triggerAsyncId(), ee1.triggerAsyncId);\n});\n\nconst ee2 = new EventEmitter();\n\n// 'foo' listeners on ordinary EventEmitters that do not track async\n// context, however, run in the same async context as the emit().\nee2.on('foo', () => {\n notStrictEqual(executionAsyncId(), ee2.asyncId);\n notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);\n});\n\nPromise.resolve().then(() => {\n ee1.emit('foo');\n ee2.emit('foo');\n});\n\nconst { EventEmitterAsyncResource, EventEmitter } = require('node:events');\nconst { notStrictEqual, strictEqual } = require('node:assert');\nconst { executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\n// Async tracking tooling will identify this as 'Q'.\nconst ee1 = new EventEmitterAsyncResource({ name: 'Q' });\n\n// 'foo' listeners will run in the EventEmitters async context.\nee1.on('foo', () => {\n strictEqual(executionAsyncId(), ee1.asyncId);\n strictEqual(triggerAsyncId(), ee1.triggerAsyncId);\n});\n\nconst ee2 = new EventEmitter();\n\n// 'foo' listeners on ordinary EventEmitters that do not track async\n// context, however, run in the same async context as the emit().\nee2.on('foo', () => {\n notStrictEqual(executionAsyncId(), ee2.asyncId);\n notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);\n});\n\nPromise.resolve().then(() => {\n ee1.emit('foo');\n ee2.emit('foo');\n});\n\nThe EventEmitterAsyncResource class has the same methods and takes the\nsame options as EventEmitter and AsyncResource themselves.
The returned AsyncResource object has an additional eventEmitter property\nthat provides a reference to this EventEmitterAsyncResource.
Call all destroy hooks. This should only ever be called once. An error will\nbe thrown if it is called more than once. This must be manually called. If\nthe resource is left to be collected by the GC then the destroy hooks will\nnever be called.
By default, a maximum of 10 listeners can be registered for any single\nevent. This limit can be changed for individual EventEmitter instances\nusing the emitter.setMaxListeners(n) method. To change the default\nfor all EventEmitter instances, the events.defaultMaxListeners\nproperty can be used. If this value is not a positive number, a RangeError\nis thrown.
Take caution when setting the events.defaultMaxListeners because the\nchange affects all EventEmitter instances, including those created before\nthe change is made. However, calling emitter.setMaxListeners(n) still has\nprecedence over events.defaultMaxListeners.
This is not a hard limit. The EventEmitter instance will allow\nmore listeners to be added but will output a trace warning to stderr indicating\nthat a \"possible EventEmitter memory leak\" has been detected. For any single\nEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()\nmethods can be used to temporarily avoid this warning:
defaultMaxListeners has no effect on AbortSignal instances. While it is\nstill possible to use emitter.setMaxListeners(n) to set a warning limit\nfor individual AbortSignal instances, per default AbortSignal instances will not warn.
import { EventEmitter } from 'node:events';\nconst emitter = new EventEmitter();\nemitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n // do stuff\n emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n\nconst EventEmitter = require('node:events');\nconst emitter = new EventEmitter();\nemitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n // do stuff\n emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n\nThe --trace-warnings command-line flag can be used to display the\nstack trace for such warnings.
The emitted warning can be inspected with process.on('warning') and will\nhave the additional emitter, type, and count properties, referring to\nthe event emitter instance, the event's name and the number of attached\nlisteners, respectively.\nIts name property is set to 'MaxListenersExceededWarning'.
This symbol shall be used to install a listener for only monitoring 'error'\nevents. Listeners installed using this symbol are called before the regular\n'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an\n'error' event is emitted. Therefore, the process will still crash if no\nregular 'error' listener is installed.
Change the default captureRejections option on all new EventEmitter objects.
See how to write a custom rejection handler.
", "shortDesc": "`Symbol.for('nodejs.rejection')`" } ], "methods": [ { "textRaw": "`events.getEventListeners(emitterOrTarget, eventName)`", "name": "getEventListeners", "type": "method", "meta": { "added": [ "v15.2.0", "v14.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`emitterOrTarget` {EventEmitter|EventTarget}", "name": "emitterOrTarget", "type": "EventEmitter|EventTarget" }, { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ], "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" } } ], "desc": "Returns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on\nthe emitter.
For EventTargets this is the only way to get the event listeners for the\nevent target. This is useful for debugging and diagnostic purposes.
import { getEventListeners, EventEmitter } from 'node:events';\n\n{\n const ee = new EventEmitter();\n const listener = () => console.log('Events are fun');\n ee.on('foo', listener);\n console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]\n}\n{\n const et = new EventTarget();\n const listener = () => console.log('Events are fun');\n et.addEventListener('foo', listener);\n console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]\n}\n\nconst { getEventListeners, EventEmitter } = require('node:events');\n\n{\n const ee = new EventEmitter();\n const listener = () => console.log('Events are fun');\n ee.on('foo', listener);\n console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]\n}\n{\n const et = new EventTarget();\n const listener = () => console.log('Events are fun');\n et.addEventListener('foo', listener);\n console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]\n}\n"
},
{
"textRaw": "`events.getMaxListeners(emitterOrTarget)`",
"name": "getMaxListeners",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`emitterOrTarget` {EventEmitter|EventTarget}",
"name": "emitterOrTarget",
"type": "EventEmitter|EventTarget"
}
],
"return": {
"textRaw": "Returns: {number}",
"name": "return",
"type": "number"
}
}
],
"desc": "Returns the currently set max amount of listeners.
\nFor EventEmitters this behaves exactly the same as calling .getMaxListeners on\nthe emitter.
For EventTargets this is the only way to get the max event listeners for the\nevent target. If the number of event handlers on a single EventTarget exceeds\nthe max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';\n\n{\n const ee = new EventEmitter();\n console.log(getMaxListeners(ee)); // 10\n setMaxListeners(11, ee);\n console.log(getMaxListeners(ee)); // 11\n}\n{\n const et = new EventTarget();\n console.log(getMaxListeners(et)); // 10\n setMaxListeners(11, et);\n console.log(getMaxListeners(et)); // 11\n}\n\nconst { getMaxListeners, setMaxListeners, EventEmitter } = require('node:events');\n\n{\n const ee = new EventEmitter();\n console.log(getMaxListeners(ee)); // 10\n setMaxListeners(11, ee);\n console.log(getMaxListeners(ee)); // 11\n}\n{\n const et = new EventTarget();\n console.log(getMaxListeners(et)); // 10\n setMaxListeners(11, et);\n console.log(getMaxListeners(et)); // 11\n}\n"
},
{
"textRaw": "`events.once(emitter, name[, options])`",
"name": "once",
"type": "method",
"meta": {
"added": [
"v11.13.0",
"v10.16.0"
],
"changes": [
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/34912",
"description": "The `signal` option is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`emitter` {EventEmitter}",
"name": "emitter",
"type": "EventEmitter"
},
{
"textRaw": "`name` {string|symbol}",
"name": "name",
"type": "string|symbol"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} Can be used to cancel waiting for the event.",
"name": "signal",
"type": "AbortSignal",
"desc": "Can be used to cancel waiting for the event."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise}",
"name": "return",
"type": "Promise"
}
}
],
"desc": "Creates a Promise that is fulfilled when the EventEmitter emits the given\nevent or that is rejected if the EventEmitter emits 'error' while waiting.\nThe Promise will resolve with an array of all the arguments emitted to the\ngiven event.
This method is intentionally generic and works with the web platform\nEventTarget interface, which has no special\n'error' event semantics and does not listen to the 'error' event.
import { once, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ee = new EventEmitter();\n\nprocess.nextTick(() => {\n ee.emit('myevent', 42);\n});\n\nconst [value] = await once(ee, 'myevent');\nconsole.log(value);\n\nconst err = new Error('kaboom');\nprocess.nextTick(() => {\n ee.emit('error', err);\n});\n\ntry {\n await once(ee, 'myevent');\n} catch (err) {\n console.error('error happened', err);\n}\n\nconst { once, EventEmitter } = require('node:events');\n\nasync function run() {\n const ee = new EventEmitter();\n\n process.nextTick(() => {\n ee.emit('myevent', 42);\n });\n\n const [value] = await once(ee, 'myevent');\n console.log(value);\n\n const err = new Error('kaboom');\n process.nextTick(() => {\n ee.emit('error', err);\n });\n\n try {\n await once(ee, 'myevent');\n } catch (err) {\n console.error('error happened', err);\n }\n}\n\nrun();\n\nThe special handling of the 'error' event is only used when events.once()\nis used to wait for another event. If events.once() is used to wait for the\n'error' event itself, then it is treated as any other kind of event without\nspecial handling:
import { EventEmitter, once } from 'node:events';\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n .then(([err]) => console.log('ok', err.message))\n .catch((err) => console.error('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n\nconst { EventEmitter, once } = require('node:events');\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n .then(([err]) => console.log('ok', err.message))\n .catch((err) => console.error('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n\nAn <AbortSignal> can be used to cancel waiting for the event:
import { EventEmitter, once } from 'node:events';\n\nconst ee = new EventEmitter();\nconst ac = new AbortController();\n\nasync function foo(emitter, event, signal) {\n try {\n await once(emitter, event, { signal });\n console.log('event emitted!');\n } catch (error) {\n if (error.name === 'AbortError') {\n console.error('Waiting for the event was canceled!');\n } else {\n console.error('There was an error', error.message);\n }\n }\n}\n\nfoo(ee, 'foo', ac.signal);\nac.abort(); // Prints: Waiting for the event was canceled!\n\nconst { EventEmitter, once } = require('node:events');\n\nconst ee = new EventEmitter();\nconst ac = new AbortController();\n\nasync function foo(emitter, event, signal) {\n try {\n await once(emitter, event, { signal });\n console.log('event emitted!');\n } catch (error) {\n if (error.name === 'AbortError') {\n console.error('Waiting for the event was canceled!');\n } else {\n console.error('There was an error', error.message);\n }\n }\n}\n\nfoo(ee, 'foo', ac.signal);\nac.abort(); // Prints: Waiting for the event was canceled!\n",
"modules": [
{
"textRaw": "Caveats when awaiting multiple events",
"name": "caveats_when_awaiting_multiple_events",
"type": "module",
"desc": "It is important to be aware of execution order when using the events.once()\nmethod to await multiple events.
Conventional event listeners are called synchronously when the event is\nemitted. This guarantees that execution will not proceed beyond the emitted\nevent until all listeners have finished executing.
\nThe same is not true when awaiting Promises returned by events.once().\nPromise tasks are not handled until after the current execution stack runs to\ncompletion, which means that multiple events could be emitted before\nasynchronous execution continues from the relevant await statement.
As a result, events can be \"missed\" if a series of await events.once()\nstatements is used to listen to multiple events, since there might be times\nwhere more than one event is emitted during the same phase of the event loop.\n(The same is true when using process.nextTick() to emit events, because the\ntasks queued by process.nextTick() are executed before Promise tasks.)
import { EventEmitter, once } from 'node:events';\nimport process from 'node:process';\n\nconst myEE = new EventEmitter();\n\nasync function listen() {\n await once(myEE, 'foo');\n console.log('foo');\n\n // This Promise will never resolve, because the 'bar' event will\n // have already been emitted before the next line is executed.\n await once(myEE, 'bar');\n console.log('bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('foo');\n myEE.emit('bar');\n});\n\nlisten().then(() => console.log('done'));\n\nconst { EventEmitter, once } = require('node:events');\n\nconst myEE = new EventEmitter();\n\nasync function listen() {\n await once(myEE, 'foo');\n console.log('foo');\n\n // This Promise will never resolve, because the 'bar' event will\n // have already been emitted before the next line is executed.\n await once(myEE, 'bar');\n console.log('bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('foo');\n myEE.emit('bar');\n});\n\nlisten().then(() => console.log('done'));\n\nTo catch multiple events, create all of the Promises before awaiting any of\nthem. This is usually made easier by using Promise.all(), Promise.race(),\nor Promise.allSettled():
import { EventEmitter, once } from 'node:events';\nimport process from 'node:process';\n\nconst myEE = new EventEmitter();\n\nasync function listen() {\n await Promise.all([\n once(myEE, 'foo'),\n once(myEE, 'bar'),\n ]);\n console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('foo');\n myEE.emit('bar');\n});\n\nlisten().then(() => console.log('done'));\n\nconst { EventEmitter, once } = require('node:events');\n\nconst myEE = new EventEmitter();\n\nasync function listen() {\n await Promise.all([\n once(myEE, 'bar'),\n once(myEE, 'foo'),\n ]);\n console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n myEE.emit('foo');\n myEE.emit('bar');\n});\n\nlisten().then(() => console.log('done'));\n",
"displayName": "Caveats when awaiting multiple events"
}
]
},
{
"textRaw": "`events.listenerCount(emitterOrTarget, eventName)`",
"name": "listenerCount",
"type": "method",
"meta": {
"added": [
"v0.9.12"
],
"changes": [
{
"version": "v25.4.0",
"pr-url": "https://github.com/nodejs/node/pull/60214",
"description": "Now accepts EventTarget arguments."
},
{
"version": "v25.4.0",
"pr-url": "https://github.com/nodejs/node/pull/60214",
"description": "Deprecation revoked."
},
{
"version": "v3.2.0",
"pr-url": "https://github.com/nodejs/node/pull/2349",
"description": "Documentation-only deprecation."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`emitterOrTarget` {EventEmitter|EventTarget}",
"name": "emitterOrTarget",
"type": "EventEmitter|EventTarget"
},
{
"textRaw": "`eventName` {string|symbol}",
"name": "eventName",
"type": "string|symbol"
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Returns the number of registered listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listenerCount\non the emitter.
For EventTargets this is the only way to obtain the listener count. This can\nbe useful for debugging and diagnostic purposes.
import { EventEmitter, listenerCount } from 'node:events';\n\n{\n const ee = new EventEmitter();\n ee.on('event', () => {});\n ee.on('event', () => {});\n console.log(listenerCount(ee, 'event')); // 2\n}\n{\n const et = new EventTarget();\n et.addEventListener('event', () => {});\n et.addEventListener('event', () => {});\n console.log(listenerCount(et, 'event')); // 2\n}\n\nconst { EventEmitter, listenerCount } = require('node:events');\n\n{\n const ee = new EventEmitter();\n ee.on('event', () => {});\n ee.on('event', () => {});\n console.log(listenerCount(ee, 'event')); // 2\n}\n{\n const et = new EventTarget();\n et.addEventListener('event', () => {});\n et.addEventListener('event', () => {});\n console.log(listenerCount(et, 'event')); // 2\n}\n"
},
{
"textRaw": "`events.on(emitter, eventName[, options])`",
"name": "on",
"type": "method",
"meta": {
"added": [
"v13.6.0",
"v12.16.0"
],
"changes": [
{
"version": [
"v22.0.0",
"v20.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/52080",
"description": "Support `highWaterMark` and `lowWaterMark` options, For consistency. Old options are still supported."
},
{
"version": [
"v20.0.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41276",
"description": "The `close`, `highWatermark`, and `lowWatermark` options are supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`emitter` {EventEmitter}",
"name": "emitter",
"type": "EventEmitter"
},
{
"textRaw": "`eventName` {string|symbol} The name of the event being listened for",
"name": "eventName",
"type": "string|symbol",
"desc": "The name of the event being listened for"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} Can be used to cancel awaiting events.",
"name": "signal",
"type": "AbortSignal",
"desc": "Can be used to cancel awaiting events."
},
{
"textRaw": "`close` {string[]} Names of events that will end the iteration.",
"name": "close",
"type": "string[]",
"desc": "Names of events that will end the iteration."
},
{
"textRaw": "`highWaterMark` {integer} **Default:** `Number.MAX_SAFE_INTEGER` The high watermark. The emitter is paused every time the size of events being buffered is higher than it. Supported only on emitters implementing `pause()` and `resume()` methods.",
"name": "highWaterMark",
"type": "integer",
"default": "`Number.MAX_SAFE_INTEGER` The high watermark. The emitter is paused every time the size of events being buffered is higher than it. Supported only on emitters implementing `pause()` and `resume()` methods"
},
{
"textRaw": "`lowWaterMark` {integer} **Default:** `1` The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. Supported only on emitters implementing `pause()` and `resume()` methods.",
"name": "lowWaterMark",
"type": "integer",
"default": "`1` The low watermark. The emitter is resumed every time the size of events being buffered is lower than it. Supported only on emitters implementing `pause()` and `resume()` methods"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {AsyncIterator} that iterates `eventName` events emitted by the `emitter`",
"name": "return",
"type": "AsyncIterator",
"desc": "that iterates `eventName` events emitted by the `emitter`"
}
}
],
"desc": "import { on, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ee = new EventEmitter();\n\n// Emit later on\nprocess.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n});\n\nfor await (const event of on(ee, 'foo')) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n}\n// Unreachable here\n\nconst { on, EventEmitter } = require('node:events');\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo')) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n\nReturns an AsyncIterator that iterates eventName events. It will throw\nif the EventEmitter emits 'error'. It removes all listeners when\nexiting the loop. The value returned by each iteration is an array\ncomposed of the emitted event arguments.
An <AbortSignal> can be used to cancel waiting on events:
import { on, EventEmitter } from 'node:events';\nimport process from 'node:process';\n\nconst ac = new AbortController();\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo', { signal: ac.signal })) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n\nprocess.nextTick(() => ac.abort());\n\nconst { on, EventEmitter } = require('node:events');\n\nconst ac = new AbortController();\n\n(async () => {\n const ee = new EventEmitter();\n\n // Emit later on\n process.nextTick(() => {\n ee.emit('foo', 'bar');\n ee.emit('foo', 42);\n });\n\n for await (const event of on(ee, 'foo', { signal: ac.signal })) {\n // The execution of this inner block is synchronous and it\n // processes one event at a time (even with await). Do not use\n // if concurrent execution is required.\n console.log(event); // prints ['bar'] [42]\n }\n // Unreachable here\n})();\n\nprocess.nextTick(() => ac.abort());\n"
},
{
"textRaw": "`events.setMaxListeners(n[, ...eventTargets])`",
"name": "setMaxListeners",
"type": "method",
"meta": {
"added": [
"v15.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`n` {number} A non-negative number. The maximum number of listeners per `EventTarget` event.",
"name": "n",
"type": "number",
"desc": "A non-negative number. The maximum number of listeners per `EventTarget` event."
},
{
"name": "...eventTargets",
"optional": true
}
]
}
],
"desc": "import { setMaxListeners, EventEmitter } from 'node:events';\n\nconst target = new EventTarget();\nconst emitter = new EventEmitter();\n\nsetMaxListeners(5, target, emitter);\n\nconst {\n setMaxListeners,\n EventEmitter,\n} = require('node:events');\n\nconst target = new EventTarget();\nconst emitter = new EventEmitter();\n\nsetMaxListeners(5, target, emitter);\n"
},
{
"textRaw": "`events.addAbortListener(signal, listener)`",
"name": "addAbortListener",
"type": "method",
"meta": {
"added": [
"v20.5.0",
"v18.18.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57765",
"description": "Change stability index for this feature from Experimental to Stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`signal` {AbortSignal}",
"name": "signal",
"type": "AbortSignal"
},
{
"textRaw": "`listener` {Function|EventListener}",
"name": "listener",
"type": "Function|EventListener"
}
],
"return": {
"textRaw": "Returns: {Disposable} A Disposable that removes the `abort` listener.",
"name": "return",
"type": "Disposable",
"desc": "A Disposable that removes the `abort` listener."
}
}
],
"desc": "Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may\nlead to resource leaks since another third party with the signal can\ncall e.stopImmediatePropagation(). Unfortunately Node.js cannot change\nthis since it would violate the web standard. Additionally, the original\nAPI makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these\ntwo issues by listening to the event such that stopImmediatePropagation does\nnot prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
\nconst { addAbortListener } = require('node:events');\n\nfunction example(signal) {\n signal.addEventListener('abort', (e) => e.stopImmediatePropagation());\n // addAbortListener() returns a disposable, so the `using` keyword ensures\n // the abort listener is automatically removed when this scope exits.\n using _ = addAbortListener(signal, (e) => {\n // Do something when signal is aborted.\n });\n}\n\nimport { addAbortListener } from 'node:events';\n\nfunction example(signal) {\n signal.addEventListener('abort', (e) => e.stopImmediatePropagation());\n // addAbortListener() returns a disposable, so the `using` keyword ensures\n // the abort listener is automatically removed when this scope exits.\n using _ = addAbortListener(signal, (e) => {\n // Do something when signal is aborted.\n });\n}\n"
}
],
"source": "doc/api/events.md"
},
{
"textRaw": "File system",
"name": "file_system",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:fs module enables interacting with the file system in a\nway modeled on standard POSIX functions.
To use the promise-based APIs:
\nimport * as fs from 'node:fs/promises';\n\nconst fs = require('node:fs/promises');\n\nTo use the callback and sync APIs:
\nimport * as fs from 'node:fs';\n\nconst fs = require('node:fs');\n\nAll file system operations have synchronous, callback, and promise-based\nforms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
", "modules": [ { "textRaw": "Promise example", "name": "promise_example", "type": "module", "desc": "Promise-based operations return a promise that is fulfilled when the\nasynchronous operation is complete.
\nimport { unlink } from 'node:fs/promises';\n\ntry {\n await unlink('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (error) {\n console.error('there was an error:', error.message);\n}\n\nconst { unlink } = require('node:fs/promises');\n\n(async function(path) {\n try {\n await unlink(path);\n console.log(`successfully deleted ${path}`);\n } catch (error) {\n console.error('there was an error:', error.message);\n }\n})('/tmp/hello');\n",
"displayName": "Promise example"
},
{
"textRaw": "Callback example",
"name": "callback_example",
"type": "module",
"desc": "The callback form takes a completion callback function as its last\nargument and invokes the operation asynchronously. The arguments passed to\nthe completion callback depend on the method, but the first argument is always\nreserved for an exception. If the operation is completed successfully, then\nthe first argument is null or undefined.
import { unlink } from 'node:fs';\n\nunlink('/tmp/hello', (err) => {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});\n\nconst { unlink } = require('node:fs');\n\nunlink('/tmp/hello', (err) => {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});\n\nThe callback-based versions of the node:fs module APIs are preferable over\nthe use of the promise APIs when maximal performance (both in terms of\nexecution time and memory allocation) is required.
The synchronous APIs block the Node.js event loop and further JavaScript\nexecution until the operation is complete. Exceptions are thrown immediately\nand can be handled using try…catch, or can be allowed to bubble up.
import { unlinkSync } from 'node:fs';\n\ntry {\n unlinkSync('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (err) {\n // handle the error\n}\n\nconst { unlinkSync } = require('node:fs');\n\ntry {\n unlinkSync('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (err) {\n // handle the error\n}\n",
"displayName": "Synchronous example"
},
{
"textRaw": "Promises API",
"name": "promises_api",
"type": "module",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/31553",
"description": "Exposed as `require('fs/promises')`."
},
{
"version": [
"v11.14.0",
"v10.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/26581",
"description": "This API is no longer experimental."
},
{
"version": "v10.1.0",
"pr-url": "https://github.com/nodejs/node/pull/20504",
"description": "The API is accessible via `require('fs').promises` only."
}
]
},
"desc": "The fs/promises API provides asynchronous file system methods that return\npromises.
The promise APIs use the underlying Node.js threadpool to perform file\nsystem operations off the event loop thread. These operations are not\nsynchronized or threadsafe. Care must be taken when performing multiple\nconcurrent modifications on the same file or data corruption may occur.
", "classes": [ { "textRaw": "Class: `FileHandle`", "name": "FileHandle", "type": "class", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "A <FileHandle> object is an object wrapper for a numeric file descriptor.
Instances of the <FileHandle> object are created by the fsPromises.open()\nmethod.
All <FileHandle> objects are <EventEmitter>s.
If a <FileHandle> is not closed using the filehandle.close() method, it will\ntry to automatically close the file descriptor and emit a process warning,\nhelping to prevent memory leaks. Please do not rely on this behavior because\nit can be unreliable and the file may not be closed. Instead, always explicitly\nclose <FileHandle>s. Node.js may change this behavior in the future.
The 'close' event is emitted when the <FileHandle> has been closed and can no\nlonger be used.
Alias of filehandle.writeFile().
When operating on file handles, the mode cannot be changed from what it was set\nto with fsPromises.open(). Therefore, this is equivalent to\nfilehandle.writeFile().
Modifies the permissions on the file. See chmod(2).
Changes the ownership of the file. A wrapper for chown(2).
Closes the file handle after waiting for any pending operation on the handle to\ncomplete.
\nimport { open } from 'node:fs/promises';\n\nlet filehandle;\ntry {\n filehandle = await open('thefile.txt', 'r');\n} finally {\n await filehandle?.close();\n}\n"
},
{
"textRaw": "`filehandle.createReadStream([options])`",
"name": "createReadStream",
"type": "method",
"meta": {
"added": [
"v16.11.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`encoding` {string} **Default:** `null`",
"name": "encoding",
"type": "string",
"default": "`null`"
},
{
"textRaw": "`autoClose` {boolean} **Default:** `true`",
"name": "autoClose",
"type": "boolean",
"default": "`true`"
},
{
"textRaw": "`emitClose` {boolean} **Default:** `true`",
"name": "emitClose",
"type": "boolean",
"default": "`true`"
},
{
"textRaw": "`start` {integer}",
"name": "start",
"type": "integer"
},
{
"textRaw": "`end` {integer} **Default:** `Infinity`",
"name": "end",
"type": "integer",
"default": "`Infinity`"
},
{
"textRaw": "`highWaterMark` {integer} **Default:** `64 * 1024`",
"name": "highWaterMark",
"type": "integer",
"default": "`64 * 1024`"
},
{
"textRaw": "`signal` {AbortSignal|undefined} **Default:** `undefined`",
"name": "signal",
"type": "AbortSignal|undefined",
"default": "`undefined`"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {fs.ReadStream}",
"name": "return",
"type": "fs.ReadStream"
}
}
],
"desc": "options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If start is\nomitted or undefined, filehandle.createReadStream() reads sequentially from\nthe current file position. The encoding can be any one of those accepted by\n<Buffer>.
If the FileHandle points to a character device that only supports blocking\nreads (such as keyboard or sound card), read operations do not finish until data\nis available. This can prevent the process from exiting and the stream from\nclosing naturally.
By default, the stream will emit a 'close' event after it has been\ndestroyed. Set the emitClose option to false to change this behavior.
import { open } from 'node:fs/promises';\n\nconst fd = await open('/dev/input/event0');\n// Create a stream from some character device.\nconst stream = fd.createReadStream();\nsetTimeout(() => {\n stream.close(); // This may not close the stream.\n // Artificially marking end-of-stream, as if the underlying resource had\n // indicated end-of-file by itself, allows the stream to close.\n // This does not cancel pending read operations, and if there is such an\n // operation, the process may still not be able to exit successfully\n // until it finishes.\n stream.push(null);\n stream.read(0);\n}, 100);\n\nIf autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is the application's responsibility to close it and make\nsure there's no file descriptor leak. If autoClose is set to true (default\nbehavior), on 'error' or 'end' the file descriptor will be closed\nautomatically.
An example to read the last 10 bytes of a file which is 100 bytes long:
\nimport { open } from 'node:fs/promises';\n\nconst fd = await open('sample.txt');\nfd.createReadStream({ start: 90, end: 99 });\n"
},
{
"textRaw": "`filehandle.createWriteStream([options])`",
"name": "createWriteStream",
"type": "method",
"meta": {
"added": [
"v16.11.0"
],
"changes": [
{
"version": [
"v21.0.0",
"v20.10.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50093",
"description": "The `flush` option is now supported."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
},
{
"textRaw": "`autoClose` {boolean} **Default:** `true`",
"name": "autoClose",
"type": "boolean",
"default": "`true`"
},
{
"textRaw": "`emitClose` {boolean} **Default:** `true`",
"name": "emitClose",
"type": "boolean",
"default": "`true`"
},
{
"textRaw": "`start` {integer}",
"name": "start",
"type": "integer"
},
{
"textRaw": "`highWaterMark` {number} **Default:** `16384`",
"name": "highWaterMark",
"type": "number",
"default": "`16384`"
},
{
"textRaw": "`flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. **Default:** `false`.",
"name": "flush",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, the underlying file descriptor is flushed prior to closing it."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {fs.WriteStream}",
"name": "return",
"type": "fs.WriteStream"
}
}
],
"desc": "options may also include a start option to allow writing data at some\nposition past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than\nreplacing it may require the flags open option to be set to r+ rather than\nthe default r. The encoding can be any one of those accepted by <Buffer>.
If autoClose is set to true (default behavior) on 'error' or 'finish'\nthe file descriptor will be closed automatically. If autoClose is false,\nthen the file descriptor won't be closed, even if there's an error.\nIt is the application's responsibility to close it and make sure there's no\nfile descriptor leak.
By default, the stream will emit a 'close' event after it has been\ndestroyed. Set the emitClose option to false to change this behavior.
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details.
Unlike filehandle.sync this method does not flush modified metadata.
Reads data from the file and stores that in the given buffer.
\nIf the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.
" }, { "textRaw": "`filehandle.read([options])`", "name": "read", "type": "method", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [ { "version": "v21.0.0", "pr-url": "https://github.com/nodejs/node/pull/42835", "description": "Accepts bigint values as `position`." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. **Default:** `Buffer.alloc(16384)`", "name": "buffer", "type": "Buffer|TypedArray|DataView", "default": "`Buffer.alloc(16384)`", "desc": "A buffer that will be filled with the file data read." }, { "textRaw": "`offset` {integer} The location in the buffer at which to start filling. **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`", "desc": "The location in the buffer at which to start filling." }, { "textRaw": "`length` {integer} The number of bytes to read. **Default:** `buffer.byteLength - offset`", "name": "length", "type": "integer", "default": "`buffer.byteLength - offset`", "desc": "The number of bytes to read." }, { "textRaw": "`position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged. **Default:**: `null`", "name": "position", "type": "integer|bigint|null", "default": ": `null`", "desc": "The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged." } ], "optional": true } ], "return": { "textRaw": "Returns: {Promise} Fulfills upon success with an object with two properties:", "name": "return", "type": "Promise", "desc": "Fulfills upon success with an object with two properties:", "options": [ { "textRaw": "`bytesRead` {integer} The number of bytes read", "name": "bytesRead", "type": "integer", "desc": "The number of bytes read" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer` argument.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A reference to the passed in `buffer` argument." } ] } } ], "desc": "Reads data from the file and stores that in the given buffer.
\nIf the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.
" }, { "textRaw": "`filehandle.read(buffer[, options])`", "name": "read", "type": "method", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v21.0.0", "pr-url": "https://github.com/nodejs/node/pull/42835", "description": "Accepts bigint values as `position`." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A buffer that will be filled with the file data read." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`offset` {integer} The location in the buffer at which to start filling. **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`", "desc": "The location in the buffer at which to start filling." }, { "textRaw": "`length` {integer} The number of bytes to read. **Default:** `buffer.byteLength - offset`", "name": "length", "type": "integer", "default": "`buffer.byteLength - offset`", "desc": "The number of bytes to read." }, { "textRaw": "`position` {integer|bigint|null} The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged. **Default:**: `null`", "name": "position", "type": "integer|bigint|null", "default": ": `null`", "desc": "The location where to begin reading data from the file. If `null` or `-1`, data will be read from the current file position, and the position will be updated. If `position` is a non-negative integer, the current file position will remain unchanged." } ], "optional": true } ], "return": { "textRaw": "Returns: {Promise} Fulfills upon success with an object with two properties:", "name": "return", "type": "Promise", "desc": "Fulfills upon success with an object with two properties:", "options": [ { "textRaw": "`bytesRead` {integer} The number of bytes read", "name": "bytesRead", "type": "integer", "desc": "The number of bytes read" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer` argument.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A reference to the passed in `buffer` argument." } ] } } ], "desc": "Reads data from the file and stores that in the given buffer.
\nIf the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.
" }, { "textRaw": "`filehandle.readableWebStream([options])`", "name": "readableWebStream", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." }, { "version": [ "v23.8.0", "v22.15.0" ], "pr-url": "https://github.com/nodejs/node/pull/55461", "description": "Removed option to create a 'bytes' stream. Streams are now always 'bytes' streams." }, { "version": [ "v20.0.0", "v18.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/46933", "description": "Added option to create a 'bytes' stream." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`autoClose` {boolean} When true, causes the {FileHandle} to be closed when the stream is closed. **Default:** `false`", "name": "autoClose", "type": "boolean", "default": "`false`", "desc": "When true, causes the {FileHandle} to be closed when the stream is closed." } ], "optional": true } ], "return": { "textRaw": "Returns: {ReadableStream}", "name": "return", "type": "ReadableStream" } } ], "desc": "Returns a byte-oriented ReadableStream that may be used to read the file's\ncontents.
An error will be thrown if this method is called more than once or is called\nafter the FileHandle is closed or closing.
import {\n open,\n} from 'node:fs/promises';\n\nconst file = await open('./some/file/to/read');\n\nfor await (const chunk of file.readableWebStream())\n console.log(chunk);\n\nawait file.close();\n\nconst {\n open,\n} = require('node:fs/promises');\n\n(async () => {\n const file = await open('./some/file/to/read');\n\n for await (const chunk of file.readableWebStream())\n console.log(chunk);\n\n await file.close();\n})();\n\nWhile the ReadableStream will read the file to completion, it will not\nclose the FileHandle automatically. User code must still call the\nfileHandle.close() method unless the autoClose option is set to true.
Asynchronously reads the entire contents of a file.
\nIf options is a string, then it specifies the encoding.
The <FileHandle> has to support reading.
If one or more filehandle.read() calls are made on a file handle and then a\nfilehandle.readFile() call is made, the data will be read from the current\nposition till the end of the file. It doesn't always read from the beginning\nof the file.
Convenience method to create a readline interface and stream over the file.\nSee filehandle.createReadStream() for the options.
import { open } from 'node:fs/promises';\n\nconst file = await open('./some/file/to/read');\n\nfor await (const line of file.readLines()) {\n console.log(line);\n}\n\nconst { open } = require('node:fs/promises');\n\n(async () => {\n const file = await open('./some/file/to/read');\n\n for await (const line of file.readLines()) {\n console.log(line);\n }\n})();\n"
},
{
"textRaw": "`filehandle.readv(buffers[, position])`",
"name": "readv",
"type": "method",
"meta": {
"added": [
"v13.13.0",
"v12.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`buffers` {Buffer[]|TypedArray[]|DataView[]}",
"name": "buffers",
"type": "Buffer[]|TypedArray[]|DataView[]"
},
{
"textRaw": "`position` {integer|null} The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. **Default:** `null`",
"name": "position",
"type": "integer|null",
"default": "`null`",
"desc": "The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfills upon success an object containing two properties:",
"name": "return",
"type": "Promise",
"desc": "Fulfills upon success an object containing two properties:",
"options": [
{
"textRaw": "`bytesRead` {integer} the number of bytes read",
"name": "bytesRead",
"type": "integer",
"desc": "the number of bytes read"
},
{
"textRaw": "`buffers` {Buffer[]|TypedArray[]|DataView[]} property containing a reference to the `buffers` input.",
"name": "buffers",
"type": "Buffer[]|TypedArray[]|DataView[]",
"desc": "property containing a reference to the `buffers` input."
}
]
}
}
],
"desc": "Read from a file and write to an array of <ArrayBufferView>s
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail.
Truncates the file.
\nIf the file was larger than len bytes, only the first len bytes will be\nretained in the file.
The following example retains only the first four bytes of the file:
\nimport { open } from 'node:fs/promises';\n\nlet filehandle = null;\ntry {\n filehandle = await open('temp.txt', 'r+');\n await filehandle.truncate(4);\n} finally {\n await filehandle?.close();\n}\n\nIf the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):
If len is negative then 0 will be used.
Change the file system timestamps of the object referenced by the <FileHandle>\nthen fulfills the promise with no arguments upon success.
Write buffer to the file.
The promise is fulfilled with an object containing two properties:
\nbytesWritten <integer> the number of bytes writtenbuffer <Buffer> | <TypedArray> | <DataView> a reference to the buffer written.It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the promise to be fulfilled (or rejected). For this\nscenario, use filehandle.createWriteStream().
On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
" }, { "textRaw": "`filehandle.write(buffer[, options])`", "name": "write", "type": "method", "meta": { "added": [ "v18.3.0", "v16.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView}", "name": "buffer", "type": "Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`offset` {integer} **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`" }, { "textRaw": "`length` {integer} **Default:** `buffer.byteLength - offset`", "name": "length", "type": "integer", "default": "`buffer.byteLength - offset`" }, { "textRaw": "`position` {integer|null} **Default:** `null`", "name": "position", "type": "integer|null", "default": "`null`" } ], "optional": true } ], "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" } } ], "desc": "Write buffer to the file.
Similar to the above filehandle.write function, this version takes an\noptional options object. If no options object is specified, it will\ndefault with the above values.
Write string to the file. If string is not a string, the promise is\nrejected with an error.
The promise is fulfilled with an object containing two properties:
\nbytesWritten <integer> the number of bytes writtenbuffer <string> a reference to the string written.It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the promise to be fulfilled (or rejected). For this\nscenario, use filehandle.createWriteStream().
On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
" }, { "textRaw": "`filehandle.writeFile(data, options)`", "name": "writeFile", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": [ "v15.14.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/37490", "description": "The `data` argument supports `AsyncIterable`, `Iterable`, and `Stream`." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `data` parameter won't coerce unsupported input to strings anymore." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream}", "name": "data", "type": "string|Buffer|TypedArray|DataView|AsyncIterable|Iterable|Stream" }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`encoding` {string|null} The expected character encoding when `data` is a string. **Default:** `'utf8'`", "name": "encoding", "type": "string|null", "default": "`'utf8'`", "desc": "The expected character encoding when `data` is a string." }, { "textRaw": "`signal` {AbortSignal|undefined} allows aborting an in-progress writeFile. **Default:** `undefined`", "name": "signal", "type": "AbortSignal|undefined", "default": "`undefined`", "desc": "allows aborting an in-progress writeFile." } ] } ], "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" } } ], "desc": "Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.\nThe promise is fulfilled with no arguments upon success.
If options is a string, then it specifies the encoding.
The <FileHandle> has to support writing.
It is unsafe to use filehandle.writeFile() multiple times on the same file\nwithout waiting for the promise to be fulfilled (or rejected).
If one or more filehandle.write() calls are made on a file handle and then a\nfilehandle.writeFile() call is made, the data will be written from the\ncurrent position till the end of the file. It doesn't always write from the\nbeginning of the file.
Write an array of <ArrayBufferView>s to the file.
The promise is fulfilled with an object containing a two properties:
\nbytesWritten <integer> the number of bytes writtenbuffers <Buffer[]> | <TypedArray[]> | <DataView[]> a reference to the buffers\ninput.It is unsafe to call writev() multiple times on the same file without waiting\nfor the promise to be fulfilled (or rejected).
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
" }, { "textRaw": "`filehandle[Symbol.asyncDispose]()`", "name": "[Symbol.asyncDispose]", "type": "method", "meta": { "added": [ "v20.4.0", "v18.18.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58467", "description": "No longer experimental." } ] }, "signatures": [ { "params": [] } ], "desc": "Calls filehandle.close() and returns a promise that fulfills when the\nfilehandle is closed.
Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. mode should be either the value fs.constants.F_OK\nor a mask consisting of the bitwise OR of any of fs.constants.R_OK,\nfs.constants.W_OK, and fs.constants.X_OK (e.g.\nfs.constants.W_OK | fs.constants.R_OK). Check File access constants for\npossible values of mode.
If the accessibility check is successful, the promise is fulfilled with no\nvalue. If any of the accessibility checks fail, the promise is rejected\nwith an <Error> object. The following example checks if the file /etc/passwd can be read and written by the current process.
import { access, constants } from 'node:fs/promises';\n\ntry {\n await access('/etc/passwd', constants.R_OK | constants.W_OK);\n console.log('can access');\n} catch {\n console.error('cannot access');\n}\n\nUsing fsPromises.access() to check for the accessibility of a file before\ncalling fsPromises.open() is not recommended. Doing so introduces a race\ncondition, since other processes may change the file's state between the two\ncalls. Instead, user code should open/read/write the file directly and handle\nthe error raised if the file is not accessible.
Asynchronously append data to a file, creating the file if it does not yet\nexist. 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()\nfor more details.
The path may be specified as a <FileHandle> that has been opened\nfor appending (using fsPromises.open()).
Changes the permissions of a file.
" }, { "textRaw": "`fsPromises.chown(path, uid, gid)`", "name": "chown", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`uid` {integer}", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer}", "name": "gid", "type": "integer" } ], "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." } } ], "desc": "Changes the ownership of a file.
" }, { "textRaw": "`fsPromises.copyFile(src, dest[, mode])`", "name": "copyFile", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/27044", "description": "Changed `flags` argument to `mode` and imposed stricter type validation." } ] }, "signatures": [ { "params": [ { "textRaw": "`src` {string|Buffer|URL} source filename to copy", "name": "src", "type": "string|Buffer|URL", "desc": "source filename to copy" }, { "textRaw": "`dest` {string|Buffer|URL} destination filename of the copy operation", "name": "dest", "type": "string|Buffer|URL", "desc": "destination filename of the copy operation" }, { "textRaw": "`mode` {integer} Optional modifiers that specify 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`) **Default:** `0`.", "name": "mode", "type": "integer", "default": "`0`", "desc": "Optional modifiers that specify 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`)", "options": [ { "textRaw": "`fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already exists.", "name": "fs.constants.COPYFILE_EXCL", "desc": "The copy operation will fail if `dest` already exists." }, { "textRaw": "`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.", "name": "fs.constants.COPYFILE_FICLONE", "desc": "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." }, { "textRaw": "`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.", "name": "fs.constants.COPYFILE_FICLONE_FORCE", "desc": "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." } ], "optional": true } ], "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." } } ], "desc": "Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists.
No guarantees are made about the atomicity of the copy operation. If an\nerror occurs after the destination file has been opened for writing, an attempt\nwill be made to remove the destination.
\nimport { copyFile, constants } from 'node:fs/promises';\n\ntry {\n await copyFile('source.txt', 'destination.txt');\n console.log('source.txt was copied to destination.txt');\n} catch {\n console.error('The file could not be copied');\n}\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ntry {\n await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);\n console.log('source.txt was copied to destination.txt');\n} catch {\n console.error('The file could not be copied');\n}\n"
},
{
"textRaw": "`fsPromises.cp(src, dest[, options])`",
"name": "cp",
"type": "method",
"meta": {
"added": [
"v16.7.0"
],
"changes": [
{
"version": "v22.3.0",
"pr-url": "https://github.com/nodejs/node/pull/53127",
"description": "This API is no longer experimental."
},
{
"version": [
"v20.1.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47084",
"description": "Accept an additional `mode` option to specify the copy behavior as the `mode` argument of `fs.copyFile()`."
},
{
"version": [
"v17.6.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41819",
"description": "Accepts an additional `verbatimSymlinks` option to specify whether to perform path resolution for symlinks."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`src` {string|URL} source path to copy.",
"name": "src",
"type": "string|URL",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string|URL} destination path to copy to.",
"name": "dest",
"type": "string|URL",
"desc": "destination path to copy to."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`dereference` {boolean} dereference symlinks. **Default:** `false`.",
"name": "dereference",
"type": "boolean",
"default": "`false`",
"desc": "dereference symlinks."
},
{
"textRaw": "`errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. **Default:** `false`.",
"name": "errorOnExist",
"type": "boolean",
"default": "`false`",
"desc": "when `force` is `false`, and the destination exists, throw an error."
},
{
"textRaw": "`filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false` **Default:** `undefined`.",
"name": "filter",
"type": "Function",
"default": "`undefined`",
"desc": "Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false`",
"options": [
{
"textRaw": "`src` {string} source path to copy.",
"name": "src",
"type": "string",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string} destination path to copy to.",
"name": "dest",
"type": "string",
"desc": "destination path to copy to."
},
{
"textRaw": "Returns: {boolean|Promise} A value that is coercible to `boolean` or a `Promise` that fulfils with such value.",
"name": "return",
"type": "boolean|Promise",
"desc": "A value that is coercible to `boolean` or a `Promise` that fulfils with such value."
}
]
},
{
"textRaw": "`force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`.",
"name": "force",
"type": "boolean",
"default": "`true`",
"desc": "overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior."
},
{
"textRaw": "`mode` {integer} modifiers for copy operation. **Default:** `0`. See `mode` flag of `fsPromises.copyFile()`.",
"name": "mode",
"type": "integer",
"default": "`0`. See `mode` flag of `fsPromises.copyFile()`",
"desc": "modifiers for copy operation."
},
{
"textRaw": "`preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. **Default:** `false`.",
"name": "preserveTimestamps",
"type": "boolean",
"default": "`false`",
"desc": "When `true` timestamps from `src` will be preserved."
},
{
"textRaw": "`recursive` {boolean} copy directories recursively **Default:** `false`",
"name": "recursive",
"type": "boolean",
"default": "`false`",
"desc": "copy directories recursively"
},
{
"textRaw": "`verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. **Default:** `false`",
"name": "verbatimSymlinks",
"type": "boolean",
"default": "`false`",
"desc": "When `true`, path resolution for symlinks will be skipped."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.",
"name": "return",
"type": "Promise",
"desc": "Fulfills with `undefined` upon success."
}
}
],
"desc": "Asynchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.
When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.
import { glob } from 'node:fs/promises';\n\nfor await (const entry of glob('**/*.js'))\n console.log(entry);\n\nconst { glob } = require('node:fs/promises');\n\n(async () => {\n for await (const entry of glob('**/*.js'))\n console.log(entry);\n})();\n"
},
{
"textRaw": "`fsPromises.lchmod(path, mode)`",
"name": "lchmod",
"type": "method",
"meta": {
"changes": [],
"deprecated": [
"v10.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`mode` {integer}",
"name": "mode",
"type": "integer"
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.",
"name": "return",
"type": "Promise",
"desc": "Fulfills with `undefined` upon success."
}
}
],
"desc": "Changes the permissions on a symbolic link.
\nThis method is only implemented on macOS.
" }, { "textRaw": "`fsPromises.lchown(path, uid, gid)`", "name": "lchown", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/21498", "description": "This API is no longer deprecated." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`uid` {integer}", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer}", "name": "gid", "type": "integer" } ], "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." } } ], "desc": "Changes the ownership on a symbolic link.
" }, { "textRaw": "`fsPromises.lutimes(path, atime, mtime)`", "name": "lutimes", "type": "method", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`atime` {number|string|Date}", "name": "atime", "type": "number|string|Date" }, { "textRaw": "`mtime` {number|string|Date}", "name": "mtime", "type": "number|string|Date" } ], "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." } } ], "desc": "Changes the access and modification times of a file in the same way as\nfsPromises.utimes(), with the difference that if the path refers to a\nsymbolic link, then the link is not dereferenced: instead, the timestamps of\nthe symbolic link itself are changed.
Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail.
Equivalent to fsPromises.stat() unless path refers to a symbolic link,\nin which case the link itself is stat-ed, not the file that it refers to.\nRefer to the POSIX lstat(2) document for more detail.
Asynchronously creates a directory.
\nThe optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfsPromises.mkdir() when path is a directory that exists results in a\nrejection only when recursive is false.
import { mkdir } from 'node:fs/promises';\n\ntry {\n const projectFolder = new URL('./test/project/', import.meta.url);\n const createDir = await mkdir(projectFolder, { recursive: true });\n\n console.log(`created ${createDir}`);\n} catch (err) {\n console.error(err.message);\n}\n\nconst { mkdir } = require('node:fs/promises');\nconst { join } = require('node:path');\n\nasync function makeDirectory() {\n const projectFolder = join(__dirname, 'test', 'project');\n const dirCreation = await mkdir(projectFolder, { recursive: true });\n\n console.log(dirCreation);\n return dirCreation;\n}\n\nmakeDirectory().catch(console.error);\n"
},
{
"textRaw": "`fsPromises.mkdtemp(prefix[, options])`",
"name": "mkdtemp",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": [
"v20.6.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/48828",
"description": "The `prefix` parameter now accepts buffers and URL."
},
{
"version": [
"v16.5.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/39028",
"description": "The `prefix` parameter now accepts an empty string."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`prefix` {string|Buffer|URL}",
"name": "prefix",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {string|Object}",
"name": "options",
"type": "string|Object",
"options": [
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfills with a string containing the file system path of the newly created temporary directory.",
"name": "return",
"type": "Promise",
"desc": "Fulfills with a string containing the file system path of the newly created temporary directory."
}
}
],
"desc": "Creates a unique temporary directory. A unique directory name is generated by\nappending six random characters to the end of the provided prefix. Due to\nplatform inconsistencies, avoid trailing X characters in prefix. Some\nplatforms, notably the BSDs, can return more than six random characters, and\nreplace trailing X characters in prefix with random characters.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\ntry {\n await mkdtemp(join(tmpdir(), 'foo-'));\n} catch (err) {\n console.error(err);\n}\n\nThe fsPromises.mkdtemp() method will append the six randomly selected\ncharacters directly to the prefix string. For instance, given a directory\n/tmp, if the intention is to create a temporary directory within /tmp, the\nprefix must end with a trailing platform-specific path separator\n(require('node:path').sep).
The resulting Promise holds an async-disposable object whose path property\nholds the created directory path. When the object is disposed, the directory\nand its contents will be removed asynchronously if it still exists. If the\ndirectory cannot be deleted, disposal will throw an error. The object has an\nasync remove() method which will perform the same task.
Both this function and the disposal function on the resulting object are\nasync, so it should be used with await + await using as in\nawait using dir = await fsPromises.mkdtempDisposable('prefix').
For detailed information, see the documentation of fsPromises.mkdtemp().
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
Opens a <FileHandle>.
Refer to the POSIX open(2) documentation for more detail.
Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.
Asynchronously open a directory for iterative scanning. See the POSIX\nopendir(3) documentation for more detail.
Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.
The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.
Example using async iteration:
\nimport { opendir } from 'node:fs/promises';\n\ntry {\n const dir = await opendir('./');\n for await (const dirent of dir)\n console.log(dirent.name);\n} catch (err) {\n console.error(err);\n}\n\nWhen using the async iterator, the <fs.Dir> object will be automatically\nclosed after the iterator exits.
Reads the contents of a directory.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames. If the encoding is set to 'buffer', the filenames returned\nwill be passed as <Buffer> objects.
If options.withFileTypes is set to true, the returned array will contain\n<fs.Dirent> objects.
import { readdir } from 'node:fs/promises';\n\ntry {\n const files = await readdir(path);\n for (const file of files)\n console.log(file);\n} catch (err) {\n console.error(err);\n}\n"
},
{
"textRaw": "`fsPromises.readFile(path[, options])`",
"name": "readFile",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": [
"v15.2.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/35911",
"description": "The options argument may include an AbortSignal to abort an ongoing readFile request."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL|FileHandle} filename or `FileHandle`",
"name": "path",
"type": "string|Buffer|URL|FileHandle",
"desc": "filename or `FileHandle`"
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`encoding` {string|null} **Default:** `null`",
"name": "encoding",
"type": "string|null",
"default": "`null`"
},
{
"textRaw": "`flag` {string} See support of file system `flags`. **Default:** `'r'`.",
"name": "flag",
"type": "string",
"default": "`'r'`",
"desc": "See support of file system `flags`."
},
{
"textRaw": "`signal` {AbortSignal} allows aborting an in-progress readFile",
"name": "signal",
"type": "AbortSignal",
"desc": "allows aborting an in-progress readFile"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} Fulfills with the contents of the file.",
"name": "return",
"type": "Promise",
"desc": "Fulfills with the contents of the file."
}
}
],
"desc": "Asynchronously reads the entire contents of a file.
\nIf no encoding is specified (using options.encoding), the data is returned\nas 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\nplatform-specific. On macOS, Linux, and Windows, the promise will be rejected\nwith an error. On FreeBSD, a representation of the directory's contents will be\nreturned.
An example of reading a package.json file located in the same directory of the\nrunning code:
import { readFile } from 'node:fs/promises';\ntry {\n const filePath = new URL('./package.json', import.meta.url);\n const contents = await readFile(filePath, { encoding: 'utf8' });\n console.log(contents);\n} catch (err) {\n console.error(err.message);\n}\n\nconst { readFile } = require('node:fs/promises');\nconst { resolve } = require('node:path');\nasync function logFile() {\n try {\n const filePath = resolve('./package.json');\n const contents = await readFile(filePath, { encoding: 'utf8' });\n console.log(contents);\n } catch (err) {\n console.error(err.message);\n }\n}\nlogFile();\n\nIt is possible to abort an ongoing readFile using an <AbortSignal>. If a\nrequest is aborted the promise returned is rejected with an AbortError:
import { readFile } from 'node:fs/promises';\n\ntry {\n const controller = new AbortController();\n const { signal } = controller;\n const promise = readFile(fileName, { signal });\n\n // Abort the request before the promise settles.\n controller.abort();\n\n await promise;\n} catch (err) {\n // When a request is aborted - err is an AbortError\n console.error(err);\n}\n\nAborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.readFile performs.
Any specified <FileHandle> has to support reading.
Reads the contents of the symbolic link referred to by path. See the POSIX\nreadlink(2) 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\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer', the link path\nreturned will be passed as a <Buffer> object.
Determines the actual location of path using the same semantics as the\nfs.realpath.native() function.
Only paths that can be converted to UTF8 strings are supported.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path. If the encoding is set to 'buffer', the path returned will be\npassed as a <Buffer> object.
On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.
Renames oldPath to newPath.
Removes the directory identified by path.
Using fsPromises.rmdir() on a file (not a directory) results in the\npromise being rejected with an ENOENT error on Windows and an ENOTDIR\nerror on POSIX.
To get a behavior similar to the rm -rf Unix command, use\nfsPromises.rm() with options { recursive: true, force: true }.
Removes files and directories (modeled on the standard POSIX rm utility).
Creates a symbolic link.
\nThe type argument is only used on Windows platforms and can be one of 'dir',\n'file', or 'junction'. If the type argument is null, Node.js will\nautodetect target type and use 'file' or 'dir'. If the target does not\nexist, 'file' will be used. Windows junction points require the destination\npath to be absolute. When using 'junction', the target argument will\nautomatically be normalized to absolute path. Junction points on NTFS volumes\ncan only point to directories.
Truncates (shortens or extends the length) of the content at path to len\nbytes.
If path refers to a symbolic link, then the link is removed without affecting\nthe file or directory to which that link refers. If the path refers to a file\npath that is not a symbolic link, the file is deleted. See the POSIX unlink(2)\ndocumentation for more detail.
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
Dates, or a\nnumeric string like '123456789.0'.NaN, Infinity, or\n-Infinity, an Error will be thrown.Returns an async iterator that watches for changes on filename, where filename\nis either a file or a directory.
const { watch } = require('node:fs/promises');\n\nconst ac = new AbortController();\nconst { signal } = ac;\nsetTimeout(() => ac.abort(), 10000);\n\n(async () => {\n try {\n const watcher = watch(__filename, { signal });\n for await (const event of watcher)\n console.log(event);\n } catch (err) {\n if (err.name === 'AbortError')\n return;\n throw err;\n }\n})();\n\nOn most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.
All the caveats for fs.watch() also apply to fsPromises.watch().
Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a buffer, an <AsyncIterable>, or an <Iterable> 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()\nfor more details.
Any specified <FileHandle> has to support writing.
It is unsafe to use fsPromises.writeFile() multiple times on the same file\nwithout waiting for the promise to be settled.
Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience\nmethod that performs multiple write calls internally to write the buffer\npassed to it. For performance sensitive code consider using\nfs.createWriteStream() or filehandle.createWriteStream().
It is possible to use an <AbortSignal> to cancel an fsPromises.writeFile().\nCancelation is \"best effort\", and some amount of data is likely still\nto be written.
import { writeFile } from 'node:fs/promises';\nimport { Buffer } from 'node:buffer';\n\ntry {\n const controller = new AbortController();\n const { signal } = controller;\n const data = new Uint8Array(Buffer.from('Hello Node.js'));\n const promise = writeFile('message.txt', data, { signal });\n\n // Abort the request before the promise settles.\n controller.abort();\n\n await promise;\n} catch (err) {\n // When a request is aborted - err is an AbortError\n console.error(err);\n}\n\nAborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.writeFile performs.
Returns an object containing commonly used constants for file system\noperations. The object is the same as fs.constants. See FS constants\nfor more details.
The callback APIs perform all operations asynchronously, without blocking the\nevent loop, then invoke a callback function upon completion or error.
\nThe callback APIs use the underlying Node.js threadpool to perform file\nsystem operations off the event loop thread. These operations are not\nsynchronized or threadsafe. Care must be taken when performing multiple\nconcurrent modifications on the same file or data corruption may occur.
", "methods": [ { "textRaw": "`fs.access(path[, mode], callback)`", "name": "access", "type": "method", "meta": { "added": [ "v0.11.15" ], "changes": [ { "version": "v25.0.0", "pr-url": "https://github.com/nodejs/node/pull/55862", "description": "The constants `fs.F_OK`, `fs.R_OK`, `fs.W_OK` and `fs.X_OK` which were present directly on `fs` are removed." }, { "version": "v20.8.0", "pr-url": "https://github.com/nodejs/node/pull/49683", "description": "The constants `fs.F_OK`, `fs.R_OK`, `fs.W_OK` and `fs.X_OK` which were present directly on `fs` are deprecated." }, { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6534", "description": "The constants like `fs.R_OK`, etc which were present directly on `fs` were moved into `fs.constants` as a soft deprecation. Thus for Node.js `< v6.3.0` use `fs` to access those constants, or do something like `(fs.constants || fs).R_OK` to work with all versions." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", "name": "mode", "type": "integer", "default": "`fs.constants.F_OK`", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. mode should be either the value fs.constants.F_OK\nor a mask consisting of the bitwise OR of any of fs.constants.R_OK,\nfs.constants.W_OK, and fs.constants.X_OK (e.g.\nfs.constants.W_OK | fs.constants.R_OK). Check File access constants for\npossible values of mode.
The final argument, callback, is a callback function that is invoked with\na possible error argument. If any of the accessibility checks fail, the error\nargument will be an Error object. The following examples check if\npackage.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';\n\nconst file = 'package.json';\n\n// Check if the file exists in the current directory.\naccess(file, constants.F_OK, (err) => {\n console.log(`${file} ${err ? 'does not exist' : 'exists'}`);\n});\n\n// Check if the file is readable.\naccess(file, constants.R_OK, (err) => {\n console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);\n});\n\n// Check if the file is writable.\naccess(file, constants.W_OK, (err) => {\n console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);\n});\n\n// Check if the file is readable and writable.\naccess(file, constants.R_OK | constants.W_OK, (err) => {\n console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);\n});\n\nDo not use fs.access() to check for the accessibility of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile(). Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
\nimport { access, open, close } from 'node:fs';\n\naccess('myfile', (err) => {\n if (!err) {\n console.error('myfile already exists');\n return;\n }\n\n open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n});\n\nwrite (RECOMMENDED)
\nimport { open, close } from 'node:fs';\n\nopen('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === 'EEXIST') {\n console.error('myfile already exists');\n return;\n }\n\n throw err;\n }\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n\nread (NOT RECOMMENDED)
\nimport { access, open, close } from 'node:fs';\naccess('myfile', (err) => {\n if (err) {\n if (err.code === 'ENOENT') {\n console.error('myfile does not exist');\n return;\n }\n\n throw err;\n }\n\n open('myfile', 'r', (err, fd) => {\n if (err) throw err;\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n});\n\nread (RECOMMENDED)
\nimport { open, close } from 'node:fs';\n\nopen('myfile', 'r', (err, fd) => {\n if (err) {\n if (err.code === 'ENOENT') {\n console.error('myfile does not exist');\n return;\n }\n\n throw err;\n }\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n\nThe \"not recommended\" examples above check for accessibility and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.
\nIn general, check for the accessibility of a file only if the file will not be\nused directly, for example when its accessibility is a signal from another\nprocess.
\nOn Windows, access-control policies (ACLs) on a directory may limit access to\na file or directory. The fs.access() function, however, does not check the\nACL and therefore may report that a path is accessible even if the ACL restricts\nthe user from reading or writing to it.
Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.
The mode option only affects the newly created file. See fs.open()\nfor more details.
import { appendFile } from 'node:fs';\n\nappendFile('message.txt', 'data to append', (err) => {\n if (err) throw err;\n console.log('The \"data to append\" was appended to file!');\n});\n\nIf options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';\n\nappendFile('message.txt', 'data to append', 'utf8', callback);\n\nThe path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.
import { open, close, appendFile } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('message.txt', 'a', (err, fd) => {\n if (err) throw err;\n\n try {\n appendFile(fd, 'data to append', 'utf8', (err) => {\n closeFd(fd);\n if (err) throw err;\n });\n } catch (err) {\n closeFd(fd);\n throw err;\n }\n});\n"
},
{
"textRaw": "`fs.chmod(path, mode, callback)`",
"name": "chmod",
"type": "method",
"meta": {
"added": [
"v0.1.30"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12562",
"description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime."
},
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/7897",
"description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`mode` {string|integer}",
"name": "mode",
"type": "string|integer"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
}
]
}
]
}
],
"desc": "Asynchronously changes the permissions of a file. No arguments other than a\npossible exception are given to the completion callback.
\nSee the POSIX chmod(2) documentation for more detail.
import { chmod } from 'node:fs';\n\nchmod('my_file.txt', 0o775, (err) => {\n if (err) throw err;\n console.log('The permissions for file \"my_file.txt\" have been changed!');\n});\n",
"modules": [
{
"textRaw": "File modes",
"name": "file_modes",
"type": "module",
"desc": "The mode argument used in both the fs.chmod() and fs.chmodSync()\nmethods is a numeric bitmask created using a logical OR of the following\nconstants:
| Constant | Octal | Description |
|---|---|---|
fs.constants.S_IRUSR | 0o400 | read by owner |
fs.constants.S_IWUSR | 0o200 | write by owner |
fs.constants.S_IXUSR | 0o100 | execute/search by owner |
fs.constants.S_IRGRP | 0o40 | read by group |
fs.constants.S_IWGRP | 0o20 | write by group |
fs.constants.S_IXGRP | 0o10 | execute/search by group |
fs.constants.S_IROTH | 0o4 | read by others |
fs.constants.S_IWOTH | 0o2 | write by others |
fs.constants.S_IXOTH | 0o1 | execute/search by others |
An easier method of constructing the mode is to use a sequence of three\noctal digits (e.g. 765). The left-most digit (7 in the example), specifies\nthe permissions for the file owner. The middle digit (6 in the example),\nspecifies permissions for the group. The right-most digit (5 in the example),\nspecifies the permissions for others.
| Number | Description |
|---|---|
7 | read, write, and execute |
6 | read and write |
5 | read and execute |
4 | read only |
3 | write and execute |
2 | write only |
1 | execute only |
0 | no permission |
For example, the octal value 0o765 means:
When using raw numbers where file modes are expected, any value larger than\n0o777 may result in platform-specific behaviors that are not supported to work\nconsistently. Therefore constants like S_ISVTX, S_ISGID, or S_ISUID are\nnot exposed in fs.constants.
Caveats: on Windows only the write permission can be changed, and the\ndistinction among the permissions of group, owner, or others is not\nimplemented.
", "displayName": "File modes" } ] }, { "textRaw": "`fs.chown(path, uid, gid, callback)`", "name": "chown", "type": "method", "meta": { "added": [ "v0.1.97" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/12562", "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." }, { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7897", "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`uid` {integer}", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer}", "name": "gid", "type": "integer" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "Asynchronously changes owner and group of a file. No arguments other than a\npossible exception are given to the completion callback.
\nSee the POSIX chown(2) documentation for more detail.
Closes the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.
\nCalling fs.close() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. No arguments other than a possible exception are given to the\ncallback function. Node.js makes no guarantees about the atomicity of the copy\noperation. If an error occurs after the destination file has been opened for\nwriting, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support\ncopy-on-write, then the operation will fail.import { copyFile, constants } from 'node:fs';\n\nfunction callback(err) {\n if (err) throw err;\n console.log('source.txt was copied to destination.txt');\n}\n\n// destination.txt will be created or overwritten by default.\ncopyFile('source.txt', 'destination.txt', callback);\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ncopyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);\n"
},
{
"textRaw": "`fs.cp(src, dest[, options], callback)`",
"name": "cp",
"type": "method",
"meta": {
"added": [
"v16.7.0"
],
"changes": [
{
"version": "v22.3.0",
"pr-url": "https://github.com/nodejs/node/pull/53127",
"description": "This API is no longer experimental."
},
{
"version": [
"v20.1.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47084",
"description": "Accept an additional `mode` option to specify the copy behavior as the `mode` argument of `fs.copyFile()`."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": [
"v17.6.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41819",
"description": "Accepts an additional `verbatimSymlinks` option to specify whether to perform path resolution for symlinks."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`src` {string|URL} source path to copy.",
"name": "src",
"type": "string|URL",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string|URL} destination path to copy to.",
"name": "dest",
"type": "string|URL",
"desc": "destination path to copy to."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`dereference` {boolean} dereference symlinks. **Default:** `false`.",
"name": "dereference",
"type": "boolean",
"default": "`false`",
"desc": "dereference symlinks."
},
{
"textRaw": "`errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. **Default:** `false`.",
"name": "errorOnExist",
"type": "boolean",
"default": "`false`",
"desc": "when `force` is `false`, and the destination exists, throw an error."
},
{
"textRaw": "`filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false` **Default:** `undefined`.",
"name": "filter",
"type": "Function",
"default": "`undefined`",
"desc": "Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. Can also return a `Promise` that resolves to `true` or `false`",
"options": [
{
"textRaw": "`src` {string} source path to copy.",
"name": "src",
"type": "string",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string} destination path to copy to.",
"name": "dest",
"type": "string",
"desc": "destination path to copy to."
},
{
"textRaw": "Returns: {boolean|Promise} A value that is coercible to `boolean` or a `Promise` that fulfils with such value.",
"name": "return",
"type": "boolean|Promise",
"desc": "A value that is coercible to `boolean` or a `Promise` that fulfils with such value."
}
]
},
{
"textRaw": "`force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`.",
"name": "force",
"type": "boolean",
"default": "`true`",
"desc": "overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior."
},
{
"textRaw": "`mode` {integer} modifiers for copy operation. **Default:** `0`. See `mode` flag of `fs.copyFile()`.",
"name": "mode",
"type": "integer",
"default": "`0`. See `mode` flag of `fs.copyFile()`",
"desc": "modifiers for copy operation."
},
{
"textRaw": "`preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. **Default:** `false`.",
"name": "preserveTimestamps",
"type": "boolean",
"default": "`false`",
"desc": "When `true` timestamps from `src` will be preserved."
},
{
"textRaw": "`recursive` {boolean} copy directories recursively **Default:** `false`",
"name": "recursive",
"type": "boolean",
"default": "`false`",
"desc": "copy directories recursively"
},
{
"textRaw": "`verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. **Default:** `false`",
"name": "verbatimSymlinks",
"type": "boolean",
"default": "`false`",
"desc": "When `true`, path resolution for symlinks will be skipped."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
}
]
}
]
}
],
"desc": "Asynchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.
When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.
options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is\nomitted or undefined, fs.createReadStream() reads sequentially from the\ncurrent file position. The encoding can be any one of those accepted by\n<Buffer>.
If fd is specified, ReadStream will ignore the path argument and will use\nthe specified file descriptor. This means that no 'open' event will be\nemitted. fd should be blocking; non-blocking fds should be passed to\n<net.Socket>.
If fd points to a character device that only supports blocking reads\n(such as keyboard or sound card), read operations do not finish until data is\navailable. This can prevent the process from exiting and the stream from\nclosing naturally.
By default, the stream will emit a 'close' event after it has been\ndestroyed. Set the emitClose option to false to change this behavior.
By providing the fs option, it is possible to override the corresponding fs\nimplementations for open, read, and close. When providing the fs option,\nan override for read is required. If no fd is provided, an override for\nopen is also required. If autoClose is true, an override for close is\nalso required.
import { createReadStream } from 'node:fs';\n\n// Create a stream from some character device.\nconst stream = createReadStream('/dev/input/event0');\nsetTimeout(() => {\n stream.close(); // This may not close the stream.\n // Artificially marking end-of-stream, as if the underlying resource had\n // indicated end-of-file by itself, allows the stream to close.\n // This does not cancel pending read operations, and if there is such an\n // operation, the process may still not be able to exit successfully\n // until it finishes.\n stream.push(null);\n stream.read(0);\n}, 100);\n\nIf autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is the application's responsibility to close it and make\nsure there's no file descriptor leak. If autoClose is set to true (default\nbehavior), on 'error' or 'end' the file descriptor will be closed\nautomatically.
mode sets the file mode (permission and sticky bits), but only if the\nfile was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
\nimport { createReadStream } from 'node:fs';\n\ncreateReadStream('sample.txt', { start: 90, end: 99 });\n\nIf options is a string, then it specifies the encoding.
options may also include a start option to allow writing data at some\nposition past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than\nreplacing it may require the flags option to be set to r+ rather than the\ndefault w. The encoding can be any one of those accepted by <Buffer>.
If autoClose is set to true (default behavior) on 'error' or 'finish'\nthe file descriptor will be closed automatically. If autoClose is false,\nthen the file descriptor won't be closed, even if there's an error.\nIt is the application's responsibility to close it and make sure there's no\nfile descriptor leak.
By default, the stream will emit a 'close' event after it has been\ndestroyed. Set the emitClose option to false to change this behavior.
By providing the fs option it is possible to override the corresponding fs\nimplementations for open, write, writev, and close. Overriding write()\nwithout writev() can reduce performance as some optimizations (_writev())\nwill be disabled. When providing the fs option, overrides for at least one of\nwrite and writev are required. If no fd option is supplied, an override\nfor open is also required. If autoClose is true, an override for close\nis 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\n'open' event will be emitted. fd should be blocking; non-blocking fds\nshould be passed to <net.Socket>.
If options is a string, then it specifies the encoding.
Test whether or not the element at the given path exists by checking with the file system.\nThen call the callback argument with either true or false:
import { exists } from 'node:fs';\n\nexists('/etc/passwd', (e) => {\n console.log(e ? 'it exists' : 'no passwd!');\n});\n\nThe parameters for this callback are not consistent with other Node.js\ncallbacks. Normally, the first parameter to a Node.js callback is an err\nparameter, optionally followed by other parameters. The fs.exists() callback\nhas only one boolean parameter. This is one reason fs.access() is recommended\ninstead of fs.exists().
If path is a symbolic link, it is followed. Thus, if path exists but points\nto a non-existent element, the callback will receive the value false.
Using fs.exists() to check for the existence of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file does not exist.
write (NOT RECOMMENDED)
\nimport { exists, open, close } from 'node:fs';\n\nexists('myfile', (e) => {\n if (e) {\n console.error('myfile already exists');\n } else {\n open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n }\n});\n\nwrite (RECOMMENDED)
\nimport { open, close } from 'node:fs';\nopen('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === 'EEXIST') {\n console.error('myfile already exists');\n return;\n }\n\n throw err;\n }\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n\nread (NOT RECOMMENDED)
\nimport { open, close, exists } from 'node:fs';\n\nexists('myfile', (e) => {\n if (e) {\n open('myfile', 'r', (err, fd) => {\n if (err) throw err;\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n } else {\n console.error('myfile does not exist');\n }\n});\n\nread (RECOMMENDED)
\nimport { open, close } from 'node:fs';\n\nopen('myfile', 'r', (err, fd) => {\n if (err) {\n if (err.code === 'ENOENT') {\n console.error('myfile does not exist');\n return;\n }\n\n throw err;\n }\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n\nThe \"not recommended\" examples above check for existence and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.
\nIn general, check for the existence of a file only if the file won't be\nused directly, for example when its existence is a signal from another\nprocess.
" }, { "textRaw": "`fs.fchmod(fd, mode, callback)`", "name": "fchmod", "type": "method", "meta": { "added": [ "v0.4.7" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/12562", "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7897", "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`mode` {string|integer}", "name": "mode", "type": "string|integer" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "Sets the permissions on the file. No arguments other than a possible exception\nare given to the completion callback.
\nSee the POSIX fchmod(2) documentation for more detail.
Sets the owner of the file. No arguments other than a possible exception are\ngiven to the completion callback.
\nSee the POSIX fchown(2) documentation for more detail.
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details. No arguments other than a possible\nexception are given to the completion callback.
Invokes the callback with the <fs.Stats> for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail. No arguments other\nthan a possible exception are given to the completion callback.
Truncates the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.
\nSee the POSIX ftruncate(2) documentation for more detail.
If the file referred to by the file descriptor was larger than len bytes, only\nthe first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the\nfile:
\nimport { open, close, ftruncate } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('temp.txt', 'r+', (err, fd) => {\n if (err) throw err;\n\n try {\n ftruncate(fd, 4, (err) => {\n closeFd(fd);\n if (err) throw err;\n });\n } catch (err) {\n closeFd(fd);\n if (err) throw err;\n }\n});\n\nIf the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):
If len is negative then 0 will be used.
Change the file system timestamps of the object referenced by the supplied file\ndescriptor. See fs.utimes().
import { glob } from 'node:fs';\n\nglob('**/*.js', (err, matches) => {\n if (err) throw err;\n console.log(matches);\n});\n\nconst { glob } = require('node:fs');\n\nglob('**/*.js', (err, matches) => {\n if (err) throw err;\n console.log(matches);\n});\n"
},
{
"textRaw": "`fs.lchmod(path, mode, callback)`",
"name": "lchmod",
"type": "method",
"meta": {
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37460",
"description": "The error returned may be an `AggregateError` if more than one error is returned."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12562",
"description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/7897",
"description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013."
}
],
"deprecated": [
"v0.4.7"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`mode` {integer}",
"name": "mode",
"type": "integer"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error|AggregateError}",
"name": "err",
"type": "Error|AggregateError"
}
]
}
]
}
],
"desc": "Changes the permissions on a symbolic link. No arguments other than a possible\nexception are given to the completion callback.
\nThis method is only implemented on macOS.
\nSee the POSIX lchmod(2) documentation for more detail.
Set the owner of the symbolic link. No arguments other than a possible\nexception are given to the completion callback.
\nSee the POSIX lchown(2) documentation for more detail.
Changes the access and modification times of a file in the same way as\nfs.utimes(), with the difference that if the path refers to a symbolic\nlink, then the link is not dereferenced: instead, the timestamps of the\nsymbolic link itself are changed.
No arguments other than a possible exception are given to the completion\ncallback.
" }, { "textRaw": "`fs.link(existingPath, newPath, callback)`", "name": "link", "type": "method", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/12562", "description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime." }, { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `existingPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7897", "description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013." } ] }, "signatures": [ { "params": [ { "textRaw": "`existingPath` {string|Buffer|URL}", "name": "existingPath", "type": "string|Buffer|URL" }, { "textRaw": "`newPath` {string|Buffer|URL}", "name": "newPath", "type": "string|Buffer|URL" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail. No arguments other than a possible\nexception are given to the completion callback.
Retrieves the <fs.Stats> for the symbolic link referred to by the path.\nThe callback gets two arguments (err, stats) where stats is a <fs.Stats>\nobject. lstat() is identical to stat(), except that if path is a symbolic\nlink, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
Asynchronously creates a directory.
\nThe callback is given a possible exception and, if recursive is true, the\nfirst directory path created, (err[, path]).\npath can still be undefined when recursive is true, if no directory was\ncreated (for instance, if it was previously created).
The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfs.mkdir() when path is a directory that exists results in an error only\nwhen recursive is false. If recursive is false and the directory exists,\nan EEXIST error occurs.
import { mkdir } from 'node:fs';\n\n// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.\nmkdir('./tmp/a/apple', { recursive: true }, (err) => {\n if (err) throw err;\n});\n\nOn Windows, using fs.mkdir() on the root directory even with recursion will\nresult in an error:
import { mkdir } from 'node:fs';\n\nmkdir('/', { recursive: true }, (err) => {\n // => [Error: EPERM: operation not permitted, mkdir 'C:\\']\n});\n\nSee the POSIX mkdir(2) documentation for more details.
Creates a unique temporary directory.
\nGenerates six random characters to be appended behind a required\nprefix to create a unique temporary directory. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second\nparameter.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs';\nimport { join } from 'node:path';\nimport { tmpdir } from 'node:os';\n\nmkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n\nThe fs.mkdtemp() method will append the six randomly selected characters\ndirectly to the prefix string. For instance, given a directory /tmp, if the\nintention is to create a temporary directory within /tmp, the prefix\nmust end with a trailing platform-specific path separator\n(require('node:path').sep).
import { tmpdir } from 'node:os';\nimport { mkdtemp } from 'node:fs';\n\n// The parent directory for the new temporary directory\nconst tmpDir = tmpdir();\n\n// This method is *INCORRECT*:\nmkdtemp(tmpDir, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmpabc123`.\n // A new temporary directory is created at the file system root\n // rather than *within* the /tmp directory.\n});\n\n// This method is *CORRECT*:\nimport { sep } from 'node:path';\nmkdtemp(`${tmpDir}${sep}`, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmp/abc123`.\n // A new temporary directory is created within\n // the /tmp directory.\n});\n"
},
{
"textRaw": "`fs.open(path[, flags[, mode]], callback)`",
"name": "open",
"type": "method",
"meta": {
"added": [
"v0.0.2"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v11.1.0",
"pr-url": "https://github.com/nodejs/node/pull/23767",
"description": "The `flags` argument is now optional and defaults to `'r'`."
},
{
"version": "v9.9.0",
"pr-url": "https://github.com/nodejs/node/pull/18801",
"description": "The `as` and `as+` flags are supported now."
},
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`flags` {string|number} See support of file system `flags`. **Default:** `'r'`.",
"name": "flags",
"type": "string|number",
"default": "`'r'`",
"desc": "See support of file system `flags`.",
"optional": true
},
{
"textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)",
"name": "mode",
"type": "string|integer",
"default": "`0o666` (readable and writable)",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`fd` {integer}",
"name": "fd",
"type": "integer"
}
]
}
]
}
],
"desc": "Asynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. On Windows, only the write permission can be manipulated; see\nfs.chmod().
The callback gets two arguments (err, fd).
Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.
Functions based on fs.open() exhibit this behavior as well:\nfs.writeFile(), fs.readFile(), etc.
Returns a <Blob> whose data is backed by the given file.
The file must not be modified after the <Blob> is created. Any modifications\nwill cause reading the <Blob> data to fail with a DOMException error.\nSynchronous stat operations on the file when the Blob is created, and before\neach read in order to detect whether the file data has been modified on disk.
import { openAsBlob } from 'node:fs';\n\nconst blob = await openAsBlob('the.file.txt');\nconst ab = await blob.arrayBuffer();\nblob.stream();\n\nconst { openAsBlob } = require('node:fs');\n\n(async () => {\n const blob = await openAsBlob('the.file.txt');\n const ab = await blob.arrayBuffer();\n blob.stream();\n})();\n"
},
{
"textRaw": "`fs.opendir(path[, options], callback)`",
"name": "opendir",
"type": "method",
"meta": {
"added": [
"v12.12.0"
],
"changes": [
{
"version": [
"v20.1.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41439",
"description": "Added `recursive` option."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": [
"v13.1.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30114",
"description": "The `bufferSize` option was introduced."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`encoding` {string|null} **Default:** `'utf8'`",
"name": "encoding",
"type": "string|null",
"default": "`'utf8'`"
},
{
"textRaw": "`bufferSize` {number} Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage. **Default:** `32`",
"name": "bufferSize",
"type": "number",
"default": "`32`",
"desc": "Number of directory entries that are buffered internally when reading from the directory. Higher values lead to better performance but higher memory usage."
},
{
"textRaw": "`recursive` {boolean} **Default:** `false`",
"name": "recursive",
"type": "boolean",
"default": "`false`"
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`dir` {fs.Dir}",
"name": "dir",
"type": "fs.Dir"
}
]
}
]
}
],
"desc": "Asynchronously open a directory. See the POSIX opendir(3) documentation for\nmore details.
Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.
The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.
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\nnumber of bytes read is zero.
\nIf this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffer properties.
The fs.read() method reads data from the file specified\nby the file descriptor (fd).\nThe length argument indicates the maximum number\nof bytes that Node.js\nwill attempt to read from the kernel.\nHowever, the actual number of bytes read (bytesRead) can be lower\nthan the specified length for various reasons.
For example:
\nlength, bytesRead\nwill be set to the actual number of bytes read.bytesRead parameter in the callback will indicate\nthe actual number of bytes read, which may be less than the specified length.filesystem\nor encounters any other issue during reading,\nbytesRead can be lower than the specified length.Therefore, when using fs.read(), it's important to\ncheck the bytesRead value to\ndetermine how many bytes were actually read from the file.\nDepending on your application\nlogic, you may need to handle cases where bytesRead\nis lower than the specified length,\nsuch as by wrapping the read call in a loop if you require\na minimum amount of bytes.
This behavior is similar to the POSIX preadv2 function.
Similar to the fs.read() function, this version takes an optional\noptions object. If no options object is specified, it will default with the\nabove values.
Similar to the fs.read() function, this version takes an optional\noptions object. If no options object is specified, it will default with the\nabove values.
Reads the contents of a directory. The callback gets two arguments (err, files)\nwhere files is an array of the names of the files in the directory excluding\n'.' and '..'.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding is set to 'buffer',\nthe filenames returned will be passed as <Buffer> objects.
If options.withFileTypes is set to true, the files array will contain\n<fs.Dirent> objects.
Asynchronously reads the entire contents of a file.
\nimport { readFile } from 'node:fs';\n\nreadFile('/etc/passwd', (err, data) => {\n if (err) throw err;\n console.log(data);\n});\n\nThe callback is passed two arguments (err, data), where data is the\ncontents of the file.
If no encoding is specified, then the raw buffer is returned.
\nIf options is a string, then it specifies the encoding:
import { readFile } from 'node:fs';\n\nreadFile('/etc/passwd', 'utf8', callback);\n\nWhen the path is a directory, the behavior of fs.readFile() and\nfs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an\nerror will be returned. On FreeBSD, a representation of the directory's contents\nwill be returned.
import { readFile } from 'node:fs';\n\n// macOS, Linux, and Windows\nreadFile('<directory>', (err, data) => {\n // => [Error: EISDIR: illegal operation on a directory, read <directory>]\n});\n\n// FreeBSD\nreadFile('<directory>', (err, data) => {\n // => null, <data>\n});\n\nIt is possible to abort an ongoing request using an AbortSignal. If a\nrequest is aborted the callback is called with an AbortError:
import { readFile } from 'node:fs';\n\nconst controller = new AbortController();\nconst signal = controller.signal;\nreadFile(fileInfo[0].name, { signal }, (err, buf) => {\n // ...\n});\n// When you want to abort the request\ncontroller.abort();\n\nThe fs.readFile() function buffers the entire file. To minimize memory costs,\nwhen possible prefer streaming via fs.createReadStream().
Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.readFile performs.
path, it will not be closed\nautomatically.'Hello World' and six bytes are read with the file descriptor,\nthe call to fs.readFile() with the same file descriptor, would give\n'World', rather than 'Hello World'.The fs.readFile() method asynchronously reads the contents of a file into\nmemory one chunk at a time, allowing the event loop to turn between each chunk.\nThis allows the read operation to have less impact on other activity that may\nbe using the underlying libuv thread pool but means that it will take longer\nto read a complete file into memory.
The additional read overhead can vary broadly on different systems and depends\non the type of file being read. If the file type is not a regular file (a pipe\nfor instance) and Node.js is unable to determine an actual file size, each read\noperation will load on 64 KiB of data. For regular files, each read will process\n512 KiB of data.
\nFor applications that require as-fast-as-possible reading of file contents, it\nis better to use fs.read() directly and for application code to manage\nreading the full contents of the file itself.
The Node.js GitHub issue #25741 provides more information and a detailed\nanalysis on the performance of fs.readFile() for multiple file sizes in\ndifferent Node.js versions.
Reads the contents of the symbolic link referred to by path. The callback gets\ntwo arguments (err, linkString).
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding is set to 'buffer',\nthe link path returned will be passed as a <Buffer> object.
Read from a file specified by fd and write to an array of ArrayBufferViews\nusing readv().
position is the offset from the beginning of the file from where data\nshould be read. If typeof position !== 'number', the data will be read\nfrom the current position.
The callback will be given three arguments: err, bytesRead, and\nbuffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffers properties.
Asynchronously computes the canonical pathname by resolving ., .., and\nsymbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can\nexpose a file system entity through many pathnames.
\nThis function behaves like realpath(3), with some exceptions:
No case conversion is performed on case-insensitive file systems.
\nThe maximum number of symbolic links is platform-independent and generally\n(much) higher than what the native realpath(3) implementation supports.
The callback gets two arguments (err, resolvedPath). May use process.cwd\nto resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.
If path resolves to a socket or a pipe, the function will return a system\ndependent name for that object.
A path that does not exist results in an ENOENT error.\nerror.path is the absolute file path.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Only paths that can be converted to UTF8 strings are supported.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.
On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.
Asynchronously rename file at oldPath to the pathname provided\nas newPath. In the case that newPath already exists, it will\nbe overwritten. If there is a directory at newPath, an error will\nbe raised instead. No arguments other than a possible exception are\ngiven to the completion callback.
See also: rename(2).
import { rename } from 'node:fs';\n\nrename('oldFile.txt', 'newFile.txt', (err) => {\n if (err) throw err;\n console.log('Rename complete!');\n});\n"
},
{
"textRaw": "`fs.rmdir(path[, options], callback)`",
"name": "rmdir",
"type": "method",
"meta": {
"added": [
"v0.0.2"
],
"changes": [
{
"version": "v25.0.0",
"pr-url": "https://github.com/nodejs/node/pull/58616",
"description": "Remove `recursive` option."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37216",
"description": "Using `fs.rmdir(path, { recursive: true })` on a `path` that is a file is no longer permitted and results in an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37216",
"description": "Using `fs.rmdir(path, { recursive: true })` on a `path` that does not exist is no longer permitted and results in a `ENOENT` error."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37302",
"description": "The `recursive` option is deprecated, using it triggers a deprecation warning."
},
{
"version": "v14.14.0",
"pr-url": "https://github.com/nodejs/node/pull/35579",
"description": "The `recursive` option is deprecated, use `fs.rm` instead."
},
{
"version": [
"v13.3.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30644",
"description": "The `maxBusyTries` option is renamed to `maxRetries`, and its default is 0. The `emfileWait` option has been removed, and `EMFILE` errors use the same retry logic as other errors. The `retryDelay` option is now supported. `ENFILE` errors are now retried."
},
{
"version": "v12.10.0",
"pr-url": "https://github.com/nodejs/node/pull/29168",
"description": "The `recursive`, `maxBusyTries`, and `emfileWait` options are now supported."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12562",
"description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime."
},
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `path` parameters can be a WHATWG `URL` object using `file:` protocol."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/7897",
"description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {Object} There are currently no options exposed. There used to be options for `recursive`, `maxBusyTries`, and `emfileWait` but they were deprecated and removed. The `options` argument is still accepted for backwards compatibility but it is not used.",
"name": "options",
"type": "Object",
"desc": "There are currently no options exposed. There used to be options for `recursive`, `maxBusyTries`, and `emfileWait` but they were deprecated and removed. The `options` argument is still accepted for backwards compatibility but it is not used.",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
}
]
}
]
}
],
"desc": "Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.
Using fs.rmdir() on a file (not a directory) results in an ENOENT error on\nWindows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use fs.rm()\nwith options { recursive: true, force: true }.
Asynchronously removes files and directories (modeled on the standard POSIX rm\nutility). No arguments other than a possible exception are given to the\ncompletion callback.
Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is an <fs.Stats> object.
In case of an error, the err.code will be one of Common System Errors.
fs.stat() follows symbolic links. Use fs.lstat() to look at the\nlinks themselves.
Using fs.stat() to check for the existence of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile() is not recommended.\nInstead, user code should open/read/write the file directly and handle the\nerror raised if the file is not available.
To check if a file exists without manipulating it afterwards, fs.access()\nis recommended.
For example, given the following directory structure:
\n- txtDir\n-- file.txt\n- app.js\n\nThe next program will check for the stats of the given paths:
\nimport { stat } from 'node:fs';\n\nconst pathsToCheck = ['./txtDir', './txtDir/file.txt'];\n\nfor (let i = 0; i < pathsToCheck.length; i++) {\n stat(pathsToCheck[i], (err, stats) => {\n console.log(stats.isDirectory());\n console.log(stats);\n });\n}\n\nThe resulting output will resemble:
\ntrue\nStats {\n dev: 16777220,\n mode: 16877,\n nlink: 3,\n uid: 501,\n gid: 20,\n rdev: 0,\n blksize: 4096,\n ino: 14214262,\n size: 96,\n blocks: 0,\n atimeMs: 1561174653071.963,\n mtimeMs: 1561174614583.3518,\n ctimeMs: 1561174626623.5366,\n birthtimeMs: 1561174126937.2893,\n atime: 2019-06-22T03:37:33.072Z,\n mtime: 2019-06-22T03:36:54.583Z,\n ctime: 2019-06-22T03:37:06.624Z,\n birthtime: 2019-06-22T03:28:46.937Z\n}\nfalse\nStats {\n dev: 16777220,\n mode: 33188,\n nlink: 1,\n uid: 501,\n gid: 20,\n rdev: 0,\n blksize: 4096,\n ino: 14214074,\n size: 8,\n blocks: 8,\n atimeMs: 1561174616618.8555,\n mtimeMs: 1561174614584,\n ctimeMs: 1561174614583.8145,\n birthtimeMs: 1561174007710.7478,\n atime: 2019-06-22T03:36:56.619Z,\n mtime: 2019-06-22T03:36:54.584Z,\n ctime: 2019-06-22T03:36:54.584Z,\n birthtime: 2019-06-22T03:26:47.711Z\n}\n"
},
{
"textRaw": "`fs.statfs(path[, options], callback)`",
"name": "statfs",
"type": "method",
"meta": {
"added": [
"v19.6.0",
"v18.15.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.StatFs} object should be `bigint`. **Default:** `false`.",
"name": "bigint",
"type": "boolean",
"default": "`false`",
"desc": "Whether the numeric values in the returned {fs.StatFs} object should be `bigint`."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`stats` {fs.StatFs}",
"name": "stats",
"type": "fs.StatFs"
}
]
}
]
}
],
"desc": "Asynchronous statfs(2). Returns information about the mounted file system which\ncontains 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.
Creates the link called path pointing to target. No arguments other than a\npossible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
The type argument is only available on Windows and ignored on other platforms.\nIt can be set to 'dir', 'file', or 'junction'. If the type argument is\nnull, Node.js will autodetect target type and use 'file' or 'dir'.\nIf the target does not exist, 'file' will be used. Windows junction points\nrequire the destination path to be absolute. When using 'junction', the\ntarget argument will automatically be normalized to absolute path. Junction\npoints on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
\nimport { symlink } from 'node:fs';\n\nsymlink('./mew', './mewtwo', callback);\n\nThe above example creates a symbolic link mewtwo which points to mew in the\nsame directory:
$ tree .\n.\n├── mew\n└── mewtwo -> ./mew\n"
},
{
"textRaw": "`fs.truncate(path[, len], callback)`",
"name": "truncate",
"type": "method",
"meta": {
"added": [
"v0.8.6"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v16.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37460",
"description": "The error returned may be an `AggregateError` if more than one error is returned."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12562",
"description": "The `callback` parameter is no longer optional. Not passing it will throw a `TypeError` at runtime."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/7897",
"description": "The `callback` parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`len` {integer} **Default:** `0`",
"name": "len",
"type": "integer",
"default": "`0`",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"options": [
{
"textRaw": "`err` {Error|AggregateError}",
"name": "err",
"type": "Error|AggregateError"
}
]
}
]
}
],
"desc": "Truncates the file. No arguments other than a possible exception are\ngiven to the completion callback. A file descriptor can also be passed as the\nfirst argument. In this case, fs.ftruncate() is called.
import { truncate } from 'node:fs';\n// Assuming that 'path/file.txt' is a regular file.\ntruncate('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was truncated');\n});\n\nconst { truncate } = require('node:fs');\n// Assuming that 'path/file.txt' is a regular file.\ntruncate('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was truncated');\n});\n\nPassing a file descriptor is deprecated and may result in an error being thrown\nin the future.
\nSee the POSIX truncate(2) documentation for more details.
Asynchronously removes a file or symbolic link. No arguments other than a\npossible exception are given to the completion callback.
\nimport { unlink } from 'node:fs';\n// Assuming that 'path/file.txt' is a regular file.\nunlink('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was deleted');\n});\n\nfs.unlink() will not work on a directory, empty or otherwise. To remove a\ndirectory, use fs.rmdir().
See the POSIX unlink(2) documentation for more details.
Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed,\neffectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.
Using fs.watch() is more efficient than fs.watchFile() and\nfs.unwatchFile(). fs.watch() should be used instead of fs.watchFile()\nand fs.unwatchFile() when possible.
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
Dates, or a numeric string like '123456789.0'.NaN, Infinity, or\n-Infinity, an Error will be thrown.Watch for changes on filename, where filename is either a file or a\ndirectory.
The second argument is optional. If options is provided as a string, it\nspecifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventType\nis either 'rename' or 'change', and filename is the name of the file\nwhich triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.
The listener callback is attached to the 'change' event fired by\n<fs.FSWatcher>, but it is not the same thing as the 'change' value of\neventType.
If a signal is passed, aborting the corresponding AbortController will close\nthe returned <fs.FSWatcher>.
The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.
On Windows, no events will be emitted if the watched directory is moved or\nrenamed. An EPERM error is reported when the watched directory is deleted.
The fs.watch API does not provide any protection with respect\nto malicious actions on the file system. For example, on Windows it is\nimplemented by monitoring changes in a directory versus specific files. This\nallows substitution of a file and fs reporting changes on the new file\nwith the same filename.
This feature depends on the underlying operating system providing a way\nto be notified of file system changes.
\ninotify(7).kqueue(2).kqueue(2) for files and FSEvents for\ndirectories.event ports.ReadDirectoryChangesW.AHAFS, which must be enabled.If the underlying functionality is not available for some reason, then\nfs.watch() will not be able to function and may throw an exception.\nFor example, watching files or directories can be unreliable, and in some\ncases impossible, on network file systems (NFS, SMB, etc) or host file systems\nwhen using virtualization software such as Vagrant or Docker.
It is still possible to use fs.watchFile(), which uses stat polling, but\nthis method is slower and less reliable.
On Linux and macOS systems, fs.watch() resolves the path to an inode and\nwatches the inode. If the watched path is deleted and recreated, it is assigned\na new inode. The watch will emit an event for the delete but will continue\nwatching the original inode. Events for the new inode will not be emitted.\nThis is expected behavior.
AIX files retain the same inode for the lifetime of a file. Saving and closing a\nwatched file on AIX will result in two notifications (one for adding new\ncontent, and one for truncation).
" }, { "textRaw": "Filename argument", "name": "Filename argument", "type": "misc", "desc": "Providing filename argument in the callback is only supported on Linux,\nmacOS, Windows, and AIX. Even on supported platforms, filename is not always\nguaranteed to be provided. Therefore, don't assume that filename argument is\nalways provided in the callback, and have some fallback logic if it is null.
import { watch } from 'node:fs';\nwatch('somedir', (eventType, filename) => {\n console.log(`event type is: ${eventType}`);\n if (filename) {\n console.log(`filename provided: ${filename}`);\n } else {\n console.log('filename not provided');\n }\n});\n"
}
]
}
]
},
{
"textRaw": "`fs.watchFile(filename[, options], listener)`",
"name": "watchFile",
"type": "method",
"meta": {
"added": [
"v0.1.31"
],
"changes": [
{
"version": "v10.5.0",
"pr-url": "https://github.com/nodejs/node/pull/20220",
"description": "The `bigint` option is now supported."
},
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `filename` parameter can be a WHATWG `URL` object using `file:` protocol."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`filename` {string|Buffer|URL}",
"name": "filename",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`bigint` {boolean} **Default:** `false`",
"name": "bigint",
"type": "boolean",
"default": "`false`"
},
{
"textRaw": "`persistent` {boolean} **Default:** `true`",
"name": "persistent",
"type": "boolean",
"default": "`true`"
},
{
"textRaw": "`interval` {integer} **Default:** `5007`",
"name": "interval",
"type": "integer",
"default": "`5007`"
}
],
"optional": true
},
{
"textRaw": "`listener` {Function}",
"name": "listener",
"type": "Function",
"options": [
{
"textRaw": "`current` {fs.Stats}",
"name": "current",
"type": "fs.Stats"
},
{
"textRaw": "`previous` {fs.Stats}",
"name": "previous",
"type": "fs.Stats"
}
]
}
],
"return": {
"textRaw": "Returns: {fs.StatWatcher}",
"name": "return",
"type": "fs.StatWatcher"
}
}
],
"desc": "Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.
The options argument may be omitted. If provided, it should be an object. The\noptions object may contain a boolean named persistent that indicates\nwhether the process should continue to run as long as files are being watched.\nThe options object may specify an interval property indicating how often the\ntarget should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous\nstat object:
import { watchFile } from 'node:fs';\n\nwatchFile('message.text', (curr, prev) => {\n console.log(`the current mtime is: ${curr.mtime}`);\n console.log(`the previous mtime was: ${prev.mtime}`);\n});\n\nThese stat objects are instances of fs.Stat. If the bigint option is true,\nthe numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary\nto compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it\nwill invoke the listener once, with all the fields zeroed (or, for dates, the\nUnix Epoch). If the file is created later on, the listener will be called\nagain, with the latest stat objects. This is a change in functionality since\nv0.10.
Using fs.watch() is more efficient than fs.watchFile and\nfs.unwatchFile. fs.watch should be used instead of fs.watchFile and\nfs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears,\nthen the contents of previous in the second callback event (the file's\nreappearance) will be the same as the contents of previous in the first\ncallback event (its disappearance).
This happens when:
\nWrite buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.
position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).
The callback will be given three arguments (err, bytesWritten, buffer) where\nbytesWritten specifies how many bytes were written from buffer.
If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
" }, { "textRaw": "`fs.write(fd, buffer[, options], callback)`", "name": "write", "type": "method", "meta": { "added": [ "v18.3.0", "v16.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView}", "name": "buffer", "type": "Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`offset` {integer} **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`" }, { "textRaw": "`length` {integer} **Default:** `buffer.byteLength - offset`", "name": "length", "type": "integer", "default": "`buffer.byteLength - offset`" }, { "textRaw": "`position` {integer|null} **Default:** `null`", "name": "position", "type": "integer|null", "default": "`null`" } ], "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`bytesWritten` {integer}", "name": "bytesWritten", "type": "integer" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView}", "name": "buffer", "type": "Buffer|TypedArray|DataView" } ] } ] } ], "desc": "Write buffer to the file specified by fd.
Similar to the above fs.write function, this version takes an\noptional options object. If no options object is specified, it will\ndefault with the above values.
Write string to the file specified by fd. If string is not a string,\nan exception is thrown.
position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number' the data will be written at\nthe current position. See pwrite(2).
encoding is the expected string encoding.
The callback will receive the arguments (err, written, string) where written\nspecifies how many bytes the passed string required to be written. Bytes\nwritten is not necessarily the same as string characters written. See\nBuffer.byteLength.
It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
\nOn Windows, if the file descriptor is connected to the console (e.g. fd == 1\nor stdout) a string containing non-ASCII characters will not be rendered\nproperly by default, regardless of the encoding used.\nIt is possible to configure the console to render UTF-8 properly by changing the\nactive codepage with the chcp 65001 command. See the chcp docs for more\ndetails.
When file is a filename, asynchronously writes data to the file, replacing the\nfile if it already exists. data can be a string or a buffer.
When file is a file descriptor, the behavior is similar to calling\nfs.write() directly (which is recommended). See the notes below on using\na file descriptor.
The encoding option is ignored if data is a buffer.
The mode option only affects the newly created file. See fs.open()\nfor more details.
import { writeFile } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nconst data = new Uint8Array(Buffer.from('Hello Node.js'));\nwriteFile('message.txt', data, (err) => {\n if (err) throw err;\n console.log('The file has been saved!');\n});\n\nIf options is a string, then it specifies the encoding:
import { writeFile } from 'node:fs';\n\nwriteFile('message.txt', 'Hello Node.js', 'utf8', callback);\n\nIt is unsafe to use fs.writeFile() multiple times on the same file without\nwaiting for the callback. For this scenario, fs.createWriteStream() is\nrecommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that\nperforms multiple write calls internally to write the buffer passed to it.\nFor performance sensitive code consider using fs.createWriteStream().
It is possible to use an <AbortSignal> to cancel an fs.writeFile().\nCancelation is \"best effort\", and some amount of data is likely still\nto be written.
import { writeFile } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nconst controller = new AbortController();\nconst { signal } = controller;\nconst data = new Uint8Array(Buffer.from('Hello Node.js'));\nwriteFile('message.txt', data, { signal }, (err) => {\n // When a request is aborted - the callback is called with an AbortError\n});\n// When the request should be aborted\ncontroller.abort();\n\nAborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.writeFile performs.
When file is a file descriptor, the behavior is almost identical to directly\ncalling fs.write() like:
import { write } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nwrite(fd, Buffer.from(data, options.encoding), callback);\n\nThe difference from directly calling fs.write() is that under some unusual\nconditions, fs.write() might write only part of the buffer and need to be\nretried to write the remaining data, whereas fs.writeFile() retries until\nthe data is entirely written (or an error occurs).
The implications of this are a common source of confusion. In\nthe file descriptor case, the file is not replaced! The data is not necessarily\nwritten to the beginning of the file, and the file's original data may remain\nbefore and/or after the newly written data.
\nFor example, if fs.writeFile() is called twice in a row, first to write the\nstring 'Hello', then to write the string ', World', the file would contain\n'Hello, World', and might contain some of the file's original data (depending\non the size of the original file, and the position of the file descriptor). If\na file name had been used instead of a descriptor, the file would be guaranteed\nto contain only ', World'.
Write an array of ArrayBufferViews to the file specified by fd using\nwritev().
position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.
The callback will be given three arguments: err, bytesWritten, and\nbuffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify()ed, it returns a promise for an\nObject with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without\nwaiting for the callback. For this scenario, use fs.createWriteStream().
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
" } ], "displayName": "Callback API" }, { "textRaw": "Synchronous API", "name": "synchronous_api", "type": "module", "desc": "The synchronous APIs perform all operations synchronously, blocking the\nevent loop until the operation completes or fails.
", "methods": [ { "textRaw": "`fs.accessSync(path[, mode])`", "name": "accessSync", "type": "method", "meta": { "added": [ "v0.11.15" ], "changes": [ { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`mode` {integer} **Default:** `fs.constants.F_OK`", "name": "mode", "type": "integer", "default": "`fs.constants.F_OK`", "optional": true } ] } ], "desc": "Synchronously tests a user's permissions for the file or directory specified\nby path. The mode argument is an optional integer that specifies the\naccessibility checks to be performed. mode should be either the value\nfs.constants.F_OK or a mask consisting of the bitwise OR of any of\nfs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.\nfs.constants.W_OK | fs.constants.R_OK). Check File access constants for\npossible values of mode.
If any of the accessibility checks fail, an Error will be thrown. Otherwise,\nthe method will return undefined.
import { accessSync, constants } from 'node:fs';\n\ntry {\n accessSync('etc/passwd', constants.R_OK | constants.W_OK);\n console.log('can read/write');\n} catch (err) {\n console.error('no access!');\n}\n"
},
{
"textRaw": "`fs.appendFileSync(path, data[, options])`",
"name": "appendFileSync",
"type": "method",
"meta": {
"added": [
"v0.6.7"
],
"changes": [
{
"version": [
"v21.1.0",
"v20.10.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50095",
"description": "The `flush` option is now supported."
},
{
"version": "v7.0.0",
"pr-url": "https://github.com/nodejs/node/pull/7831",
"description": "The passed `options` object will never be modified."
},
{
"version": "v5.0.0",
"pr-url": "https://github.com/nodejs/node/pull/3163",
"description": "The `file` parameter can be a file descriptor now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL|number} filename or file descriptor",
"name": "path",
"type": "string|Buffer|URL|number",
"desc": "filename or file descriptor"
},
{
"textRaw": "`data` {string|Buffer}",
"name": "data",
"type": "string|Buffer"
},
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`encoding` {string|null} **Default:** `'utf8'`",
"name": "encoding",
"type": "string|null",
"default": "`'utf8'`"
},
{
"textRaw": "`mode` {integer} **Default:** `0o666`",
"name": "mode",
"type": "integer",
"default": "`0o666`"
},
{
"textRaw": "`flag` {string} See support of file system `flags`. **Default:** `'a'`.",
"name": "flag",
"type": "string",
"default": "`'a'`",
"desc": "See support of file system `flags`."
},
{
"textRaw": "`flush` {boolean} If `true`, the underlying file descriptor is flushed prior to closing it. **Default:** `false`.",
"name": "flush",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, the underlying file descriptor is flushed prior to closing it."
}
],
"optional": true
}
]
}
],
"desc": "Synchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.
The mode option only affects the newly created file. See fs.open()\nfor more details.
import { appendFileSync } from 'node:fs';\n\ntry {\n appendFileSync('message.txt', 'data to append');\n console.log('The \"data to append\" was appended to file!');\n} catch (err) {\n /* Handle the error */\n}\n\nIf options is a string, then it specifies the encoding:
import { appendFileSync } from 'node:fs';\n\nappendFileSync('message.txt', 'data to append', 'utf8');\n\nThe path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.
import { openSync, closeSync, appendFileSync } from 'node:fs';\n\nlet fd;\n\ntry {\n fd = openSync('message.txt', 'a');\n appendFileSync(fd, 'data to append', 'utf8');\n} catch (err) {\n /* Handle the error */\n} finally {\n if (fd !== undefined)\n closeSync(fd);\n}\n"
},
{
"textRaw": "`fs.chmodSync(path, mode)`",
"name": "chmodSync",
"type": "method",
"meta": {
"added": [
"v0.6.7"
],
"changes": [
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`mode` {string|integer}",
"name": "mode",
"type": "string|integer"
}
]
}
],
"desc": "For detailed information, see the documentation of the asynchronous version of\nthis API: fs.chmod().
See the POSIX chmod(2) documentation for more detail.
Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().
See the POSIX chown(2) documentation for more detail.
Closes the file descriptor. Returns undefined.
Calling fs.closeSync() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
Synchronously copies src to dest. By default, dest is overwritten if it\nalready exists. Returns undefined. Node.js makes no guarantees about the\natomicity of the copy operation. If an error occurs after the destination file\nhas been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a\ncopy-on-write reflink. If the platform does not support copy-on-write, then a\nfallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to\ncreate a copy-on-write reflink. If the platform does not support\ncopy-on-write, then the operation will fail.import { copyFileSync, constants } from 'node:fs';\n\n// destination.txt will be created or overwritten by default.\ncopyFileSync('source.txt', 'destination.txt');\nconsole.log('source.txt was copied to destination.txt');\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ncopyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);\n"
},
{
"textRaw": "`fs.cpSync(src, dest[, options])`",
"name": "cpSync",
"type": "method",
"meta": {
"added": [
"v16.7.0"
],
"changes": [
{
"version": "v22.3.0",
"pr-url": "https://github.com/nodejs/node/pull/53127",
"description": "This API is no longer experimental."
},
{
"version": [
"v20.1.0",
"v18.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/47084",
"description": "Accept an additional `mode` option to specify the copy behavior as the `mode` argument of `fs.copyFile()`."
},
{
"version": [
"v17.6.0",
"v16.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/41819",
"description": "Accepts an additional `verbatimSymlinks` option to specify whether to perform path resolution for symlinks."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`src` {string|URL} source path to copy.",
"name": "src",
"type": "string|URL",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string|URL} destination path to copy to.",
"name": "dest",
"type": "string|URL",
"desc": "destination path to copy to."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`dereference` {boolean} dereference symlinks. **Default:** `false`.",
"name": "dereference",
"type": "boolean",
"default": "`false`",
"desc": "dereference symlinks."
},
{
"textRaw": "`errorOnExist` {boolean} when `force` is `false`, and the destination exists, throw an error. **Default:** `false`.",
"name": "errorOnExist",
"type": "boolean",
"default": "`false`",
"desc": "when `force` is `false`, and the destination exists, throw an error."
},
{
"textRaw": "`filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well. **Default:** `undefined`",
"name": "filter",
"type": "Function",
"default": "`undefined`",
"desc": "Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. When ignoring a directory, all of its contents will be skipped as well.",
"options": [
{
"textRaw": "`src` {string} source path to copy.",
"name": "src",
"type": "string",
"desc": "source path to copy."
},
{
"textRaw": "`dest` {string} destination path to copy to.",
"name": "dest",
"type": "string",
"desc": "destination path to copy to."
},
{
"textRaw": "Returns: {boolean} Any non-`Promise` value that is coercible to `boolean`.",
"name": "return",
"type": "boolean",
"desc": "Any non-`Promise` value that is coercible to `boolean`."
}
]
},
{
"textRaw": "`force` {boolean} overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior. **Default:** `true`.",
"name": "force",
"type": "boolean",
"default": "`true`",
"desc": "overwrite existing file or directory. The copy operation will ignore errors if you set this to false and the destination exists. Use the `errorOnExist` option to change this behavior."
},
{
"textRaw": "`mode` {integer} modifiers for copy operation. **Default:** `0`. See `mode` flag of `fs.copyFileSync()`.",
"name": "mode",
"type": "integer",
"default": "`0`. See `mode` flag of `fs.copyFileSync()`",
"desc": "modifiers for copy operation."
},
{
"textRaw": "`preserveTimestamps` {boolean} When `true` timestamps from `src` will be preserved. **Default:** `false`.",
"name": "preserveTimestamps",
"type": "boolean",
"default": "`false`",
"desc": "When `true` timestamps from `src` will be preserved."
},
{
"textRaw": "`recursive` {boolean} copy directories recursively **Default:** `false`",
"name": "recursive",
"type": "boolean",
"default": "`false`",
"desc": "copy directories recursively"
},
{
"textRaw": "`verbatimSymlinks` {boolean} When `true`, path resolution for symlinks will be skipped. **Default:** `false`",
"name": "verbatimSymlinks",
"type": "boolean",
"default": "`false`",
"desc": "When `true`, path resolution for symlinks will be skipped."
}
],
"optional": true
}
]
}
],
"desc": "Synchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.
When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.
Returns true if the path exists, false otherwise.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.exists().
fs.exists() is deprecated, but fs.existsSync() is not. The callback\nparameter to fs.exists() accepts parameters that are inconsistent with other\nNode.js callbacks. fs.existsSync() does not use a callback.
import { existsSync } from 'node:fs';\n\nif (existsSync('/etc/passwd'))\n console.log('The path exists.');\n"
},
{
"textRaw": "`fs.fchmodSync(fd, mode)`",
"name": "fchmodSync",
"type": "method",
"meta": {
"added": [
"v0.4.7"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fd` {integer}",
"name": "fd",
"type": "integer"
},
{
"textRaw": "`mode` {string|integer}",
"name": "mode",
"type": "string|integer"
}
]
}
],
"desc": "Sets the permissions on the file. Returns undefined.
See the POSIX fchmod(2) documentation for more detail.
Sets the owner of the file. Returns undefined.
See the POSIX fchown(2) documentation for more detail.
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details. Returns undefined.
Retrieves the <fs.Stats> for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail. Returns undefined.
Truncates the file descriptor. Returns undefined.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.ftruncate().
Synchronous version of fs.futimes(). Returns undefined.
import { globSync } from 'node:fs';\n\nconsole.log(globSync('**/*.js'));\n\nconst { globSync } = require('node:fs');\n\nconsole.log(globSync('**/*.js'));\n"
},
{
"textRaw": "`fs.lchmodSync(path, mode)`",
"name": "lchmodSync",
"type": "method",
"meta": {
"changes": [],
"deprecated": [
"v0.4.7"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`mode` {integer}",
"name": "mode",
"type": "integer"
}
]
}
],
"desc": "Changes the permissions on a symbolic link. Returns undefined.
This method is only implemented on macOS.
\nSee the POSIX lchmod(2) documentation for more detail.
Set the owner for the path. Returns undefined.
See the POSIX lchown(2) documentation for more details.
Change the file system timestamps of the symbolic link referenced by path.\nReturns undefined, or throws an exception when parameters are incorrect or\nthe operation fails. This is the synchronous version of fs.lutimes().
Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail. Returns undefined.
Retrieves the <fs.Stats> for the symbolic link referred to by path.
See the POSIX lstat(2) documentation for more details.
Synchronously creates a directory. Returns undefined, or if recursive is\ntrue, the first directory path created.\nThis is the synchronous version of fs.mkdir().
See the POSIX mkdir(2) documentation for more details.
Returns the created directory path.
\nFor detailed information, see the documentation of the asynchronous version of\nthis API: fs.mkdtemp().
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
Returns a disposable object whose path property holds the created directory\npath. When the object is disposed, the directory and its contents will be\nremoved if it still exists. If the directory cannot be deleted, disposal will\nthrow an error. The object has a remove() method which will perform the same\ntask.
For detailed information, see the documentation of fs.mkdtemp().
There is no callback-based version of this API because it is designed for use\nwith the using syntax.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
Synchronously open a directory. See opendir(3).
Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.
The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.
Returns an integer representing the file descriptor.
\nFor detailed information, see the documentation of the asynchronous version of\nthis API: fs.open().
Reads the contents of the directory.
\nSee the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames returned. If the encoding is set to 'buffer',\nthe filenames returned will be passed as <Buffer> objects.
If options.withFileTypes is set to true, the result will contain\n<fs.Dirent> objects.
Returns the contents of the path.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readFile().
If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.
Similar to fs.readFile(), when the path is a directory, the behavior of\nfs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';\n\n// macOS, Linux, and Windows\nreadFileSync('<directory>');\n// => [Error: EISDIR: illegal operation on a directory, read <directory>]\n\n// FreeBSD\nreadFileSync('<directory>'); // => <data>\n"
},
{
"textRaw": "`fs.readlinkSync(path[, options])`",
"name": "readlinkSync",
"type": "method",
"meta": {
"added": [
"v0.1.31"
],
"changes": [
{
"version": "v7.6.0",
"pr-url": "https://github.com/nodejs/node/pull/10739",
"description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`options` {string|Object}",
"name": "options",
"type": "string|Object",
"options": [
{
"textRaw": "`encoding` {string} **Default:** `'utf8'`",
"name": "encoding",
"type": "string",
"default": "`'utf8'`"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {string|Buffer}",
"name": "return",
"type": "string|Buffer"
}
}
],
"desc": "Returns the symbolic link's string value.
\nSee the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer',\nthe link path returned will be passed as a <Buffer> object.
Returns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().
Returns the number of bytesRead.
Similar to the above fs.readSync function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readv().
Returns the resolved pathname.
\nFor detailed information, see the documentation of the asynchronous version of\nthis API: fs.realpath().
Synchronous realpath(3).
Only paths that can be converted to UTF8 strings are supported.
\nThe optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path returned. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.
On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.
Renames the file from oldPath to newPath. Returns undefined.
See the POSIX rename(2) documentation for more details.
Synchronous rmdir(2). Returns undefined.
Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error\non Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use fs.rmSync()\nwith options { recursive: true, force: true }.
Synchronously removes files and directories (modeled on the standard POSIX rm\nutility). Returns undefined.
Retrieves the <fs.Stats> for the path.
Synchronous statfs(2). Returns information about the mounted file system which\ncontains path.
In case of an error, the err.code will be one of Common System Errors.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.symlink().
Truncates the file. Returns undefined. A file descriptor can also be\npassed 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\nin the future.
" }, { "textRaw": "`fs.unlinkSync(path)`", "name": "unlinkSync", "type": "method", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `path` parameter can be a WHATWG `URL` object using `file:` protocol." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" } ] } ], "desc": "Synchronous unlink(2). Returns undefined.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.utimes().
The mode option only affects the newly created file. See fs.open()\nfor more details.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writeFile().
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, string...).
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writev().
The common objects are shared by all of the file system API variants\n(promise, callback, and synchronous).
", "classes": [ { "textRaw": "Class: `fs.Dir`", "name": "fs.Dir", "type": "class", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "desc": "A class representing a directory stream.
\nCreated by fs.opendir(), fs.opendirSync(), or\nfsPromises.opendir().
import { opendir } from 'node:fs/promises';\n\ntry {\n const dir = await opendir('./');\n for await (const dirent of dir)\n console.log(dirent.name);\n} catch (err) {\n console.error(err);\n}\n\nWhen using the async iterator, the <fs.Dir> object will be automatically\nclosed after the iterator exits.
Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.
\nA promise is returned that will be fulfilled after the resource has been\nclosed.
" }, { "textRaw": "`dir.close(callback)`", "name": "close", "type": "method", "meta": { "added": [ "v12.12.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.
\nThe callback will be called after the resource handle has been closed.
Synchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.
" }, { "textRaw": "`dir.read()`", "name": "read", "type": "method", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Promise} Fulfills with a {fs.Dirent|null}", "name": "return", "type": "Promise", "desc": "Fulfills with a {fs.Dirent|null}" } } ], "desc": "Asynchronously read the next directory entry via readdir(3) as an <fs.Dirent>.
A promise is returned that will be fulfilled with an <fs.Dirent>, or null\nif there are no more directory entries to read.
Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
" }, { "textRaw": "`dir.read(callback)`", "name": "read", "type": "method", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`dirent` {fs.Dirent|null}", "name": "dirent", "type": "fs.Dirent|null" } ] } ] } ], "desc": "Asynchronously read the next directory entry via readdir(3) as an <fs.Dirent>.
After the read is completed, the callback will be called with an\n<fs.Dirent>, or null if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
" }, { "textRaw": "`dir.readSync()`", "name": "readSync", "type": "method", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {fs.Dirent|null}", "name": "return", "type": "fs.Dirent|null" } } ], "desc": "Synchronously read the next directory entry as an <fs.Dirent>. See the\nPOSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, null will be returned.
Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
" }, { "textRaw": "`dir[Symbol.asyncIterator]()`", "name": "[Symbol.asyncIterator]", "type": "method", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {AsyncIterator} An AsyncIterator of {fs.Dirent}", "name": "return", "type": "AsyncIterator", "desc": "An AsyncIterator of {fs.Dirent}" } } ], "desc": "Asynchronously iterates over the directory until all entries have\nbeen read. Refer to the POSIX readdir(3) documentation for more detail.
Entries returned by the async iterator are always an <fs.Dirent>.\nThe null case from dir.read() is handled internally.
See <fs.Dir> for an example.
Directory entries returned by this iterator are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
" }, { "textRaw": "`dir[Symbol.asyncDispose]()`", "name": "[Symbol.asyncDispose]", "type": "method", "meta": { "added": [ "v24.1.0", "v22.1.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58467", "description": "No longer experimental." } ] }, "signatures": [ { "params": [] } ], "desc": "Calls dir.close() if the directory handle is open, and returns a promise that\nfulfills when disposal is complete.
Calls dir.closeSync() if the directory handle is open, and returns\nundefined.
The read-only path of this directory as was provided to fs.opendir(),\nfs.opendirSync(), or fsPromises.opendir().
A representation of a directory entry, which can be a file or a subdirectory\nwithin the directory, as returned by reading from an <fs.Dir>. The\ndirectory entry is a combination of the file name and file type pairs.
Additionally, when fs.readdir() or fs.readdirSync() is called with\nthe withFileTypes option set to true, the resulting array is filled with\n<fs.Dirent> objects, rather than strings or <Buffer>s.
Returns true if the <fs.Dirent> object describes a block device.
Returns true if the <fs.Dirent> object describes a character device.
Returns true if the <fs.Dirent> object describes a file system\ndirectory.
Returns true if the <fs.Dirent> object describes a first-in-first-out\n(FIFO) pipe.
Returns true if the <fs.Dirent> object describes a regular file.
Returns true if the <fs.Dirent> object describes a socket.
Returns true if the <fs.Dirent> object describes a symbolic link.
The file name that this <fs.Dirent> object refers to. The type of this\nvalue is determined by the options.encoding passed to fs.readdir() or\nfs.readdirSync().
The path to the parent directory of the file this <fs.Dirent> object refers to.
<EventEmitter>A successful call to fs.watch() method will return a new <fs.FSWatcher>\nobject.
All <fs.FSWatcher> objects emit a 'change' event whenever a specific watched\nfile is modified.
Emitted when something changes in a watched directory or file.\nSee more details in fs.watch().
The filename argument may not be provided depending on operating system\nsupport. If filename is provided, it will be provided as a <Buffer> if fs.watch() is called with its encoding option set to 'buffer', otherwise\nfilename will be a UTF-8 string.
import { watch } from 'node:fs';\n// Example when handled through fs.watch() listener\nwatch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {\n if (filename) {\n console.log(filename);\n // Prints: <Buffer ...>\n }\n});\n"
},
{
"textRaw": "Event: `'close'`",
"name": "close",
"type": "event",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"params": [],
"desc": "Emitted when the watcher stops watching for changes. The closed\n<fs.FSWatcher> object is no longer usable in the event handler.
Emitted when an error occurs while watching the file. The errored\n<fs.FSWatcher> object is no longer usable in the event handler.
Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the\n<fs.FSWatcher> object is no longer usable.
When called, requests that the Node.js event loop not exit so long as the\n<fs.FSWatcher> is active. Calling watcher.ref() multiple times will have\nno effect.
By default, all <fs.FSWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.
When called, the active <fs.FSWatcher> object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the <fs.FSWatcher> object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.
<EventEmitter>A successful call to fs.watchFile() method will return a new <fs.StatWatcher>\nobject.
When called, requests that the Node.js event loop not exit so long as the\n<fs.StatWatcher> is active. Calling watcher.ref() multiple times will have\nno effect.
By default, all <fs.StatWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.
When called, the active <fs.StatWatcher> object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the <fs.StatWatcher> object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.
<stream.Readable>Instances of <fs.ReadStream> are created and returned using the fs.createReadStream() function.
Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.
Emitted when the <fs.ReadStream>'s file descriptor has been opened.
Emitted when the <fs.ReadStream> is ready to be used.
Fires immediately after 'open'.
The number of bytes that have been read so far.
" }, { "textRaw": "Type: {string|Buffer}", "name": "path", "type": "string|Buffer", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "desc": "The path to the file the stream is reading from as specified in the first\nargument to fs.createReadStream(). If path is passed as a string, then\nreadStream.path will be a string. If path is passed as a <Buffer>, then readStream.path will be a <Buffer>. If fd is specified, then\nreadStream.path will be undefined.
This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.
A <fs.Stats> object provides information about a file.
Objects returned from fs.stat(), fs.lstat(), fs.fstat(), and\ntheir synchronous counterparts are of this type.\nIf bigint in the options passed to those methods is true, the numeric values\nwill be bigint instead of number, and the object will contain additional\nnanosecond-precision properties suffixed with Ns.\nStat objects are not to be created directly using the new keyword.
Stats {\n dev: 2114,\n ino: 48064969,\n mode: 33188,\n nlink: 1,\n uid: 85,\n gid: 100,\n rdev: 0,\n size: 527,\n blksize: 4096,\n blocks: 8,\n atimeMs: 1318289051000.1,\n mtimeMs: 1318289051000.1,\n ctimeMs: 1318289051000.1,\n birthtimeMs: 1318289051000.1,\n atime: Mon, 10 Oct 2011 23:24:11 GMT,\n mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n\nbigint version:
BigIntStats {\n dev: 2114n,\n ino: 48064969n,\n mode: 33188n,\n nlink: 1n,\n uid: 85n,\n gid: 100n,\n rdev: 0n,\n size: 527n,\n blksize: 4096n,\n blocks: 8n,\n atimeMs: 1318289051000n,\n mtimeMs: 1318289051000n,\n ctimeMs: 1318289051000n,\n birthtimeMs: 1318289051000n,\n atimeNs: 1318289051000000000n,\n mtimeNs: 1318289051000000000n,\n ctimeNs: 1318289051000000000n,\n birthtimeNs: 1318289051000000000n,\n atime: Mon, 10 Oct 2011 23:24:11 GMT,\n mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n",
"methods": [
{
"textRaw": "`stats.isBlockDevice()`",
"name": "isBlockDevice",
"type": "method",
"meta": {
"added": [
"v0.1.10"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the <fs.Stats> object describes a block device.
Returns true if the <fs.Stats> object describes a character device.
Returns true if the <fs.Stats> object describes a file system directory.
If the <fs.Stats> object was obtained from calling fs.lstat() on a\nsymbolic link which resolves to a directory, this method will return false.\nThis is because fs.lstat() returns information\nabout a symbolic link itself and not the path it resolves to.
Returns true if the <fs.Stats> object describes a first-in-first-out (FIFO)\npipe.
Returns true if the <fs.Stats> object describes a regular file.
Returns true if the <fs.Stats> object describes a socket.
Returns true if the <fs.Stats> object describes a symbolic link.
This method is only valid when using fs.lstat().
The numeric identifier of the device containing the file.
" }, { "textRaw": "Type: {number|bigint}", "name": "ino", "type": "number|bigint", "desc": "The file system specific \"Inode\" number for the file.
" }, { "textRaw": "Type: {number|bigint}", "name": "mode", "type": "number|bigint", "desc": "A bit-field describing the file type and mode.
" }, { "textRaw": "Type: {number|bigint}", "name": "nlink", "type": "number|bigint", "desc": "The number of hard-links that exist for the file.
" }, { "textRaw": "Type: {number|bigint}", "name": "uid", "type": "number|bigint", "desc": "The numeric user identifier of the user that owns the file (POSIX).
" }, { "textRaw": "Type: {number|bigint}", "name": "gid", "type": "number|bigint", "desc": "The numeric group identifier of the group that owns the file (POSIX).
" }, { "textRaw": "Type: {number|bigint}", "name": "rdev", "type": "number|bigint", "desc": "A numeric device identifier if the file represents a device.
" }, { "textRaw": "Type: {number|bigint}", "name": "size", "type": "number|bigint", "desc": "The size of the file in bytes.
\nIf the underlying file system does not support getting the size of the file,\nthis will be 0.
The file system block size for i/o operations.
" }, { "textRaw": "Type: {number|bigint}", "name": "blocks", "type": "number|bigint", "desc": "The number of blocks allocated for this file.
" }, { "textRaw": "Type: {number|bigint}", "name": "atimeMs", "type": "number|bigint", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "The timestamp indicating the last time this file was accessed expressed in\nmilliseconds since the POSIX Epoch.
" }, { "textRaw": "Type: {number|bigint}", "name": "mtimeMs", "type": "number|bigint", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "The timestamp indicating the last time this file was modified expressed in\nmilliseconds since the POSIX Epoch.
" }, { "textRaw": "Type: {number|bigint}", "name": "ctimeMs", "type": "number|bigint", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "The timestamp indicating the last time the file status was changed expressed\nin milliseconds since the POSIX Epoch.
" }, { "textRaw": "Type: {number|bigint}", "name": "birthtimeMs", "type": "number|bigint", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "The timestamp indicating the creation time of this file expressed in\nmilliseconds since the POSIX Epoch.
" }, { "textRaw": "Type: {bigint}", "name": "atimeNs", "type": "bigint", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was accessed expressed in\nnanoseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was modified expressed in\nnanoseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time the file status was changed expressed\nin nanoseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the creation time of this file expressed in\nnanoseconds since the POSIX Epoch.
The timestamp indicating the last time this file was accessed.
" }, { "textRaw": "Type: {Date}", "name": "mtime", "type": "Date", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "The timestamp indicating the last time this file was modified.
" }, { "textRaw": "Type: {Date}", "name": "ctime", "type": "Date", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "The timestamp indicating the last time the file status was changed.
" }, { "textRaw": "Type: {Date}", "name": "birthtime", "type": "Date", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "The timestamp indicating the creation time of this file.
" } ], "modules": [ { "textRaw": "Stat time values", "name": "stat_time_values", "type": "module", "desc": "The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are\nnumeric values that hold the corresponding times in milliseconds. Their\nprecision is platform specific. When bigint: true is passed into the\nmethod that generates the object, the properties will be bigints,\notherwise they will be numbers.
The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are\nbigints that hold the corresponding times in nanoseconds. They are\nonly present when bigint: true is passed into the method that generates\nthe object. Their precision is platform specific.
atime, mtime, ctime, and birthtime are\nDate object alternate representations of the various times. The\nDate and number values are not connected. Assigning a new number value, or\nmutating the Date value, will not be reflected in the corresponding alternate\nrepresentation.
The times in the stat object have the following semantics:
\natime \"Access Time\": Time when file data last accessed. Changed\nby the mknod(2), utimes(2), and read(2) system calls.mtime \"Modified Time\": Time when file data last modified.\nChanged by the mknod(2), utimes(2), and write(2) system calls.ctime \"Change Time\": Time when file status was last changed\n(inode data modification). Changed by the chmod(2), chown(2),\nlink(2), mknod(2), rename(2), unlink(2), utimes(2),\nread(2), and write(2) system calls.birthtime \"Birth Time\": Time of file creation. Set once when the\nfile is created. On file systems where birthtime is not available,\nthis field may instead hold either the ctime or\n1970-01-01T00:00Z (ie, Unix epoch timestamp 0). This value may be greater\nthan atime or mtime in this case. On Darwin and other FreeBSD variants,\nalso set if the atime is explicitly set to an earlier value than the current\nbirthtime using the utimes(2) system call.Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As\nof 0.12, ctime is not \"creation time\", and on Unix systems, it never was.
Provides information about a mounted file system.
\nObjects returned from fs.statfs() and its synchronous counterpart are of\nthis type. If bigint in the options passed to those methods is true, the\nnumeric values will be bigint instead of number.
StatFs {\n type: 1397114950,\n bsize: 4096,\n blocks: 121938943,\n bfree: 61058895,\n bavail: 61058895,\n files: 999,\n ffree: 1000000\n}\n\nbigint version:
StatFs {\n type: 1397114950n,\n bsize: 4096n,\n blocks: 121938943n,\n bfree: 61058895n,\n bavail: 61058895n,\n files: 999n,\n ffree: 1000000n\n}\n",
"properties": [
{
"textRaw": "Type: {number|bigint}",
"name": "bavail",
"type": "number|bigint",
"meta": {
"added": [
"v19.6.0",
"v18.15.0"
],
"changes": []
},
"desc": "Free blocks available to unprivileged users.
" }, { "textRaw": "Type: {number|bigint}", "name": "bfree", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Free blocks in file system.
" }, { "textRaw": "Type: {number|bigint}", "name": "blocks", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Total data blocks in file system.
" }, { "textRaw": "Type: {number|bigint}", "name": "bsize", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Optimal transfer block size.
" }, { "textRaw": "Type: {number|bigint}", "name": "ffree", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Free file nodes in file system.
" }, { "textRaw": "Type: {number|bigint}", "name": "files", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Total file nodes in file system.
" }, { "textRaw": "Type: {number|bigint}", "name": "type", "type": "number|bigint", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "desc": "Type of file system.
" } ] }, { "textRaw": "Class: `fs.Utf8Stream`", "name": "fs.Utf8Stream", "type": "class", "meta": { "added": [ "v24.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "An optimized UTF-8 stream writer that allows for flushing all the internal\nbuffering on demand. It handles EAGAIN errors correctly, allowing for\ncustomization, for example, by dropping content if the disk is busy.
The 'close' event is emitted when the stream is fully closed.
The 'drain' event is emitted when the internal buffer has drained sufficiently\nto allow continued writing.
The 'drop' event is emitted when the maximal length is reached and that data\nwill not be written. The data that was dropped is passed as the first argument\nto the event handler.
The 'error' event is emitted when an error occurs.
The 'finish' event is emitted when the stream has been ended and all data has\nbeen flushed to the underlying file.
The 'ready' event is emitted when the stream is ready to accept writes.
The 'write' event is emitted when a write operation has completed. The number\nof bytes written is passed as the first argument to the event handler.
Close the stream immediately, without flushing the internal buffer.
" }, { "textRaw": "`utf8Stream.end()`", "name": "end", "type": "method", "signatures": [ { "params": [] } ], "desc": "Close the stream gracefully, flushing the internal buffer before closing.
" }, { "textRaw": "`utf8Stream.flush(callback)`", "name": "flush", "type": "method", "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error|null} An error if the flush failed, otherwise `null`.", "name": "err", "type": "Error|null", "desc": "An error if the flush failed, otherwise `null`." } ] } ] } ], "desc": "Writes the current buffer to the file if a write was not in progress. Do\nnothing if minLength is zero or if it is already writing.
Flushes the buffered data synchronously. This is a costly operation.
" }, { "textRaw": "`utf8Stream.reopen(file)`", "name": "reopen", "type": "method", "signatures": [ { "params": [ { "name": "file" } ] } ], "desc": "file: <string> | <Buffer> | <URL> A path to a file to be written to (mode\ncontrolled by the append option).Reopen the file in place, useful for log rotation.
" }, { "textRaw": "`utf8Stream.write(data)`", "name": "write", "type": "method", "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer} The data to write.", "name": "data", "type": "string|Buffer", "desc": "The data to write." } ], "return": { "textRaw": "Returns {boolean}", "name": "return", "type": "boolean" } } ], "desc": "When the options.contentMode is set to 'utf8' when the stream is created,\nthe data argument must be a string. If the contentMode is set to 'buffer',\nthe data argument must be a <Buffer>.
Calls utf8Stream.destroy().
<stream.Writable>Instances of <fs.WriteStream> are created and returned using the fs.createWriteStream() function.
Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.
Emitted when the <fs.WriteStream>'s file is opened.
Emitted when the <fs.WriteStream> is ready to be used.
Fires immediately after 'open'.
The number of bytes written so far. Does not include data that is still queued\nfor writing.
" }, { "textRaw": "`writeStream.path`", "name": "path", "type": "property", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "desc": "The path to the file the stream is writing to as specified in the first\nargument to fs.createWriteStream(). If path is passed as a string, then\nwriteStream.path will be a string. If path is passed as a <Buffer>, then writeStream.path will be a <Buffer>.
This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.
Closes writeStream. Optionally accepts a\ncallback that will be executed once the writeStream\nis closed.
Returns an object containing commonly used constants for file system\noperations.
", "modules": [ { "textRaw": "FS constants", "name": "fs_constants", "type": "module", "desc": "The following constants are exported by fs.constants and fsPromises.constants.
Not every constant will be available on every operating system;\nthis is especially important for Windows, where many of the POSIX specific\ndefinitions are not available.\nFor portable applications it is recommended to check for their presence\nbefore use.
\nTo use more than one constant, use the bitwise OR | operator.
Example:
\nimport { open, constants } from 'node:fs';\n\nconst {\n O_RDWR,\n O_CREAT,\n O_EXCL,\n} = constants;\n\nopen('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {\n // ...\n});\n",
"modules": [
{
"textRaw": "File access constants",
"name": "file_access_constants",
"type": "module",
"desc": "The following constants are meant for use as the mode parameter passed to\nfsPromises.access(), fs.access(), and fs.accessSync().
| Constant | Description |
|---|---|
F_OK | Flag indicating that the file is visible to the calling process.\n This is useful for determining if a file exists, but says nothing\n about rwx permissions. Default if no mode is specified. |
R_OK | Flag indicating that the file can be read by the calling process. |
W_OK | Flag indicating that the file can be written by the calling\n process. |
X_OK | Flag indicating that the file can be executed by the calling\n process. This has no effect on Windows\n (will behave like fs.constants.F_OK). |
The definitions are also available on Windows.
", "displayName": "File access constants" }, { "textRaw": "File copy constants", "name": "file_copy_constants", "type": "module", "desc": "The following constants are meant for use with fs.copyFile().
| Constant | Description |
|---|---|
COPYFILE_EXCL | If present, the copy operation will fail with an error if the\n destination path already exists. |
COPYFILE_FICLONE | If present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then a fallback copy mechanism is used. |
COPYFILE_FICLONE_FORCE | If present, the copy operation will attempt to create a\n copy-on-write reflink. If the underlying platform does not support\n copy-on-write, then the operation will fail with an error. |
The definitions are also available on Windows.
", "displayName": "File copy constants" }, { "textRaw": "File open constants", "name": "file_open_constants", "type": "module", "desc": "The following constants are meant for use with fs.open().
| Constant | Description |
|---|---|
O_RDONLY | Flag indicating to open a file for read-only access. |
O_WRONLY | Flag indicating to open a file for write-only access. |
O_RDWR | Flag indicating to open a file for read-write access. |
O_CREAT | Flag indicating to create the file if it does not already exist. |
O_EXCL | Flag indicating that opening a file should fail if the\n O_CREAT flag is set and the file already exists. |
O_NOCTTY | Flag indicating that if path identifies a terminal device, opening the\n path shall not cause that terminal to become the controlling terminal for\n the process (if the process does not already have one). |
O_TRUNC | Flag indicating that if the file exists and is a regular file, and the\n file is opened successfully for write access, its length shall be truncated\n to zero. |
O_APPEND | Flag indicating that data will be appended to the end of the file. |
O_DIRECTORY | Flag indicating that the open should fail if the path is not a\n directory. |
O_NOATIME | Flag indicating reading accesses to the file system will no longer\n result in an update to the atime information associated with\n the file. This flag is available on Linux operating systems only. |
O_NOFOLLOW | Flag indicating that the open should fail if the path is a symbolic\n link. |
O_SYNC | Flag indicating that the file is opened for synchronized I/O with write\n operations waiting for file integrity. |
O_DSYNC | Flag indicating that the file is opened for synchronized I/O with write\n operations waiting for data integrity. |
O_SYMLINK | Flag indicating to open the symbolic link itself rather than the\n resource it is pointing to. |
O_DIRECT | When set, an attempt will be made to minimize caching effects of file\n I/O. |
O_NONBLOCK | Flag indicating to open the file in nonblocking mode when possible. |
UV_FS_O_FILEMAP | When set, a memory file mapping is used to access the file. This flag\n is available on Windows operating systems only. On other operating systems,\n this flag is ignored. |
On Windows, only O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR,\nO_TRUNC, O_WRONLY, and UV_FS_O_FILEMAP are available.
The following constants are meant for use with the <fs.Stats> object's mode property for determining a file's type.
| Constant | Description |
|---|---|
S_IFMT | Bit mask used to extract the file type code. |
S_IFREG | File type constant for a regular file. |
S_IFDIR | File type constant for a directory. |
S_IFCHR | File type constant for a character-oriented device file. |
S_IFBLK | File type constant for a block-oriented device file. |
S_IFIFO | File type constant for a FIFO/pipe. |
S_IFLNK | File type constant for a symbolic link. |
S_IFSOCK | File type constant for a socket. |
On Windows, only S_IFCHR, S_IFDIR, S_IFLNK, S_IFMT, and S_IFREG,\nare available.
The following constants are meant for use with the <fs.Stats> object's mode property for determining the access permissions for a file.
| Constant | Description |
|---|---|
S_IRWXU | File mode indicating readable, writable, and executable by owner. |
S_IRUSR | File mode indicating readable by owner. |
S_IWUSR | File mode indicating writable by owner. |
S_IXUSR | File mode indicating executable by owner. |
S_IRWXG | File mode indicating readable, writable, and executable by group. |
S_IRGRP | File mode indicating readable by group. |
S_IWGRP | File mode indicating writable by group. |
S_IXGRP | File mode indicating executable by group. |
S_IRWXO | File mode indicating readable, writable, and executable by others. |
S_IROTH | File mode indicating readable by others. |
S_IWOTH | File mode indicating writable by others. |
S_IXOTH | File mode indicating executable by others. |
On Windows, only S_IRUSR and S_IWUSR are available.
Because they are executed asynchronously by the underlying thread pool,\nthere is no guaranteed ordering when using either the callback or\npromise-based methods.
\nFor example, the following is prone to error because the fs.stat()\noperation might complete before the fs.rename() operation:
const fs = require('node:fs');\n\nfs.rename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n console.log('renamed complete');\n});\nfs.stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n});\n\nIt is important to correctly order the operations by awaiting the results\nof one before invoking the other:
\nimport { rename, stat } from 'node:fs/promises';\n\nconst oldPath = '/tmp/hello';\nconst newPath = '/tmp/world';\n\ntry {\n await rename(oldPath, newPath);\n const stats = await stat(newPath);\n console.log(`stats: ${JSON.stringify(stats)}`);\n} catch (error) {\n console.error('there was an error:', error.message);\n}\n\nconst { rename, stat } = require('node:fs/promises');\n\n(async function(oldPath, newPath) {\n try {\n await rename(oldPath, newPath);\n const stats = await stat(newPath);\n console.log(`stats: ${JSON.stringify(stats)}`);\n } catch (error) {\n console.error('there was an error:', error.message);\n }\n})('/tmp/hello', '/tmp/world');\n\nOr, when using the callback APIs, move the fs.stat() call into the callback\nof the fs.rename() operation:
import { rename, stat } from 'node:fs';\n\nrename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n });\n});\n\nconst { rename, stat } = require('node:fs/promises');\n\nrename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n });\n});\n",
"displayName": "Ordering of callback and promise-based operations"
},
{
"textRaw": "File paths",
"name": "file_paths",
"type": "module",
"desc": "Most fs operations accept file paths that may be specified in the form of\na string, a <Buffer>, or a <URL> object using the file: protocol.
String paths are interpreted as UTF-8 character sequences identifying\nthe absolute or relative filename. Relative paths will be resolved relative\nto the current working directory as determined by calling process.cwd().
Example using an absolute path on POSIX:
\nimport { open } from 'node:fs/promises';\n\nlet fd;\ntry {\n fd = await open('/open/some/file.txt', 'r');\n // Do something with the file\n} finally {\n await fd?.close();\n}\n\nExample using a relative path on POSIX (relative to process.cwd()):
import { open } from 'node:fs/promises';\n\nlet fd;\ntry {\n fd = await open('file.txt', 'r');\n // Do something with the file\n} finally {\n await fd?.close();\n}\n",
"displayName": "String paths"
},
{
"textRaw": "File URL paths",
"name": "file_url_paths",
"type": "module",
"meta": {
"added": [
"v7.6.0"
],
"changes": []
},
"desc": "For most node:fs module functions, the path or filename argument may be\npassed as a <URL> object using the file: protocol.
import { readFileSync } from 'node:fs';\n\nreadFileSync(new URL('file:///tmp/hello'));\n\nfile: URLs are always absolute paths.
On Windows, file: <URL>s with a host name convert to UNC paths, while file: <URL>s with drive letters convert to local absolute paths. file: <URL>s\nwith no host name and no drive letter will result in an error:
import { readFileSync } from 'node:fs';\n// On Windows :\n\n// - WHATWG file URLs with hostname convert to UNC path\n// file://hostname/p/a/t/h/file => \\\\hostname\\p\\a\\t\\h\\file\nreadFileSync(new URL('file://hostname/p/a/t/h/file'));\n\n// - WHATWG file URLs with drive letters convert to absolute path\n// file:///C:/tmp/hello => C:\\tmp\\hello\nreadFileSync(new URL('file:///C:/tmp/hello'));\n\n// - WHATWG file URLs without hostname must have a drive letters\nreadFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));\nreadFileSync(new URL('file:///c/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute\n\nfile: <URL>s with drive letters must use : as a separator just after\nthe drive letter. Using another separator will result in an error.
On all other platforms, file: <URL>s with a host name are unsupported and\nwill result in an error:
import { readFileSync } from 'node:fs';\n// On other platforms:\n\n// - WHATWG file URLs with hostname are unsupported\n// file://hostname/p/a/t/h/file => throw!\nreadFileSync(new URL('file://hostname/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute\n\n// - WHATWG file URLs convert to absolute path\n// file:///tmp/hello => /tmp/hello\nreadFileSync(new URL('file:///tmp/hello'));\n\nA file: <URL> having encoded slash characters will result in an error on all\nplatforms:
import { readFileSync } from 'node:fs';\n\n// On Windows\nreadFileSync(new URL('file:///C:/p/a/t/h/%2F'));\nreadFileSync(new URL('file:///C:/p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n\n// On POSIX\nreadFileSync(new URL('file:///p/a/t/h/%2F'));\nreadFileSync(new URL('file:///p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n/ characters */\n\nOn Windows, file: <URL>s having encoded backslash will result in an error:
import { readFileSync } from 'node:fs';\n\n// On Windows\nreadFileSync(new URL('file:///C:/path/%5C'));\nreadFileSync(new URL('file:///C:/path/%5c'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n",
"displayName": "Platform-specific considerations"
}
],
"displayName": "File URL paths"
},
{
"textRaw": "Buffer paths",
"name": "buffer_paths",
"type": "module",
"desc": "Paths specified using a <Buffer> are useful primarily on certain POSIX\noperating systems that treat file paths as opaque byte sequences. On such\nsystems, it is possible for a single file path to contain sub-sequences that\nuse multiple character encodings. As with string paths, <Buffer> paths may\nbe relative or absolute:
Example using an absolute path on POSIX:
\nimport { open } from 'node:fs/promises';\nimport { Buffer } from 'node:buffer';\n\nlet fd;\ntry {\n fd = await open(Buffer.from('/open/some/file.txt'), 'r');\n // Do something with the file\n} finally {\n await fd?.close();\n}\n",
"displayName": "Buffer paths"
},
{
"textRaw": "Per-drive working directories on Windows",
"name": "per-drive_working_directories_on_windows",
"type": "module",
"desc": "On Windows, Node.js follows the concept of per-drive working directory. This\nbehavior can be observed when using a drive path without a backslash. For\nexample fs.readdirSync('C:\\\\') can potentially return a different result than\nfs.readdirSync('C:'). For more information, see\nthis MSDN page.
On POSIX systems, for every process, the kernel maintains a table of currently\nopen files and resources. Each open file is assigned a simple numeric\nidentifier called a file descriptor. At the system-level, all file system\noperations use these file descriptors to identify and track each specific\nfile. Windows systems use a different but conceptually similar mechanism for\ntracking resources. To simplify things for users, Node.js abstracts away the\ndifferences between operating systems and assigns all open files a numeric file\ndescriptor.
\nThe callback-based fs.open(), and synchronous fs.openSync() methods open a\nfile and allocate a new file descriptor. Once allocated, the file descriptor may\nbe used to read data from, write data to, or request information about the file.
Operating systems limit the number of file descriptors that may be open\nat any given time so it is critical to close the descriptor when operations\nare completed. Failure to do so will result in a memory leak that will\neventually cause an application to crash.
\nimport { open, close, fstat } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('/open/some/file.txt', 'r', (err, fd) => {\n if (err) throw err;\n try {\n fstat(fd, (err, stat) => {\n if (err) {\n closeFd(fd);\n throw err;\n }\n\n // use stat\n\n closeFd(fd);\n });\n } catch (err) {\n closeFd(fd);\n throw err;\n }\n});\n\nThe promise-based APIs use a <FileHandle> object in place of the numeric\nfile descriptor. These objects are better managed by the system to ensure\nthat resources are not leaked. However, it is still required that they are\nclosed when operations are completed:
import { open } from 'node:fs/promises';\n\nlet file;\ntry {\n file = await open('/open/some/file.txt', 'r');\n const stat = await file.stat();\n // use stat\n} finally {\n await file.close();\n}\n",
"displayName": "File descriptors"
},
{
"textRaw": "Threadpool usage",
"name": "threadpool_usage",
"type": "module",
"desc": "All callback and promise-based file system APIs (with the exception of\nfs.FSWatcher()) use libuv's threadpool. This can have surprising and negative\nperformance implications for some applications. See the\nUV_THREADPOOL_SIZE documentation for more information.
The following flags are available wherever the flag option takes a\nstring.
'a': Open file for appending.\nThe file is created if it does not exist.
'ax': Like 'a' but fails if the path exists.
'a+': Open file for reading and appending.\nThe file is created if it does not exist.
'ax+': Like 'a+' but fails if the path exists.
'as': Open file for appending in synchronous mode.\nThe file is created if it does not exist.
'as+': Open file for reading and appending in synchronous mode.\nThe file is created if it does not exist.
'r': Open file for reading.\nAn exception occurs if the file does not exist.
'rs': Open file for reading in synchronous mode.\nAn exception occurs if the file does not exist.
'r+': Open file for reading and writing.\nAn exception occurs if the file does not exist.
'rs+': Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts as it allows\nskipping the potentially stale local cache. It has a very real impact on\nI/O performance so using this flag is not recommended unless it is needed.
\nThis doesn't turn fs.open() or fsPromises.open() into a synchronous\nblocking call. If synchronous operation is desired, something like\nfs.openSync() should be used.
'w': Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx': Like 'w' but fails if the path exists.
'w+': Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx+': Like 'w+' but fails if the path exists.
flag can also be a number as documented by open(2); commonly used constants\nare available from fs.constants. On Windows, flags are translated to\ntheir equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE,\nor O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.
The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to\nreturn an error if the path already exists. On POSIX, if the path is a symbolic\nlink, using O_EXCL returns an error even if the link is to a path that does\nnot exist. The exclusive flag might not work with network file systems.
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
\nModifying a file rather than replacing it may require the flag option to be\nset to 'r+' rather than the default 'w'.
The behavior of some flags are platform-specific. As such, opening a directory\non macOS and Linux with the 'a+' flag, as in the example below, will return an\nerror. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle\nwill be returned.
// macOS and Linux\nfs.open('<directory>', 'a+', (err, fd) => {\n // => [Error: EISDIR: illegal operation on a directory, open <directory>]\n});\n\n// Windows and FreeBSD\nfs.open('<directory>', 'a+', (err, fd) => {\n // => null, <fd>\n});\n\nOn Windows, opening an existing hidden file using the 'w' flag (either\nthrough fs.open(), fs.writeFile(), or fsPromises.open()) will fail with\nEPERM. Existing hidden files can be opened for writing with the 'r+' flag.
A call to fs.ftruncate() or filehandle.truncate() can be used to reset\nthe file contents.
This module, containing both a client and server, can be imported via\nrequire('node:http') (CommonJS) or import * as http from 'node:http' (ES module).
The HTTP interfaces in Node.js are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses, so the\nuser is able to stream data.
\nHTTP message headers are represented by an object like this:
\n{ \"content-length\": \"123\",\n \"content-type\": \"text/plain\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.com\",\n \"accept\": \"*/*\" }\n\nKeys are lowercased. Values are not modified.
\nIn order to support the full spectrum of possible HTTP applications, the Node.js\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.
\nSee message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders\nproperty, which is an array of [key, value, key2, value2, ...]. For\nexample, the previous message header object might have a rawHeaders\nlist like the following:
[ 'ConTent-Length', '123456',\n 'content-LENGTH', '123',\n 'content-type', 'text/plain',\n 'CONNECTION', 'keep-alive',\n 'Host', 'example.com',\n 'accepT', '*/*' ]\n",
"classes": [
{
"textRaw": "Class: `http.Agent`",
"name": "http.Agent",
"type": "class",
"meta": {
"added": [
"v0.3.4"
],
"changes": []
},
"desc": "An Agent is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent will still make\nthe 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\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).
It is good practice, to destroy() an Agent instance when it is no\nlonger in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either\na 'close' event or an 'agentRemove' event. When intending to keep one\nHTTP request open for a long time without keeping it in the agent, something\nlike the following may be done:
http.get(options, (res) => {\n // Do stuff\n}).on('socket', (socket) => {\n socket.emit('agentRemove');\n});\n\nAn agent may also be used for an individual request. By providing\n{agent: false} as an option to the http.get() or http.request()\nfunctions, a one-time use Agent with default options will be used\nfor the client connection.
agent:false:
http.get({\n hostname: 'localhost',\n port: 80,\n path: '/',\n agent: false, // Create a new agent just for this one request\n}, (res) => {\n // Do stuff with response\n});\n",
"signatures": [
{
"textRaw": "`new Agent([options])`",
"name": "Agent",
"type": "ctor",
"meta": {
"added": [
"v0.3.4"
],
"changes": [
{
"version": [
"v24.7.0",
"v22.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/59315",
"description": "Add support for `agentKeepAliveTimeoutBuffer`."
},
{
"version": [
"v24.5.0"
],
"pr-url": "https://github.com/nodejs/node/pull/58980",
"description": "Add support for `proxyEnv`."
},
{
"version": [
"v24.5.0"
],
"pr-url": "https://github.com/nodejs/node/pull/58980",
"description": "Add support for `defaultPort` and `protocol`."
},
{
"version": [
"v15.6.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36685",
"description": "Change the default scheduling from 'fifo' to 'lifo'."
},
{
"version": [
"v14.5.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/33617",
"description": "Add `maxTotalSockets` option to agent constructor."
},
{
"version": [
"v14.5.0",
"v12.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/33278",
"description": "Add `scheduling` option to specify the free socket scheduling strategy."
}
]
},
"params": [
{
"textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the following fields:",
"name": "options",
"type": "Object",
"desc": "Set of configurable options to set on the agent. Can have the following fields:",
"options": [
{
"textRaw": "`keepAlive` {boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used. **Default:** `false`.",
"name": "keepAlive",
"type": "boolean",
"default": "`false`",
"desc": "Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the `keep-alive` value of the `Connection` header. The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`, in which case `Connection: close` will be used."
},
{
"textRaw": "`keepAliveMsecs` {number} When using the `keepAlive` option, specifies the initial delay for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. **Default:** `1000`.",
"name": "keepAliveMsecs",
"type": "number",
"default": "`1000`",
"desc": "When using the `keepAlive` option, specifies the initial delay for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`."
},
{
"textRaw": "`agentKeepAliveTimeoutBuffer` {number} Milliseconds to subtract from the server-provided `keep-alive: timeout=...` hint when determining socket expiration time. This buffer helps ensure the agent closes the socket slightly before the server does, reducing the chance of sending a request on a socket that’s about to be closed by the server. **Default:** `1000`.",
"name": "agentKeepAliveTimeoutBuffer",
"type": "number",
"default": "`1000`",
"desc": "Milliseconds to subtract from the server-provided `keep-alive: timeout=...` hint when determining socket expiration time. This buffer helps ensure the agent closes the socket slightly before the server does, reducing the chance of sending a request on a socket that’s about to be closed by the server."
},
{
"textRaw": "`maxSockets` {number} Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until the `maxSockets` value is reached. If the host attempts to open more connections than `maxSockets`, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at most `maxSockets` active connections at any point in time, from a given host. **Default:** `Infinity`.",
"name": "maxSockets",
"type": "number",
"default": "`Infinity`",
"desc": "Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until the `maxSockets` value is reached. If the host attempts to open more connections than `maxSockets`, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at most `maxSockets` active connections at any point in time, from a given host."
},
{
"textRaw": "`maxTotalSockets` {number} Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. **Default:** `Infinity`.",
"name": "maxTotalSockets",
"type": "number",
"default": "`Infinity`",
"desc": "Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached."
},
{
"textRaw": "`maxFreeSockets` {number} Maximum number of sockets per host to leave open in a free state. Only relevant if `keepAlive` is set to `true`. **Default:** `256`.",
"name": "maxFreeSockets",
"type": "number",
"default": "`256`",
"desc": "Maximum number of sockets per host to leave open in a free state. Only relevant if `keepAlive` is set to `true`."
},
{
"textRaw": "`scheduling` {string} Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible. **Default:** `'lifo'`.",
"name": "scheduling",
"type": "string",
"default": "`'lifo'`",
"desc": "Scheduling strategy to apply when picking the next free socket to use. It can be `'fifo'` or `'lifo'`. The main difference between the two scheduling strategies is that `'lifo'` selects the most recently used socket, while `'fifo'` selects the least recently used socket. In case of a low rate of request per second, the `'lifo'` scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the `'fifo'` scheduling will maximize the number of open sockets, while the `'lifo'` scheduling will keep it as low as possible."
},
{
"textRaw": "`timeout` {number} Socket timeout in milliseconds. This will set the timeout when the socket is created.",
"name": "timeout",
"type": "number",
"desc": "Socket timeout in milliseconds. This will set the timeout when the socket is created."
},
{
"textRaw": "`proxyEnv` {Object|undefined} Environment variables for proxy configuration. See Built-in Proxy Support for details. **Default:** `undefined`",
"name": "proxyEnv",
"type": "Object|undefined",
"default": "`undefined`",
"desc": "Environment variables for proxy configuration. See Built-in Proxy Support for details.",
"options": [
{
"textRaw": "`HTTP_PROXY` {string|undefined} URL for the proxy server that HTTP requests should use. If undefined, no proxy is used for HTTP requests.",
"name": "HTTP_PROXY",
"type": "string|undefined",
"desc": "URL for the proxy server that HTTP requests should use. If undefined, no proxy is used for HTTP requests."
},
{
"textRaw": "`HTTPS_PROXY` {string|undefined} URL for the proxy server that HTTPS requests should use. If undefined, no proxy is used for HTTPS requests.",
"name": "HTTPS_PROXY",
"type": "string|undefined",
"desc": "URL for the proxy server that HTTPS requests should use. If undefined, no proxy is used for HTTPS requests."
},
{
"textRaw": "`NO_PROXY` {string|undefined} Patterns specifying the endpoints that should not be routed through a proxy.",
"name": "NO_PROXY",
"type": "string|undefined",
"desc": "Patterns specifying the endpoints that should not be routed through a proxy."
},
{
"textRaw": "`http_proxy` {string|undefined} Same as `HTTP_PROXY`. If both are set, `http_proxy` takes precedence.",
"name": "http_proxy",
"type": "string|undefined",
"desc": "Same as `HTTP_PROXY`. If both are set, `http_proxy` takes precedence."
},
{
"textRaw": "`https_proxy` {string|undefined} Same as `HTTPS_PROXY`. If both are set, `https_proxy` takes precedence.",
"name": "https_proxy",
"type": "string|undefined",
"desc": "Same as `HTTPS_PROXY`. If both are set, `https_proxy` takes precedence."
},
{
"textRaw": "`no_proxy` {string|undefined} Same as `NO_PROXY`. If both are set, `no_proxy` takes precedence.",
"name": "no_proxy",
"type": "string|undefined",
"desc": "Same as `NO_PROXY`. If both are set, `no_proxy` takes precedence."
}
]
},
{
"textRaw": "`defaultPort` {number} Default port to use when the port is not specified in requests. **Default:** `80`.",
"name": "defaultPort",
"type": "number",
"default": "`80`",
"desc": "Default port to use when the port is not specified in requests."
},
{
"textRaw": "`protocol` {string} The protocol to use for the agent. **Default:** `'http:'`.",
"name": "protocol",
"type": "string",
"default": "`'http:'`",
"desc": "The protocol to use for the agent."
}
],
"optional": true
}
],
"desc": "options in socket.connect() are also supported.
To configure any of them, a custom http.Agent instance must be created.
import { Agent, request } from 'node:http';\nconst keepAliveAgent = new Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nrequest(options, onResponseCallback);\n\nconst http = require('node:http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n"
}
],
"methods": [
{
"textRaw": "`agent.createConnection(options[, callback])`",
"name": "createConnection",
"type": "method",
"meta": {
"added": [
"v0.11.4"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} Options containing connection details. Check `net.createConnection()` for the format of the options. For custom agents, this object is passed to the custom `createConnection` function.",
"name": "options",
"type": "Object",
"desc": "Options containing connection details. Check `net.createConnection()` for the format of the options. For custom agents, this object is passed to the custom `createConnection` function."
},
{
"textRaw": "`callback` {Function} (Optional, primarily for custom agents) A function to be called by a custom `createConnection` implementation when the socket is created, especially for asynchronous operations.",
"name": "callback",
"type": "Function",
"desc": "(Optional, primarily for custom agents) A function to be called by a custom `createConnection` implementation when the socket is created, especially for asynchronous operations.",
"options": [
{
"textRaw": "`err` {Error|null} An error object if socket creation failed.",
"name": "err",
"type": "Error|null",
"desc": "An error object if socket creation failed."
},
{
"textRaw": "`socket` {stream.Duplex} The created socket.",
"name": "socket",
"type": "stream.Duplex",
"desc": "The created socket."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Duplex} The created socket. This is returned by the default implementation or by a custom synchronous `createConnection` implementation. If a custom `createConnection` uses the `callback` for asynchronous operation, this return value might not be the primary way to obtain the socket.",
"name": "return",
"type": "stream.Duplex",
"desc": "The created socket. This is returned by the default implementation or by a custom synchronous `createConnection` implementation. If a custom `createConnection` uses the `callback` for asynchronous operation, this return value might not be the primary way to obtain the socket."
}
}
],
"desc": "Produces a socket/stream to be used for HTTP requests.
\nBy default, this function behaves identically to net.createConnection(),\nsynchronously returning the created socket. The optional callback parameter in the\nsignature is not used by this default implementation.
However, custom agents may override this method to provide greater flexibility,\nfor example, to create sockets asynchronously. When overriding createConnection:
callback\nand pass the created socket/stream to it (e.g., callback(null, newSocket)).\nIf an error occurs during socket creation, it should be passed as the first\nargument to the callback (e.g., callback(err)).The agent will call the provided createConnection function with options and\nthis internal callback. The callback provided by the agent has a signature\nof (err, stream).
Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:
socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n\nThis method can be overridden by a particular Agent subclass. If this\nmethod returns a falsy value, the socket will be destroyed instead of persisting\nit for use with the next request.
The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.
Called when socket is attached to request after being persisted because of\nthe keep-alive options. Default behavior is to:
socket.ref();\n\nThis method can be overridden by a particular Agent subclass.
The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.
Destroy any sockets that are currently in use by the agent.
\nIt is usually not necessary to do this. However, if using an\nagent with keepAlive enabled, then it is best to explicitly shut down\nthe agent when it is no longer needed. Otherwise,\nsockets might stay open for quite a long time before the server\nterminates them.
Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress or host:port:localAddress:family. For an HTTPS agent,\nthe name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options\nthat determine socket reusability.
An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and\nremoved from the array on 'timeout'.
By default set to 256. For agents with keepAlive enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is the returned value of agent.getName().
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open. Unlike maxSockets, this parameter applies across all origins.
An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.
" }, { "textRaw": "Type: {Object}", "name": "sockets", "type": "Object", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36409", "description": "The property now has a `null` prototype." } ] }, "desc": "An object which contains arrays of sockets currently in use by the\nagent. Do not modify.
" } ] }, { "textRaw": "Class: `http.ClientRequest`", "name": "http.ClientRequest", "type": "class", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "<http.OutgoingMessage>This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value),\ngetHeader(name), removeHeader(name) API. The actual header will\nbe 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.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.IncomingMessage.
During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.
If no 'response' handler is added, then the response will be\nentirely discarded. However, if a 'response' event handler is added,\nthen the data from the response object must be consumed, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.
For backward compatibility, res will only emit 'error' if there is an\n'error' listener registered.
Set Content-Length header to limit the response body size.\nIf response.strictContentLength is set to true, mismatching the\nContent-Length header value will result in an Error being thrown,\nidentified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Content-Length value should be in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes.
Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().
Indicates that the request is completed, or its underlying connection was\nterminated prematurely (before the response completion).
" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`response` {http.IncomingMessage}", "name": "response", "type": "http.IncomingMessage" }, { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" }, { "textRaw": "`head` {Buffer}", "name": "head", "type": "Buffer" } ], "desc": "Emitted each time a server responds to a request with a CONNECT method. If\nthis event is not being listened for, clients receiving a CONNECT method will\nhave their connections closed.
This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
A client and server pair demonstrating how to listen for the 'connect' event:
import { createServer, request } from 'node:http';\nimport { connect } from 'node:net';\nimport { URL } from 'node:url';\n\n// Create an HTTP tunneling proxy\nconst proxy = createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n // Connect to an origin server\n const { port, hostname } = new URL(`http://${req.url}`);\n const serverSocket = connect(port || 80, hostname, () => {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n 'Proxy-agent: Node.js-Proxy\\r\\n' +\n '\\r\\n');\n serverSocket.write(head);\n serverSocket.pipe(clientSocket);\n clientSocket.pipe(serverSocket);\n });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n // Make a request to a tunneling proxy\n const options = {\n port: 1337,\n host: '127.0.0.1',\n method: 'CONNECT',\n path: 'www.google.com:80',\n };\n\n const req = request(options);\n req.end();\n\n req.on('connect', (res, socket, head) => {\n console.log('got connected!');\n\n // Make a request over an HTTP tunnel\n socket.write('GET / HTTP/1.1\\r\\n' +\n 'Host: www.google.com:80\\r\\n' +\n 'Connection: close\\r\\n' +\n '\\r\\n');\n socket.on('data', (chunk) => {\n console.log(chunk.toString());\n });\n socket.on('end', () => {\n proxy.close();\n });\n });\n});\n\nconst http = require('node:http');\nconst net = require('node:net');\nconst { URL } = require('node:url');\n\n// Create an HTTP tunneling proxy\nconst proxy = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n // Connect to an origin server\n const { port, hostname } = new URL(`http://${req.url}`);\n const serverSocket = net.connect(port || 80, hostname, () => {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n 'Proxy-agent: Node.js-Proxy\\r\\n' +\n '\\r\\n');\n serverSocket.write(head);\n serverSocket.pipe(clientSocket);\n clientSocket.pipe(serverSocket);\n });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n // Make a request to a tunneling proxy\n const options = {\n port: 1337,\n host: '127.0.0.1',\n method: 'CONNECT',\n path: 'www.google.com:80',\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('connect', (res, socket, head) => {\n console.log('got connected!');\n\n // Make a request over an HTTP tunnel\n socket.write('GET / HTTP/1.1\\r\\n' +\n 'Host: www.google.com:80\\r\\n' +\n 'Connection: close\\r\\n' +\n '\\r\\n');\n socket.on('data', (chunk) => {\n console.log(chunk.toString());\n });\n socket.on('end', () => {\n proxy.close();\n });\n });\n});\n"
},
{
"textRaw": "Event: `'continue'`",
"name": "continue",
"type": "event",
"meta": {
"added": [
"v0.3.2"
],
"changes": []
},
"params": [],
"desc": "Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "params": [], "desc": "Emitted when the request has been sent. More specifically, this event is emitted\nwhen the last segment of the request headers and body have been handed off to\nthe operating system for transmission over the network. It does not imply that\nthe server has received anything yet.
" }, { "textRaw": "Event: `'information'`", "name": "information", "type": "event", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "params": [ { "textRaw": "`info` {Object}", "name": "info", "type": "Object", "options": [ { "textRaw": "`httpVersion` {string}", "name": "httpVersion", "type": "string" }, { "textRaw": "`httpVersionMajor` {integer}", "name": "httpVersionMajor", "type": "integer" }, { "textRaw": "`httpVersionMinor` {integer}", "name": "httpVersionMinor", "type": "integer" }, { "textRaw": "`statusCode` {integer}", "name": "statusCode", "type": "integer" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string" }, { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" }, { "textRaw": "`rawHeaders` {string[]}", "name": "rawHeaders", "type": "string[]" } ] } ], "desc": "Emitted when the server sends a 1xx intermediate response (excluding 101\nUpgrade). The listeners of this event will receive an object containing the\nHTTP version, status code, status message, key-value headers object,\nand array with the raw header names followed by their respective values.
\nimport { request } from 'node:http';\n\nconst options = {\n host: '127.0.0.1',\n port: 8080,\n path: '/length_request',\n};\n\n// Make a request\nconst req = request(options);\nreq.end();\n\nreq.on('information', (info) => {\n console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n\nconst http = require('node:http');\n\nconst options = {\n host: '127.0.0.1',\n port: 8080,\n path: '/length_request',\n};\n\n// Make a request\nconst req = http.request(options);\nreq.end();\n\nreq.on('information', (info) => {\n console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n\n101 Upgrade statuses do not fire this event due to their break from the\ntraditional HTTP request/response chain, such as web sockets, in-place TLS\nupgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the\n'upgrade' event instead.
Emitted when a response is received to this request. This event is emitted only\nonce.
" }, { "textRaw": "Event: `'socket'`", "name": "socket", "type": "event", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be destroyed manually.
\nSee also: request.setTimeout().
Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for and the response status code is 101 Switching\nProtocols, clients receiving an upgrade header will have their connections\nclosed.
\nThis event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
A client server pair demonstrating how to listen for the 'upgrade' event.
import http from 'node:http';\nimport process from 'node:process';\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nserver.on('upgrade', (req, socket, head) => {\n socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n '\\r\\n');\n\n socket.pipe(socket); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n // make a request\n const options = {\n port: 1337,\n host: '127.0.0.1',\n headers: {\n 'Connection': 'Upgrade',\n 'Upgrade': 'websocket',\n },\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('upgrade', (res, socket, upgradeHead) => {\n console.log('got upgraded!');\n socket.end();\n process.exit(0);\n });\n});\n\nconst http = require('node:http');\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nserver.on('upgrade', (req, socket, head) => {\n socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n '\\r\\n');\n\n socket.pipe(socket); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n // make a request\n const options = {\n port: 1337,\n host: '127.0.0.1',\n headers: {\n 'Connection': 'Upgrade',\n 'Upgrade': 'websocket',\n },\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('upgrade', (res, socket, upgradeHead) => {\n console.log('got upgraded!');\n socket.end();\n process.exit(0);\n });\n});\n"
}
],
"methods": [
{
"textRaw": "`request.abort()`",
"name": "abort",
"type": "method",
"meta": {
"added": [
"v0.3.8"
],
"changes": [],
"deprecated": [
"v14.1.0",
"v13.14.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use `request.destroy()` instead.",
"signatures": [
{
"params": []
}
],
"desc": "Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.
" }, { "textRaw": "`request.cork()`", "name": "cork", "type": "method", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "See writable.cork().
Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.
If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end(callback).
If callback is specified, it will be called when the request stream\nis finished.
Destroy the request. Optionally emit an 'error' event,\nand emit a 'close' event. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.
See writable.destroy() for further details.
Is true after request.destroy() has been called.
See writable.destroyed for further details.
Flushes the request headers.
\nFor efficiency reasons, Node.js normally buffers the request headers until\nrequest.end() is called or the first chunk of request data is written. It\nthen tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. request.flushHeaders() bypasses\nthe optimization and kickstarts the request.
Reads out a header on the request. The name is case-insensitive.\nThe type of the return value depends on the arguments provided to\nrequest.setHeader().
request.setHeader('content-type', 'text/html');\nrequest.setHeader('Content-Length', Buffer.byteLength(body));\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = request.getHeader('Content-Type');\n// 'contentType' is 'text/html'\nconst contentLength = request.getHeader('Content-Length');\n// 'contentLength' is of type number\nconst cookie = request.getHeader('Cookie');\n// 'cookie' is of type string[]\n"
},
{
"textRaw": "`request.getHeaderNames()`",
"name": "getHeaderNames",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nrequest.setHeader('Foo', 'bar');\nrequest.setHeader('Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = request.getHeaderNames();\n// headerNames === ['foo', 'cookie']\n"
},
{
"textRaw": "`request.getHeaders()`",
"name": "getHeaders",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the request.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
request.setHeader('Foo', 'bar');\nrequest.setHeader('Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = request.getHeaders();\n// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`request.getRawHeaderNames()`",
"name": "getRawHeaderNames",
"type": "method",
"meta": {
"added": [
"v15.13.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing raw\nheaders. Header names are returned with their exact casing being set.
\nrequest.setHeader('Foo', 'bar');\nrequest.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = request.getRawHeaderNames();\n// headerNames === ['Foo', 'Set-Cookie']\n"
},
{
"textRaw": "`request.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
const hasContentType = request.hasHeader('content-type');\n"
},
{
"textRaw": "`request.removeHeader(name)`",
"name": "removeHeader",
"type": "method",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Removes a header that's already defined into headers object.
\nrequest.removeHeader('Content-Type');\n"
},
{
"textRaw": "`request.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Sets a single header value for headers object. If this header already exists in\nthe to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, request.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.
request.setHeader('Content-Type', 'application/json');\n\nor
\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\n\nWhen the value is a string an exception will be thrown if it contains\ncharacters outside the latin1 encoding.
If you need to pass UTF-8 characters in the value please encode the value\nusing the RFC 8187 standard.
\nconst filename = 'Rock 🎵.txt';\nrequest.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`);\n"
},
{
"textRaw": "`request.setNoDelay([noDelay])`",
"name": "setNoDelay",
"type": "method",
"meta": {
"added": [
"v0.5.9"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`noDelay` {boolean}",
"name": "noDelay",
"type": "boolean",
"optional": true
}
]
}
],
"desc": "Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.
Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.
Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.
See writable.uncork().
Sends a chunk of the body. This method can be called multiple times. If no\nContent-Length is set, data will automatically be encoded in HTTP Chunked\ntransfer encoding, so that server knows when the data ends. The\nTransfer-Encoding: chunked header is added. Calling request.end()\nis necessary to finish sending the request.
The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.
The callback argument is optional and will be called when this chunk of data\nis flushed, but only if the chunk is non-empty.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
When write function is called with empty string or buffer, it does\nnothing and waits for more input.
The request.aborted property will be true if the request has\nbeen aborted.
See request.socket.
The request.finished property will be true if request.end()\nhas been called. request.end() will automatically be called if the\nrequest was initiated via http.get().
Limits maximum response headers count. If set to 0, no limit will be applied.
" }, { "textRaw": "Type: {string} The request path.", "name": "path", "type": "string", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "The request path." }, { "textRaw": "Type: {string} The request method.", "name": "method", "type": "string", "meta": { "added": [ "v0.1.97" ], "changes": [] }, "desc": "The request method." }, { "textRaw": "Type: {string} The request host.", "name": "host", "type": "string", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request host." }, { "textRaw": "Type: {string} The request protocol.", "name": "protocol", "type": "string", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request protocol." }, { "textRaw": "Type: {boolean} Whether the request is send through a reused socket.", "name": "reusedSocket", "type": "boolean", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "desc": "When sending request through a keep-alive enabled agent, the underlying socket\nmight be reused. But if server closes connection at unfortunate time, client\nmay run into a 'ECONNRESET' error.
\nimport http from 'node:http';\nconst agent = new http.Agent({ keepAlive: true });\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n .createServer((req, res) => {\n res.write('hello\\n');\n res.end();\n })\n .listen(3000);\n\nsetInterval(() => {\n // Adapting a keep-alive agent\n http.get('http://localhost:3000', { agent }, (res) => {\n res.on('data', (data) => {\n // Do nothing\n });\n });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n\nconst http = require('node:http');\nconst agent = new http.Agent({ keepAlive: true });\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n .createServer((req, res) => {\n res.write('hello\\n');\n res.end();\n })\n .listen(3000);\n\nsetInterval(() => {\n // Adapting a keep-alive agent\n http.get('http://localhost:3000', { agent }, (res) => {\n res.on('data', (data) => {\n // Do nothing\n });\n });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n\nBy marking a request whether it reused socket or not, we can do\nautomatic error retry base on it.
\nimport http from 'node:http';\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n const req = http\n .get('http://localhost:3000', { agent }, (res) => {\n // ...\n })\n .on('error', (err) => {\n // Check if retry is needed\n if (req.reusedSocket && err.code === 'ECONNRESET') {\n retriableRequest();\n }\n });\n}\n\nretriableRequest();\n\nconst http = require('node:http');\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n const req = http\n .get('http://localhost:3000', { agent }, (res) => {\n // ...\n })\n .on('error', (err) => {\n // Check if retry is needed\n if (req.reusedSocket && err.code === 'ECONNRESET') {\n retriableRequest();\n }\n });\n}\n\nretriableRequest();\n",
"shortDesc": "Whether the request is send through a reused socket."
},
{
"textRaw": "Type: {stream.Duplex}",
"name": "socket",
"type": "stream.Duplex",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"desc": "Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket.
import http from 'node:http';\nconst options = {\n host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n const ip = req.socket.localAddress;\n const port = req.socket.localPort;\n console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n // Consume response object\n});\n\nconst http = require('node:http');\nconst options = {\n host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n const ip = req.socket.localAddress;\n const port = req.socket.localPort;\n console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n // Consume response object\n});\n\nThis property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.
Is true after request.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nrequest.writableFinished instead.
Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.
<net.Server>Emitted each time a request with an HTTP Expect: 100-continue is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue as appropriate.
Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
Emitted each time a request with an HTTP Expect header is received, where the\nvalue is not 100-continue. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
If a client connection emits an 'error' event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with a\ncustom HTTP response instead of abruptly severing the connection. The socket\nmust be closed or destroyed before the listener ends.
This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
Default behavior is to try close the socket with a HTTP '400 Bad Request',\nor a HTTP '431 Request Header Fields Too Large' in the case of a\nHPE_HEADER_OVERFLOW error. If the socket is not writable or headers\nof the current attached http.ServerResponse has been sent, it is\nimmediately destroyed.
socket is the net.Socket object that the error originated from.
import http from 'node:http';\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n\nconst http = require('node:http');\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n\nWhen the 'clientError' event occurs, there is no request or response\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket object. Care must be taken to\nensure the response is a properly formatted HTTP response message.
err is an instance of Error with two extra columns:
bytesParsed: the bytes count of request packet that Node.js may have parsed\ncorrectly;rawPacket: the raw packet of current request.In some cases, the client has already received the response and/or the socket\nhas already been destroyed, like in case of ECONNRESET errors. Before\ntrying to send data to the socket, it is better to check that it is still\nwritable.
server.on('clientError', (err, socket) => {\n if (err.code === 'ECONNRESET' || !socket.writable) {\n return;\n }\n\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n"
},
{
"textRaw": "Event: `'close'`",
"name": "close",
"type": "event",
"meta": {
"added": [
"v0.1.4"
],
"changes": []
},
"params": [],
"desc": "Emitted when the server closes.
" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the `'request'` event", "name": "request", "type": "http.IncomingMessage", "desc": "Arguments for the HTTP request, as it is in the `'request'` event" }, { "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", "name": "socket", "type": "stream.Duplex", "desc": "Network socket between the server and client" }, { "textRaw": "`head` {Buffer} The first packet of the tunneling stream (may be empty)", "name": "head", "type": "Buffer", "desc": "The first packet of the tunneling stream (may be empty)" } ], "desc": "Emitted each time a client requests an HTTP CONNECT method. If this event is\nnot listened for, then clients requesting a CONNECT method will have their\nconnections closed.
This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.
This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket can\nalso be accessed at request.socket.
This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.
If socket.setTimeout() is called here, the timeout will be replaced with\nserver.keepAliveTimeout when the socket has served a request (if\nserver.keepAliveTimeout is non-zero).
This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
When the number of requests on a socket reaches the threshold of\nserver.maxRequestsPerSocket, the server will drop new requests\nand emit 'dropRequest' event instead, then send 503 to client.
Emitted each time there is a request. There may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).
" }, { "textRaw": "Event: `'upgrade'`", "name": "upgrade", "type": "event", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v24.9.0", "pr-url": "https://github.com/nodejs/node/pull/59824", "description": "Whether this event is fired can now be controlled by the `shouldUpgradeCallback` and sockets will be destroyed if upgraded while no event handler is listening." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19981", "description": "Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header." } ] }, "params": [ { "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the `'request'` event", "name": "request", "type": "http.IncomingMessage", "desc": "Arguments for the HTTP request, as it is in the `'request'` event" }, { "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", "name": "socket", "type": "stream.Duplex", "desc": "Network socket between the server and client" }, { "textRaw": "`head` {Buffer} The first packet of the upgraded stream (may be empty)", "name": "head", "type": "Buffer", "desc": "The first packet of the upgraded stream (may be empty)" } ], "desc": "Emitted each time a client's HTTP upgrade request is accepted. By default\nall HTTP upgrade requests are ignored (i.e. only regular 'request' events\nare emitted, sticking with the normal HTTP request/response flow) unless you\nlisten to this event, in which case they are all accepted (i.e. the 'upgrade'\nevent is emitted instead, and future communication must handled directly\nthrough the raw socket). You can control this more precisely by using the\nserver shouldUpgradeCallback option.
Listening to this event is optional and clients cannot insist on a protocol\nchange.
\nAfter this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.
If an upgrade is accepted by shouldUpgradeCallback but no event handler\nis registered then the socket is destroyed, resulting in an immediate\nconnection closure for the client.
This event is guaranteed to be passed an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.
Stops the server from accepting new connections and closes all connections\nconnected to this server which are not sending a request or waiting for\na response.\nSee net.Server.close().
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n}, 10000);\n"
},
{
"textRaw": "`server.closeAllConnections()`",
"name": "closeAllConnections",
"type": "method",
"meta": {
"added": [
"v18.2.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes all established HTTP(S) connections connected to this server, including\nactive connections connected to this server which are sending a request or\nwaiting for a response. This does not destroy sockets upgraded to a different\nprotocol, such as WebSocket or HTTP/2.
\n\n\nThis is a forceful way of closing all connections and should be used with\ncaution. Whenever using this in conjunction with
\nserver.close, calling this\nafterserver.closeis recommended as to avoid race conditions where new\nconnections are created between a call to this and a call toserver.close.
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n // Closes all connections, ensuring the server closes successfully\n server.closeAllConnections();\n}, 10000);\n"
},
{
"textRaw": "`server.closeIdleConnections()`",
"name": "closeIdleConnections",
"type": "method",
"meta": {
"added": [
"v18.2.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes all connections connected to this server which are not sending a request\nor waiting for a response.
\n\n\nStarting with Node.js 19.0.0, there's no need for calling this method in\nconjunction with
\nserver.closeto reapkeep-aliveconnections. Using it\nwon't cause any harm though, and it can be useful to ensure backwards\ncompatibility for libraries and applications that need to support versions\nolder than 19.0.0. Whenever using this in conjunction withserver.close,\ncalling this afterserver.closeis recommended as to avoid race\nconditions where new connections are created between a call to this and a\ncall toserver.close.
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n // Closes idle connections, such as keep-alive connections. Server will close\n // once remaining active connections are terminated\n server.closeIdleConnections();\n}, 10000);\n"
},
{
"textRaw": "`server.listen()`",
"name": "listen",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "Starts the HTTP server listening for connections.\nThis method is identical to server.listen() from net.Server.
Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.
If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback\nis assigned to the Server's 'timeout' event, timeouts must be handled\nexplicitly.
Calls server.close() and returns a promise that fulfills when the\nserver has closed.
Limit the amount of time the parser will wait to receive the complete HTTP\nheaders.
\nIf the timeout expires, the server responds with status 408 without\nforwarding the request to the request listener and then closes the connection.
\nIt must be set to a non-zero value (e.g. 120 seconds) to protect against\npotential Denial-of-Service attacks in case the server is deployed without a\nreverse proxy in front.
" }, { "textRaw": "Type: {boolean} Indicates whether or not the server is listening for connections.", "name": "listening", "type": "boolean", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Indicates whether or not the server is listening for connections." }, { "textRaw": "Type: {number} **Default:** `2000`", "name": "maxHeadersCount", "type": "number", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "default": "`2000`", "desc": "Limits maximum incoming headers count. If set to 0, no limit will be applied.
" }, { "textRaw": "Type: {number} **Default:** `300000`", "name": "requestTimeout", "type": "number", "meta": { "added": [ "v14.11.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41263", "description": "The default request timeout changed from no timeout to 300s (5 minutes)." } ] }, "default": "`300000`", "desc": "Sets the timeout value in milliseconds for receiving the entire request from\nthe client.
\nIf the timeout expires, the server responds with status 408 without\nforwarding the request to the request listener and then closes the connection.
\nIt must be set to a non-zero value (e.g. 120 seconds) to protect against\npotential Denial-of-Service attacks in case the server is deployed without a\nreverse proxy in front.
" }, { "textRaw": "Type: {number} Requests per socket. **Default:** 0 (no limit)", "name": "maxRequestsPerSocket", "type": "number", "meta": { "added": [ "v16.10.0" ], "changes": [] }, "default": "0 (no limit)", "desc": "The maximum number of requests socket can handle\nbefore closing keep alive connection.
\nA value of 0 will disable the limit.
When the limit is reached it will set the Connection header value to close,\nbut will not actually close the connection, subsequent requests sent\nafter the limit is reached will get 503 Service Unavailable as a response.
The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nA value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." }, { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).", "name": "keepAliveTimeout", "type": "number", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "default": "`5000` (5 seconds)", "desc": "The number of milliseconds of inactivity a server needs to wait for additional\nincoming data, after it has finished writing the last response, before a socket\nwill be destroyed.
\nThis timeout value is combined with the\nserver.keepAliveTimeoutBuffer option to determine the actual socket\ntimeout, calculated as:\nsocketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer\nIf the server receives new data before the keep-alive timeout has fired, it\nwill reset the regular inactivity timeout, i.e., server.timeout.
A value of 0 will disable the keep-alive timeout behavior on incoming\nconnections.\nA value of 0 makes the HTTP server behave similarly to Node.js versions prior\nto 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only\naffects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." }, { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** `1000` (1 second).", "name": "keepAliveTimeoutBuffer", "type": "number", "meta": { "added": [ "v24.6.0", "v22.19.0" ], "changes": [] }, "default": "`1000` (1 second)", "desc": "An additional buffer time added to the\nserver.keepAliveTimeout to extend the internal socket timeout.
This buffer helps reduce connection reset (ECONNRESET) errors by increasing\nthe socket timeout slightly beyond the advertised keep-alive timeout.
This option applies only to new incoming connections.
", "shortDesc": "Timeout in milliseconds." } ] }, { "textRaw": "Class: `http.ServerResponse`", "name": "http.ServerResponse", "type": "class", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "<http.OutgoingMessage>This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.
Indicates that the response is completed, or its underlying connection was\nterminated prematurely (before the response completion).
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "params": [], "desc": "Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.
" } ], "methods": [ { "textRaw": "`response.addTrailers(headers)`", "name": "addTrailers", "type": "method", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nTrailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.
\nHTTP requires the Trailer header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,
response.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
See writable.cork().
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.
If data is specified, it is similar in effect to calling\nresponse.write(data, encoding) followed by response.end(callback).
If callback is specified, it will be called when the response stream\nis finished.
Flushes the response headers. See also: request.flushHeaders().
Reads out a header that's already been queued but not sent to the client.\nThe name is case-insensitive. The type of the return value depends\non the arguments provided to response.setHeader().
response.setHeader('Content-Type', 'text/html');\nresponse.setHeader('Content-Length', Buffer.byteLength(body));\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = response.getHeader('content-type');\n// contentType is 'text/html'\nconst contentLength = response.getHeader('Content-Length');\n// contentLength is of type number\nconst setCookie = response.getHeader('set-cookie');\n// setCookie is of type string[]\n"
},
{
"textRaw": "`response.getHeaderNames()`",
"name": "getHeaderNames",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n"
},
{
"textRaw": "`response.getHeaders()`",
"name": "getHeaders",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`response.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
const hasContentType = response.hasHeader('content-type');\n"
},
{
"textRaw": "`response.removeHeader(name)`",
"name": "removeHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Removes a header that's queued for implicit sending.
\nresponse.removeHeader('Content-Encoding');\n"
},
{
"textRaw": "`response.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {number|string|string[]}",
"name": "value",
"type": "number|string|string[]"
}
],
"return": {
"textRaw": "Returns: {http.ServerResponse}",
"name": "return",
"type": "http.ServerResponse"
}
}
],
"desc": "Returns the response object.
\nSets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, response.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission. The same response object is returned to the caller,\nto enable call chaining.
response.setHeader('Content-Type', 'text/html');\n\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n\nIf response.writeHead() method is called and this method has not been\ncalled, it will directly write the supplied header values onto the network\nchannel without caching internally, and the response.getHeader() on the\nheader will not yield the expected result. If progressive population of headers\nis desired with potential future retrieval and modification, use\nresponse.setHeader() instead of response.writeHead().
Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.
If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If a handler is\nassigned to the request, the response, or the server's 'timeout' events,\ntimed out sockets must be handled explicitly.
See writable.uncork().
If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nIf rejectNonStandardBodyWrites is set to true in createServer\nthen writing to the body is not allowed when the request method or response\nstatus do not support content. If an attempt is made to write to the body for a\nHEAD request or as part of a 204 or 304response, a synchronous Error\nwith the code ERR_HTTP_BODY_NOT_ALLOWED is thrown.
chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\ncallback will be called when this chunk of data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.
\nThe first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
Sends an HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue' event on\nServer.
Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,\nindicating that the user agent can preload/preconnect the linked resources.\nThe hints is an object containing the values of headers to be sent with\nearly hints message. The optional callback argument will be called when\nthe response message has been written.
Example
\nconst earlyHintsLink = '</styles.css>; rel=preload; as=style';\nresponse.writeEarlyHints({\n 'link': earlyHintsLink,\n});\n\nconst earlyHintsLinks = [\n '</styles.css>; rel=preload; as=style',\n '</scripts.js>; rel=preload; as=script',\n];\nresponse.writeEarlyHints({\n 'link': earlyHintsLinks,\n 'x-trace-id': 'id for diagnostics',\n});\n\nconst earlyHintsCallback = () => console.log('early hints message sent');\nresponse.writeEarlyHints({\n 'link': earlyHintsLinks,\n}, earlyHintsCallback);\n"
},
{
"textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`",
"name": "writeHead",
"type": "method",
"meta": {
"added": [
"v0.1.30"
],
"changes": [
{
"version": "v14.14.0",
"pr-url": "https://github.com/nodejs/node/pull/35274",
"description": "Allow passing headers as an array."
},
{
"version": [
"v11.10.0",
"v10.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/25974",
"description": "Return `this` from `writeHead()` to allow chaining with `end()`."
},
{
"version": [
"v5.11.0",
"v4.4.5"
],
"pr-url": "https://github.com/nodejs/node/pull/6291",
"description": "A `RangeError` is thrown if `statusCode` is not a number in the range `[100, 999]`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`statusCode` {number}",
"name": "statusCode",
"type": "number"
},
{
"textRaw": "`statusMessage` {string}",
"name": "statusMessage",
"type": "string",
"optional": true
},
{
"textRaw": "`headers` {Object|Array}",
"name": "headers",
"type": "Object|Array",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ServerResponse}",
"name": "return",
"type": "http.ServerResponse"
}
}
],
"desc": "Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable statusMessage as the second\nargument.
headers may be an Array where the keys and values are in the same list.\nIt is not a list of tuples. So, the even-numbered offsets are key values,\nand the odd-numbered offsets are the associated values. The array is in the same\nformat as request.rawHeaders.
Returns a reference to the ServerResponse, so that calls can be chained.
const body = 'hello world';\nresponse\n .writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain',\n })\n .end(body);\n\nThis method must only be called once on a message and it must\nbe called before response.end() is called.
If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
If this method is called and response.setHeader() has not been called,\nit will directly write the supplied header values onto the network channel\nwithout caching internally, and the response.getHeader() on the header\nwill not yield the expected result. If progressive population of headers is\ndesired with potential future retrieval and modification, use\nresponse.setHeader() instead.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n\nContent-Length is read in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes. Node.js\nwill check whether Content-Length and the length of the body which has\nbeen transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
Sends a HTTP/1.1 102 Processing message to the client, indicating that\nthe request body should be sent.
" } ], "properties": [ { "textRaw": "Type: {stream.Duplex}", "name": "connection", "type": "stream.Duplex", "meta": { "added": [ "v0.3.0" ], "changes": [], "deprecated": [ "v13.0.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `response.socket`.", "desc": "See response.socket.
The response.finished property will be true if response.end()\nhas been called.
Boolean (read-only). True if headers were sent, false otherwise.
" }, { "textRaw": "Type: {http.IncomingMessage}", "name": "req", "type": "http.IncomingMessage", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "A reference to the original HTTP request object.
When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; HTTP requires the Date header\nin responses.
" }, { "textRaw": "Type: {stream.Duplex}", "name": "socket", "type": "stream.Duplex", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end(), the property is nulled.
import http from 'node:http';\nconst server = http.createServer((req, res) => {\n const ip = res.socket.remoteAddress;\n const port = res.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n\nconst http = require('node:http');\nconst server = http.createServer((req, res) => {\n const ip = res.socket.remoteAddress;\n const port = res.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n\nThis property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket>.
When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
response.statusCode = 404;\n\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
" }, { "textRaw": "Type: {string}", "name": "statusMessage", "type": "string", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status message that will be sent to the client when\nthe headers get flushed. If this is left as undefined then the standard\nmessage for the status code will be used.
response.statusMessage = 'Not found';\n\nAfter response header was sent to the client, this property indicates the\nstatus message which was sent out.
" }, { "textRaw": "Type: {boolean} **Default:** `false`", "name": "strictContentLength", "type": "boolean", "meta": { "added": [ "v18.10.0", "v16.18.0" ], "changes": [] }, "default": "`false`", "desc": "If set to true, Node.js will check whether the Content-Length\nheader value and the size of the body, in bytes, are equal.\nMismatching the Content-Length header value will result\nin an Error being thrown, identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nresponse.writableFinished instead.
Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.
<stream.Readable>An IncomingMessage object is created by http.Server or\nhttp.ClientRequest and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response\nstatus, 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\nparse and emit the incoming HTTP headers and payload, as the underlying socket\nmay be reused multiple times in case of keep-alive.
Emitted when the request has been aborted.
" }, { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v0.4.2" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/33035", "description": "The close event is now emitted when the request has been completed and not when the underlying socket is closed." } ] }, "params": [], "desc": "Emitted when the request has been completed.
" } ], "properties": [ { "textRaw": "Type: {boolean}", "name": "aborted", "type": "boolean", "meta": { "added": [ "v10.1.0" ], "changes": [], "deprecated": [ "v17.0.0", "v16.12.0" ] }, "stability": 0, "stabilityText": "Deprecated. Check `message.destroyed` from {stream.Readable}.", "desc": "The message.aborted property will be true if the request has\nbeen aborted.
The message.complete property will be true if a complete HTTP message has\nbeen received and successfully parsed.
This property is particularly useful as a means of determining if a client or\nserver fully transmitted a message before a connection was terminated:
\nconst req = http.request({\n host: '127.0.0.1',\n port: 8080,\n method: 'POST',\n}, (res) => {\n res.resume();\n res.on('end', () => {\n if (!res.complete)\n console.error(\n 'The connection was terminated while the message was still being sent');\n });\n});\n"
},
{
"textRaw": "`message.connection`",
"name": "connection",
"type": "property",
"meta": {
"added": [
"v0.1.90"
],
"changes": [],
"deprecated": [
"v16.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated. Use `message.socket`.",
"desc": "Alias for message.socket.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n\nDuplicates in raw headers are handled in the following ways, depending on the\nheader name:
\nage, authorization, content-length, content-type,\netag, expires, from, host, if-modified-since, if-unmodified-since,\nlast-modified, location, max-forwards, proxy-authorization, referer,\nretry-after, server, or user-agent are discarded.\nTo allow duplicate values of the headers listed above to be joined,\nuse the option joinDuplicateHeaders in http.request()\nand http.createServer(). See RFC 9110 Section 5.3 for more\ninformation.set-cookie is always an array. Duplicates are added to the array.cookie headers, the values are joined together with ; ., .Similar to message.headers, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.
// Prints something like:\n//\n// { 'user-agent': ['curl/7.22.0'],\n// host: ['127.0.0.1:8000'],\n// accept: ['*/*'] }\nconsole.log(request.headersDistinct);\n"
},
{
"textRaw": "Type: {string}",
"name": "httpVersion",
"type": "string",
"meta": {
"added": [
"v0.1.1"
],
"changes": []
},
"desc": "In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.
Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.
Only valid for request obtained from http.Server.
The request method as a string. Read only. Examples: 'GET', 'DELETE'.
The raw request/response headers list exactly as they were received.
\nThe keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.
\nHeader names are not lowercased, and duplicates are not merged.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n"
},
{
"textRaw": "Type: {string[]}",
"name": "rawTrailers",
"type": "string[]",
"meta": {
"added": [
"v0.11.6"
],
"changes": []
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.
The net.Socket object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate() to obtain the\nclient's authentication details.
This property is guaranteed to be an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specified a socket\ntype other than <net.Socket> or internally nulled.
Only valid for response obtained from http.ClientRequest.
The 3-digit HTTP response status code. E.G. 404.
Only valid for response obtained from http.ClientRequest.
The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.
The request/response trailers object. Only populated at the 'end' event.
Similar to message.trailers, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.\nOnly populated at the 'end' event.
Only valid for request obtained from http.Server.
Request URL string. This contains only the URL that is present in the actual\nHTTP request. Take the following request:
\nGET /status?name=ryan HTTP/1.1\nAccept: text/plain\n\nTo parse the URL into its parts:
\nnew URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);\n\nWhen request.url is '/status?name=ryan' and process.env.HOST is undefined:
$ node\n> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);\nURL {\n href: 'http://localhost/status?name=ryan',\n origin: 'http://localhost',\n protocol: 'http:',\n username: '',\n password: '',\n host: 'localhost',\n hostname: 'localhost',\n port: '',\n pathname: '/status',\n search: '?name=ryan',\n searchParams: URLSearchParams { 'name' => 'ryan' },\n hash: ''\n}\n\nEnsure that you set process.env.HOST to the server's host name, or consider\nreplacing this part entirely. If using req.headers.host, ensure proper\nvalidation is used, as clients may specify a custom Host header.
Calls destroy() on the socket that received the IncomingMessage. If error\nis provided, an 'error' event is emitted on the socket and error is passed\nas an argument to any listeners on the event.
Calls message.socket.setTimeout(msecs, callback).
<Stream>This class serves as the parent class of http.ClientRequest\nand http.ServerResponse. It is an abstract outgoing message from\nthe perspective of the participants of an HTTP transaction.
Emitted when the buffer of the message is free again.
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "params": [], "desc": "Emitted when the transmission is finished successfully.
" }, { "textRaw": "Event: `'prefinish'`", "name": "prefinish", "type": "event", "meta": { "added": [ "v0.11.6" ], "changes": [] }, "params": [], "desc": "Emitted after outgoingMessage.end() is called.\nWhen the event is emitted, all data has been processed but not necessarily\ncompletely flushed.
Adds HTTP trailers (headers but at the end of the message) to the message.
\nTrailers will only be emitted if the message is chunked encoded. If not,\nthe trailers will be silently discarded.
\nHTTP requires the Trailer header to be sent to emit trailers,\nwith a list of header field names in its value, e.g.
message.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nmessage.write(fileData);\nmessage.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nmessage.end();\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
Append a single header value to the header object.
\nIf the value is an array, this is equivalent to calling this method multiple\ntimes.
\nIf there were no previous values for the header, this is equivalent to calling\noutgoingMessage.setHeader(name, value).
Depending of the value of options.uniqueHeaders when the client request or the\nserver were created, this will end up in the header being sent multiple times or\na single time with values joined using ; .
See writable.cork().
Destroys the message. Once a socket is associated with the message\nand is connected, that socket will be destroyed as well.
" }, { "textRaw": "`outgoingMessage.end(chunk[, encoding][, callback])`", "name": "end", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33155", "description": "The `chunk` parameter can now be a `Uint8Array`." }, { "version": "v0.11.6", "description": "add `callback` argument." } ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array}", "name": "chunk", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string} Optional, **Default**: `utf8`", "name": "encoding", "type": "string", "desc": "Optional, **Default**: `utf8`", "optional": true }, { "textRaw": "`callback` {Function} Optional", "name": "callback", "type": "Function", "desc": "Optional", "optional": true } ], "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" } } ], "desc": "Finishes the outgoing message. If any parts of the body are unsent, it will\nflush them to the underlying system. If the message is chunked, it will\nsend the terminating chunk 0\\r\\n\\r\\n, and send the trailers (if any).
If chunk is specified, it is equivalent to calling\noutgoingMessage.write(chunk, encoding), followed by\noutgoingMessage.end(callback).
If callback is provided, it will be called when the message is finished\n(equivalent to a listener of the 'finish' event).
Flushes the message headers.
\nFor efficiency reason, Node.js normally buffers the message headers\nuntil outgoingMessage.end() is called or the first chunk of message data\nis written. It then tries to pack the headers and data into a single TCP\npacket.
It is usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. outgoingMessage.flushHeaders()\nbypasses the optimization and kickstarts the message.
Gets the value of the HTTP header with the given name. If that header is not\nset, the returned value will be undefined.
Returns an array containing the unique names of the current outgoing headers.\nAll names are lowercase.
" }, { "textRaw": "`outgoingMessage.getHeaders()`", "name": "getHeaders", "type": "method", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" } } ], "desc": "Returns a shallow copy of the current outgoing headers. Since a shallow\ncopy is used, array values may be mutated without additional calls to\nvarious header-related HTTP module methods. The keys of the returned\nobject are the header names and the values are the respective header\nvalues. All header names are lowercase.
\nThe object returned by the outgoingMessage.getHeaders() method does\nnot prototypically inherit from the JavaScript Object. This means that\ntypical Object methods such as obj.toString(), obj.hasOwnProperty(),\nand others are not defined and will not work.
outgoingMessage.setHeader('Foo', 'bar');\noutgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = outgoingMessage.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`outgoingMessage.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name is case-insensitive.
const hasContentType = outgoingMessage.hasHeader('content-type');\n"
},
{
"textRaw": "`outgoingMessage.pipe()`",
"name": "pipe",
"type": "method",
"meta": {
"added": [
"v9.0.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Overrides the stream.pipe() method inherited from the legacy Stream class\nwhich is the parent class of http.OutgoingMessage.
Calling this method will throw an Error because outgoingMessage is a\nwrite-only stream.
Removes a header that is queued for implicit sending.
\noutgoingMessage.removeHeader('Content-Encoding');\n"
},
{
"textRaw": "`outgoingMessage.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} Header name",
"name": "name",
"type": "string",
"desc": "Header name"
},
{
"textRaw": "`value` {number|string|string[]} Header value",
"name": "value",
"type": "number|string|string[]",
"desc": "Header value"
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "Sets a single header value. If the header already exists in the to-be-sent\nheaders, its value will be replaced. Use an array of strings to send multiple\nheaders with the same name.
" }, { "textRaw": "`outgoingMessage.setHeaders(headers)`", "name": "setHeaders", "type": "method", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Headers|Map}", "name": "headers", "type": "Headers|Map" } ], "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" } } ], "desc": "Sets multiple header values for implicit headers.\nheaders must be an instance of Headers or Map,\nif a header already exists in the to-be-sent headers,\nits value will be replaced.
const headers = new Headers({ foo: 'bar' });\noutgoingMessage.setHeaders(headers);\n\nor
\nconst headers = new Map([['foo', 'bar']]);\noutgoingMessage.setHeaders(headers);\n\nWhen headers have been set with outgoingMessage.setHeaders(),\nthey will be merged with any headers passed to response.writeHead(),\nwith the headers passed to response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n const headers = new Headers({ 'Content-Type': 'text/html' });\n res.setHeaders(headers);\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n"
},
{
"textRaw": "`outgoingMessage.setTimeout(msecs[, callback])`",
"name": "setTimeout",
"type": "method",
"meta": {
"added": [
"v0.9.12"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {number}",
"name": "msecs",
"type": "number"
},
{
"textRaw": "`callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.",
"name": "callback",
"type": "Function",
"desc": "Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "Once a socket is associated with the message and is connected,\nsocket.setTimeout() will be called with msecs as the first parameter.
Sends a chunk of the body. This method can be called multiple times.
\nThe encoding argument is only relevant when chunk is a string. Defaults to\n'utf8'.
The callback argument is optional and will be called when this chunk of data\nis flushed.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in the user\nmemory. The 'drain' event will be emitted when the buffer is free again.
Alias of outgoingMessage.socket.
Read-only. true if the headers were sent, otherwise false.
Reference to the underlying socket. Usually, users will not want to access\nthis property.
\nAfter calling outgoingMessage.end(), this property will be nulled.
The number of times outgoingMessage.cork() has been called.
Is true if outgoingMessage.end() has been called. This property does\nnot indicate whether the data has been flushed. For that purpose, use\nmessage.writableFinished instead.
Is true if all data has been flushed to the underlying system.
The highWaterMark of the underlying socket if assigned. Otherwise, the default\nbuffer level when writable.write() starts returning false (16384).
The number of buffered bytes.
" }, { "textRaw": "Type: {boolean}", "name": "writableObjectMode", "type": "boolean", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "Always false.
A browser-compatible implementation of <WebSocket>.
A list of the HTTP methods that are supported by the parser.
" }, { "textRaw": "Type: {Object}", "name": "STATUS_CODES", "type": "Object", "meta": { "added": [ "v0.1.22" ], "changes": [] }, "desc": "A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not Found'.
Global instance of Agent which is used as the default for all HTTP client\nrequests. Diverges from a default Agent configuration by having keepAlive\nenabled and a timeout of 5 seconds.
Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 16 KiB. Configurable using the --max-http-header-size CLI\noption.
This can be overridden for servers and client requests by passing the\nmaxHeaderSize option.
Returns a new instance of http.Server.
The requestListener is a function which is automatically\nadded to the 'request' event.
import http from 'node:http';\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nconst http = require('node:http');\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nimport http from 'node:http';\n\n// Create a local server to receive data from\nconst server = http.createServer();\n\n// Listen to the request event\nserver.on('request', (request, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nconst http = require('node:http');\n\n// Create a local server to receive data from\nconst server = http.createServer();\n\n// Listen to the request event\nserver.on('request', (request, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n"
},
{
"textRaw": "`http.get(options[, callback])`",
"name": "get",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`http.get(url[, options][, callback])`",
"name": "get",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string|URL}",
"name": "url",
"type": "string|URL"
},
{
"textRaw": "`options` {Object} Accepts the same `options` as `http.request()`, with the method set to GET by default.",
"name": "options",
"type": "Object",
"desc": "Accepts the same `options` as `http.request()`, with the method set to GET by default.",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET by default and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.
The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.
JSON fetching example:
\nhttp.get('http://localhost:8000/', (res) => {\n const { statusCode } = res;\n const contentType = res.headers['content-type'];\n\n let error;\n // Any 2xx status code signals a successful response but\n // here we're only checking for 200.\n if (statusCode !== 200) {\n error = new Error('Request Failed.\\n' +\n `Status Code: ${statusCode}`);\n } else if (!/^application\\/json/.test(contentType)) {\n error = new Error('Invalid content-type.\\n' +\n `Expected application/json but received ${contentType}`);\n }\n if (error) {\n console.error(error.message);\n // Consume response data to free up memory\n res.resume();\n return;\n }\n\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => { rawData += chunk; });\n res.on('end', () => {\n try {\n const parsedData = JSON.parse(rawData);\n console.log(parsedData);\n } catch (e) {\n console.error(e.message);\n }\n });\n}).on('error', (e) => {\n console.error(`Got error: ${e.message}`);\n});\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n"
},
{
"textRaw": "`http.request(options[, callback])`",
"name": "request",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`http.request(url[, options][, callback])`",
"name": "request",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": [
"v16.7.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/39310",
"description": "When using a `URL` object parsed username and password will now be properly URI decoded."
},
{
"version": [
"v15.3.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36048",
"description": "It is possible to abort a request with an AbortSignal."
},
{
"version": [
"v13.8.0",
"v12.15.0",
"v10.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/31448",
"description": "The `insecureHTTPParser` option is supported now."
},
{
"version": "v13.3.0",
"pr-url": "https://github.com/nodejs/node/pull/30570",
"description": "The `maxHeaderSize` option is supported now."
},
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string|URL}",
"name": "url",
"type": "string|URL"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`agent` {http.Agent|boolean} Controls `Agent` behavior. Possible values:",
"name": "agent",
"type": "http.Agent|boolean",
"desc": "Controls `Agent` behavior. Possible values:",
"options": [
{
"textRaw": "`undefined` (default): use `http.globalAgent` for this host and port.",
"name": "undefined",
"desc": "(default): use `http.globalAgent` for this host and port."
},
{
"textRaw": "`Agent` object: explicitly use the passed in `Agent`.",
"name": "Agent",
"desc": "object: explicitly use the passed in `Agent`."
},
{
"textRaw": "`false`: causes a new `Agent` with default values to be used.",
"name": "false",
"desc": "causes a new `Agent` with default values to be used."
}
]
},
{
"textRaw": "`auth` {string} Basic authentication (`'user:password'`) to compute an Authorization header.",
"name": "auth",
"type": "string",
"desc": "Basic authentication (`'user:password'`) to compute an Authorization header."
},
{
"textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See `agent.createConnection()` for more details. Any `Duplex` stream is a valid return value.",
"name": "createConnection",
"type": "Function",
"desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See `agent.createConnection()` for more details. Any `Duplex` stream is a valid return value."
},
{
"textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.",
"name": "defaultPort",
"type": "number",
"default": "`agent.defaultPort` if an `Agent` is used, else `undefined`",
"desc": "Default port for the protocol."
},
{
"textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.",
"name": "family",
"type": "number",
"desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used."
},
{
"textRaw": "`headers` {Object|Array} An object or an array of strings containing request headers. The array is in the same format as `message.rawHeaders`.",
"name": "headers",
"type": "Object|Array",
"desc": "An object or an array of strings containing request headers. The array is in the same format as `message.rawHeaders`."
},
{
"textRaw": "`hints` {number} Optional `dns.lookup()` hints.",
"name": "hints",
"type": "number",
"desc": "Optional `dns.lookup()` hints."
},
{
"textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.",
"name": "host",
"type": "string",
"default": "`'localhost'`",
"desc": "A domain name or IP address of the server to issue the request to."
},
{
"textRaw": "`hostname` {string} Alias for `host`. To support `url.parse()`, `hostname` will be used if both `host` and `hostname` are specified.",
"name": "hostname",
"type": "string",
"desc": "Alias for `host`. To support `url.parse()`, `hostname` will be used if both `host` and `hostname` are specified."
},
{
"textRaw": "`insecureHTTPParser` {boolean} If set to `true`, it will use a HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See `--insecure-http-parser` for more information. **Default:** `false`",
"name": "insecureHTTPParser",
"type": "boolean",
"default": "`false`",
"desc": "If set to `true`, it will use a HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See `--insecure-http-parser` for more information."
},
{
"textRaw": "`joinDuplicateHeaders` {boolean} It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. See `message.headers` for more information. **Default:** `false`.",
"name": "joinDuplicateHeaders",
"type": "boolean",
"default": "`false`",
"desc": "It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. See `message.headers` for more information."
},
{
"textRaw": "`localAddress` {string} Local interface to bind for network connections.",
"name": "localAddress",
"type": "string",
"desc": "Local interface to bind for network connections."
},
{
"textRaw": "`localPort` {number} Local port to connect from.",
"name": "localPort",
"type": "number",
"desc": "Local port to connect from."
},
{
"textRaw": "`lookup` {Function} Custom lookup function. **Default:** `dns.lookup()`.",
"name": "lookup",
"type": "Function",
"default": "`dns.lookup()`",
"desc": "Custom lookup function."
},
{
"textRaw": "`maxHeaderSize` {number} Optionally overrides the value of `--max-http-header-size` (the maximum length of response headers in bytes) for responses received from the server. **Default:** 16384 (16 KiB).",
"name": "maxHeaderSize",
"type": "number",
"default": "16384 (16 KiB)",
"desc": "Optionally overrides the value of `--max-http-header-size` (the maximum length of response headers in bytes) for responses received from the server."
},
{
"textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.",
"name": "method",
"type": "string",
"default": "`'GET'`",
"desc": "A string specifying the HTTP request method."
},
{
"textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`.",
"name": "path",
"type": "string",
"default": "`'/'`",
"desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future."
},
{
"textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.",
"name": "port",
"type": "number",
"default": "`defaultPort` if set, else `80`",
"desc": "Port of remote server."
},
{
"textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.",
"name": "protocol",
"type": "string",
"default": "`'http:'`",
"desc": "Protocol to use."
},
{
"textRaw": "`setDefaultHeaders` {boolean}: Specifies whether or not to automatically add default headers such as `Connection`, `Content-Length`, `Transfer-Encoding`, and `Host`. If set to `false` then all necessary headers must be added manually. Defaults to `true`.",
"name": "setDefaultHeaders",
"type": "boolean",
"desc": ": Specifies whether or not to automatically add default headers such as `Connection`, `Content-Length`, `Transfer-Encoding`, and `Host`. If set to `false` then all necessary headers must be added manually. Defaults to `true`."
},
{
"textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. If provided, this overrides `setDefaultHeaders`. Defaults to `true`.",
"name": "setHost",
"type": "boolean",
"desc": ": Specifies whether or not to automatically add the `Host` header. If provided, this overrides `setDefaultHeaders`. Defaults to `true`."
},
{
"textRaw": "`signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing request.",
"name": "signal",
"type": "AbortSignal",
"desc": ": An AbortSignal that may be used to abort an ongoing request."
},
{
"textRaw": "`socketPath` {string} Unix domain socket. Cannot be used if one of `host` or `port` is specified, as those specify a TCP Socket.",
"name": "socketPath",
"type": "string",
"desc": "Unix domain socket. Cannot be used if one of `host` or `port` is specified, as those specify a TCP Socket."
},
{
"textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.",
"name": "timeout",
"type": "number",
"desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected."
},
{
"textRaw": "`uniqueHeaders` {Array} A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using `; `.",
"name": "uniqueHeaders",
"type": "Array",
"desc": "A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using `; `."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "options in socket.connect() are also supported.
Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.
\nurl can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.
If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.
The optional callback parameter will be added as a one-time listener for\nthe 'response' event.
http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.
import http from 'node:http';\nimport { Buffer } from 'node:buffer';\n\nconst postData = JSON.stringify({\n 'msg': 'Hello World!',\n});\n\nconst options = {\n hostname: 'www.google.com',\n port: 80,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData),\n },\n};\n\nconst req = http.request(options, (res) => {\n console.log(`STATUS: ${res.statusCode}`);\n console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n res.setEncoding('utf8');\n res.on('data', (chunk) => {\n console.log(`BODY: ${chunk}`);\n });\n res.on('end', () => {\n console.log('No more data in response.');\n });\n});\n\nreq.on('error', (e) => {\n console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n\nconst http = require('node:http');\n\nconst postData = JSON.stringify({\n 'msg': 'Hello World!',\n});\n\nconst options = {\n hostname: 'www.google.com',\n port: 80,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData),\n },\n};\n\nconst req = http.request(options, (res) => {\n console.log(`STATUS: ${res.statusCode}`);\n console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n res.setEncoding('utf8');\n res.on('data', (chunk) => {\n console.log(`BODY: ${chunk}`);\n });\n res.on('end', () => {\n console.log('No more data in response.');\n });\n});\n\nreq.on('error', (e) => {\n console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n\nIn the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.
There are a few special headers that should be noted.
\nSending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.
\nSending a 'Content-Length' header will disable the default chunked encoding.
\nSending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.
Sending an Authorization header will override using the auth option\nto compute basic authentication.
Example using a URL as options:
const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n // ...\n});\n\nIn a successful request, the following events will be emitted in the following\norder:
\n'socket''response'\n'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)'end' on the res object'close'In the case of a connection error, the following events will be emitted:
\n'socket''error''close'In the case of a premature connection close before the response is received,\nthe following events will be emitted in the following order:
\n'socket''error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET''close'In the case of a premature connection close after the response is received,\nthe following events will be emitted in the following order:
\n'socket''response'\n'data' any number of times, on the res object'aborted' on the res object'close''error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET''close' on the res objectIf req.destroy() is called before a socket is assigned, the following\nevents will be emitted in the following order:
req.destroy() called here)'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET', or the error with which req.destroy() was called'close'If req.destroy() is called before the connection succeeds, the following\nevents will be emitted in the following order:
'socket'req.destroy() called here)'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET', or the error with which req.destroy() was called'close'If req.destroy() is called after the response is received, the following\nevents will be emitted in the following order:
'socket''response'\n'data' any number of times, on the res objectreq.destroy() called here)'aborted' on the res object'close''error' on the res object with an error with message 'Error: aborted'\nand code 'ECONNRESET', or the error with which req.destroy() was called'close' on the res objectIf req.abort() is called before a socket is assigned, the following\nevents will be emitted in the following order:
req.abort() called here)'abort''close'If req.abort() is called before the connection succeeds, the following\nevents 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\n'ECONNRESET''close'If req.abort() is called after the response is received, the following\nevents will be emitted in the following order:
'socket''response'\n'data' any number of times, on the res objectreq.abort() called here)'abort''aborted' on the res object'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.'close''close' on the res objectSetting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.
Passing an AbortSignal and then calling abort() on the corresponding\nAbortController will behave the same way as calling .destroy() on the\nrequest. Specifically, the 'error' event will be emitted with an error with\nthe message 'AbortError: The operation was aborted', the code 'ABORT_ERR'\nand the cause, if one was provided.
Performs the low-level validations on the provided name that are done when\nres.setHeader(name, value) is called.
Passing illegal value as name will result in a TypeError being thrown,\nidentified by code: 'ERR_INVALID_HTTP_TOKEN'.
It is not necessary to use this method before passing headers to an HTTP request\nor response. The HTTP module will automatically validate such headers.
\nExample:
\nimport { validateHeaderName } from 'node:http';\n\ntry {\n validateHeaderName('');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'\n console.error(err.message); // --> 'Header name must be a valid HTTP token [\"\"]'\n}\n\nconst { validateHeaderName } = require('node:http');\n\ntry {\n validateHeaderName('');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'\n console.error(err.message); // --> 'Header name must be a valid HTTP token [\"\"]'\n}\n"
},
{
"textRaw": "`http.validateHeaderValue(name, value)`",
"name": "validateHeaderValue",
"type": "method",
"meta": {
"added": [
"v14.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Performs the low-level validations on the provided value that are done when\nres.setHeader(name, value) is called.
Passing illegal value as value will result in a TypeError being thrown.
code: 'ERR_HTTP_INVALID_HEADER_VALUE'.code: 'ERR_INVALID_CHAR'.It is not necessary to use this method before passing headers to an HTTP request\nor response. The HTTP module will automatically validate such headers.
\nExamples:
\nimport { validateHeaderValue } from 'node:http';\n\ntry {\n validateHeaderValue('x-my-header', undefined);\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true\n console.error(err.message); // --> 'Invalid value \"undefined\" for header \"x-my-header\"'\n}\n\ntry {\n validateHeaderValue('x-my-header', 'oʊmɪɡə');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_INVALID_CHAR'); // --> true\n console.error(err.message); // --> 'Invalid character in header content [\"x-my-header\"]'\n}\n\nconst { validateHeaderValue } = require('node:http');\n\ntry {\n validateHeaderValue('x-my-header', undefined);\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true\n console.error(err.message); // --> 'Invalid value \"undefined\" for header \"x-my-header\"'\n}\n\ntry {\n validateHeaderValue('x-my-header', 'oʊmɪɡə');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_INVALID_CHAR'); // --> true\n console.error(err.message); // --> 'Invalid character in header content [\"x-my-header\"]'\n}\n"
},
{
"textRaw": "`http.setMaxIdleHTTPParsers(max)`",
"name": "setMaxIdleHTTPParsers",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`max` {number} **Default:** `1000`.",
"name": "max",
"type": "number",
"default": "`1000`"
}
]
}
],
"desc": "Set the maximum number of idle HTTP parsers.
" }, { "textRaw": "`http.setGlobalProxyFromEnv([proxyEnv])`", "name": "setGlobalProxyFromEnv", "type": "method", "meta": { "added": [ "v25.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`proxyEnv` {Object} An object containing proxy configuration. This accepts the same options as the `proxyEnv` option accepted by `Agent`. **Default:** `process.env`.", "name": "proxyEnv", "type": "Object", "default": "`process.env`", "desc": "An object containing proxy configuration. This accepts the same options as the `proxyEnv` option accepted by `Agent`.", "optional": true } ], "return": { "textRaw": "Returns: {Function} A function that restores the original agent and dispatcher settings to the state before this `http.setGlobalProxyFromEnv()` is invoked.", "name": "return", "type": "Function", "desc": "A function that restores the original agent and dispatcher settings to the state before this `http.setGlobalProxyFromEnv()` is invoked." } } ], "desc": "Dynamically resets the global configurations to enable built-in proxy support for\nfetch() and http.request()/https.request() at runtime, as an alternative\nto using the --use-env-proxy flag or NODE_USE_ENV_PROXY environment variable.\nIt can also be used to override settings configured from the environment variables.
As this function resets the global configurations, any previously configured\nhttp.globalAgent, https.globalAgent or undici global dispatcher would be\noverridden after this function is invoked. It's recommended to invoke it before any\nrequests are made and avoid invoking it in the middle of any requests.
See Built-in Proxy Support for details on proxy URL formats and NO_PROXY\nsyntax.
When Node.js creates the global agent, if the NODE_USE_ENV_PROXY environment variable is\nset to 1 or --use-env-proxy is enabled, the global agent will be constructed\nwith proxyEnv: process.env, enabling proxy support based on the environment variables.
To enable proxy support dynamically and globally, use http.setGlobalProxyFromEnv().
Custom agents can also be created with proxy support by passing a\nproxyEnv option when constructing the agent. The value can be process.env\nif they just want to inherit the configuration from the environment variables,\nor an object with specific setting overriding the environment.
The following properties of the proxyEnv are checked to configure proxy\nsupport.
HTTP_PROXY or http_proxy: Proxy server URL for HTTP requests. If both are set,\nhttp_proxy takes precedence.HTTPS_PROXY or https_proxy: Proxy server URL for HTTPS requests. If both are set,\nhttps_proxy takes precedence.NO_PROXY or no_proxy: Comma-separated list of hosts to bypass the proxy. If both are set,\nno_proxy takes precedence.If the request is made to a Unix domain socket, the proxy settings will be ignored.
", "modules": [ { "textRaw": "Proxy URL Format", "name": "proxy_url_format", "type": "module", "desc": "Proxy URLs can use either HTTP or HTTPS protocols:
\nhttp://proxy.example.com:8080https://proxy.example.com:8080http://username:password@proxy.example.com:8080The NO_PROXY environment variable supports several formats:
* - Bypass proxy for all hostsexample.com - Exact host name match.example.com - Domain suffix match (matches sub.example.com)*.example.com - Wildcard domain match192.168.1.100 - Exact IP address match192.168.1.1-192.168.1.100 - IP address rangeexample.com:8080 - Hostname with specific portMultiple entries should be separated by commas.
", "displayName": "`NO_PROXY` Format" }, { "textRaw": "Example", "name": "example", "type": "module", "desc": "To start a Node.js process with proxy support enabled for all requests sent\nthrough the default global agent, either use the NODE_USE_ENV_PROXY environment\nvariable:
NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node client.js\n\nOr the --use-env-proxy flag.
HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node --use-env-proxy client.js\n\nTo enable proxy support dynamically and globally with process.env (the default option of http.setGlobalProxyFromEnv()):
const http = require('node:http');\n\n// Reads proxy-related environment variables from process.env\nconst restore = http.setGlobalProxyFromEnv();\n\n// Subsequent requests will use the configured proxies from environment variables\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied if HTTP_PROXY or http_proxy is set\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied if HTTPS_PROXY or https_proxy is set\n});\n\n// To restore the original global agent and dispatcher settings, call the returned function.\n// restore();\n\nimport http from 'node:http';\n\n// Reads proxy-related environment variables from process.env\nhttp.setGlobalProxyFromEnv();\n\n// Subsequent requests will use the configured proxies from environment variables\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied if HTTP_PROXY or http_proxy is set\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied if HTTPS_PROXY or https_proxy is set\n});\n\n// To restore the original global agent and dispatcher settings, call the returned function.\n// restore();\n\nTo enable proxy support dynamically and globally with custom settings:
\nconst http = require('node:http');\n\nconst restore = http.setGlobalProxyFromEnv({\n http_proxy: 'http://proxy.example.com:8080',\n https_proxy: 'https://proxy.example.com:8443',\n no_proxy: 'localhost,127.0.0.1,.internal.example.com',\n});\n\n// Subsequent requests will use the configured proxies\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8080\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8443\n});\n\nimport http from 'node:http';\n\nhttp.setGlobalProxyFromEnv({\n http_proxy: 'http://proxy.example.com:8080',\n https_proxy: 'https://proxy.example.com:8443',\n no_proxy: 'localhost,127.0.0.1,.internal.example.com',\n});\n\n// Subsequent requests will use the configured proxies\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8080\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8443\n});\n\nTo create a custom agent with built-in proxy support:
\nconst http = require('node:http');\n\n// Creating a custom agent with custom proxy support.\nconst agent = new http.Agent({ proxyEnv: { HTTP_PROXY: 'http://proxy.example.com:8080' } });\n\nhttp.request({\n hostname: 'www.example.com',\n port: 80,\n path: '/',\n agent,\n}, (res) => {\n // This request will be proxied through proxy.example.com:8080 using the HTTP protocol.\n console.log(`STATUS: ${res.statusCode}`);\n});\n\nAlternatively, the following also works:
\nconst http = require('node:http');\n// Use lower-cased option name.\nconst agent1 = new http.Agent({ proxyEnv: { http_proxy: 'http://proxy.example.com:8080' } });\n// Use values inherited from the environment variables, if the process is started with\n// HTTP_PROXY=http://proxy.example.com:8080 this will use the proxy server specified\n// in process.env.HTTP_PROXY.\nconst agent2 = new http.Agent({ proxyEnv: process.env });\n",
"displayName": "Example"
}
],
"displayName": "Built-in Proxy Support"
}
],
"displayName": "HTTP",
"source": "doc/api/http.md"
},
{
"textRaw": "HTTP/2",
"name": "http/2",
"introduced_in": "v8.4.0",
"type": "module",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": [
"v15.3.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36070",
"description": "It is possible to abort a request with an AbortSignal."
},
{
"version": "v15.0.0",
"pr-url": "https://github.com/nodejs/node/pull/34664",
"description": "Requests with the `host` header (with or without `:authority`) can now be sent/received."
},
{
"version": "v10.10.0",
"pr-url": "https://github.com/nodejs/node/pull/22466",
"description": "HTTP/2 is now Stable. Previously, it had been Experimental."
}
]
},
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:http2 module provides an implementation of the HTTP/2 protocol.\nIt can be accessed using:
const http2 = require('node:http2');\n",
"modules": [
{
"textRaw": "Determining if crypto support is unavailable",
"name": "determining_if_crypto_support_is_unavailable",
"type": "module",
"desc": "It is possible for Node.js to be built without including support for the\nnode:crypto module. In such cases, attempting to import from node:http2 or\ncalling require('node:http2') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
\nlet http2;\ntry {\n http2 = require('node:http2');\n} catch (err) {\n console.error('http2 support is disabled!');\n}\n\nWhen using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made (using, for instance,\na preload module).
When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:
let http2;\ntry {\n http2 = await import('node:http2');\n} catch (err) {\n console.error('http2 support is disabled!');\n}\n",
"displayName": "Determining if crypto support is unavailable"
},
{
"textRaw": "Core API",
"name": "core_api",
"type": "module",
"desc": "The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically not designed for\ncompatibility with the existing HTTP/1 module API. However,\nthe Compatibility API is.
\nThe http2 Core API is much more symmetric between client and server than the\nhttp API. For instance, most events, like 'error', 'connect' and\n'stream', can be emitted either by client-side code or server-side code.
The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.
import { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer({\n key: readFileSync('localhost-privkey.pem'),\n cert: readFileSync('localhost-cert.pem'),\n});\n\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n // stream is a Duplex\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n\nconst http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createSecureServer({\n key: fs.readFileSync('localhost-privkey.pem'),\n cert: fs.readFileSync('localhost-cert.pem'),\n});\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n // stream is a Duplex\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n\nTo generate the certificate and key for this example, run:
\nopenssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n -keyout localhost-privkey.pem -out localhost-cert.pem\n",
"displayName": "Server-side example"
},
{
"textRaw": "Client-side example",
"name": "client-side_example",
"type": "module",
"desc": "The following illustrates an HTTP/2 client:
\nimport { connect } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst client = connect('https://localhost:8443', {\n ca: readFileSync('localhost-cert.pem'),\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n for (const name in headers) {\n console.log(`${name}: ${headers[name]}`);\n }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n console.log(`\\n${data}`);\n client.close();\n});\nreq.end();\n\nconst http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst client = http2.connect('https://localhost:8443', {\n ca: fs.readFileSync('localhost-cert.pem'),\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n for (const name in headers) {\n console.log(`${name}: ${headers[name]}`);\n }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n console.log(`\\n${data}`);\n client.close();\n});\nreq.end();\n",
"displayName": "Client-side example"
},
{
"textRaw": "Headers object",
"name": "headers_object",
"type": "module",
"desc": "Headers are represented as own-properties on JavaScript objects. The property\nkeys will be serialized to lower-case. Property values should be strings (if\nthey are not they will be coerced to strings) or an Array of strings (in order\nto send more than one value per header field).
const headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'ABC': ['has', 'more', 'than', 'one', 'value'],\n};\n\nstream.respond(headers);\n\nHeader objects passed to callback functions will have a null prototype. This\nmeans that normal JavaScript object methods such as\nObject.prototype.toString() and Object.prototype.hasOwnProperty() will\nnot work.
For incoming headers:
\n:status header is converted to number.:status, :method, :authority, :scheme, :path,\n:protocol, age, authorization, access-control-allow-credentials,\naccess-control-max-age, access-control-request-method, content-encoding,\ncontent-language, content-length, content-location, content-md5,\ncontent-range, content-type, date, dnt, etag, expires, from,\nhost, if-match, if-modified-since, if-none-match, if-range,\nif-unmodified-since, last-modified, location, max-forwards,\nproxy-authorization, range, referer,retry-after, tk,\nupgrade-insecure-requests, user-agent or x-content-type-options are\ndiscarded.set-cookie is always an array. Duplicates are added to the array.cookie headers, the values are joined together with '; '.import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream, headers) => {\n console.log(headers[':path']);\n console.log(headers.ABC);\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n console.log(headers[':path']);\n console.log(headers.ABC);\n});\n",
"modules": [
{
"textRaw": "Raw headers",
"name": "raw_headers",
"type": "module",
"desc": "In some APIs, in addition to object format, headers can also be passed or\naccessed as a raw flat array, preserving details of ordering and\nduplicate keys to match the raw transmission format.
\nIn this format the keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values. Duplicate headers are\nnot merged and so each key-value pair will appear separately.
\nThis can be useful for cases such as proxies, where existing headers\nshould be exactly forwarded as received, or as a performance\noptimization when the headers are already available in raw format.
\nconst rawHeaders = [\n ':status',\n '404',\n 'content-type',\n 'text/plain',\n];\n\nstream.respond(rawHeaders);\n",
"displayName": "Raw headers"
},
{
"textRaw": "Sensitive headers",
"name": "sensitive_headers",
"type": "module",
"desc": "HTTP2 headers can be marked as sensitive, which means that the HTTP/2\nheader compression algorithm will never index them. This can make sense for\nheader values with low entropy and that may be considered valuable to an\nattacker, for example Cookie or Authorization. To achieve this, add\nthe header name to the [http2.sensitiveHeaders] property as an array:
const headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'cookie': 'some-cookie',\n 'other-sensitive-header': 'very secret data',\n [http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header'],\n};\n\nstream.respond(headers);\n\nFor some headers, such as Authorization and short Cookie headers,\nthis flag is set automatically.
This property is also set for received headers. It will contain the names of\nall headers marked as sensitive, including ones marked that way automatically.
\nFor raw headers, this should still be set as a property on the array, like\nrawHeadersArray[http2.sensitiveHeaders] = ['cookie'], not as a separate key\nand value pair within the array itself.
The http2.getDefaultSettings(), http2.getPackedSettings(),\nhttp2.createServer(), http2.createSecureServer(),\nhttp2session.settings(), http2session.localSettings, and\nhttp2session.remoteSettings APIs either return or receive as input an\nobject that defines configuration settings for an Http2Session object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.
headerTableSize <number> Specifies the maximum number of bytes used for\nheader compression. The minimum allowed value is 0. The maximum allowed value\nis 232-1. Default: 4096.enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be\npermitted on the Http2Session instances. Default: true.initialWindowSize <number> Specifies the sender's initial window size in\nbytes for stream-level flow control. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.maxFrameSize <number> Specifies the size in bytes of the largest frame\npayload. The minimum allowed value is 16,384. The maximum allowed value is\n224-1. Default: 16384.maxConcurrentStreams <number> Specifies the maximum number of concurrent\nstreams permitted on an Http2Session. There is no default value which\nimplies, at least theoretically, 232-1 streams may be open\nconcurrently at any given time in an Http2Session. The minimum value\nis 0. The maximum allowed value is 232-1. Default:\n4294967295.maxHeaderListSize <number> Specifies the maximum size (uncompressed octets)\nof header list that will be accepted. The minimum allowed value is 0. The\nmaximum allowed value is 232-1. Default: 65535.maxHeaderSize <number> Alias for maxHeaderListSize.enableConnectProtocol<boolean> Specifies true if the \"Extended Connect\nProtocol\" defined by RFC 8441 is to be enabled. This setting is only\nmeaningful if sent by the server. Once the enableConnectProtocol setting\nhas been enabled for a given Http2Session, it cannot be disabled.\nDefault: false.customSettings <Object> Specifies additional settings, yet not implemented\nin node and the underlying libraries. The key of the object defines the\nnumeric value of the settings type (as defined in the \"HTTP/2 SETTINGS\"\nregistry established by [RFC 7540]) and the values the actual numeric value\nof the settings.\nThe settings type has to be an integer in the range from 1 to 2^16-1.\nIt should not be a settings type already handled by node, i.e. currently\nit should be greater than 6, although it is not an error.\nThe values need to be unsigned integers in the range from 0 to 2^32-1.\nCurrently, a maximum of up 10 custom settings is supported.\nIt is only supported for sending SETTINGS, or for receiving settings values\nspecified in the remoteCustomSettings options of the server or client\nobject. Do not mix the customSettings-mechanism for a settings id with\ninterfaces for the natively handled settings, in case a setting becomes\nnatively supported in a future node version.All additional properties on the settings object are ignored.
", "displayName": "Settings object" }, { "textRaw": "Error handling", "name": "error_handling", "type": "module", "desc": "There are several types of error conditions that may arise when using the\nnode:http2 module:
Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.
State errors occur when an action is attempted at an incorrect time (for\ninstance, attempting to send data on a stream after it has closed). These will\nbe reported using either a synchronous throw or via an 'error' event on\nthe Http2Stream, Http2Session or HTTP/2 Server objects, depending on where\nand when the error occurs.
Internal errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an 'error' event on the Http2Session or HTTP/2 Server objects.
Protocol errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous throw or via an 'error'\nevent on the Http2Stream, Http2Session or HTTP/2 Server objects, depending\non where and when the error occurs.
The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.
\nHeader field names are case-insensitive and are transmitted over the wire\nstrictly as lower-case strings. The API provided by Node.js allows header\nnames to be set as mixed-case strings (e.g. Content-Type) but will convert\nthose to lower-case (e.g. content-type) upon transmission.
Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.
Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.
\nHeader field values are handled with more leniency but should not contain\nnew-line or carriage return characters and should be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.
", "displayName": "Invalid character handling in header names and values" }, { "textRaw": "Push streams on the client", "name": "push_streams_on_the_client", "type": "module", "desc": "To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:
import { connect } from 'node:http2';\n\nconst client = connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n pushedStream.on('push', (responseHeaders) => {\n // Process response headers\n });\n pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n\nconst http2 = require('node:http2');\n\nconst client = http2.connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n pushedStream.on('push', (responseHeaders) => {\n // Process response headers\n });\n pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n",
"displayName": "Push streams on the client"
},
{
"textRaw": "Supporting the `CONNECT` method",
"name": "supporting_the_`connect`_method",
"type": "module",
"desc": "The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.
A simple TCP Server:
\nimport { createServer } from 'node:net';\n\nconst server = createServer((socket) => {\n let name = '';\n socket.setEncoding('utf8');\n socket.on('data', (chunk) => name += chunk);\n socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n\nconst net = require('node:net');\n\nconst server = net.createServer((socket) => {\n let name = '';\n socket.setEncoding('utf8');\n socket.on('data', (chunk) => name += chunk);\n socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n\nAn HTTP/2 CONNECT proxy:
\nimport { createServer, constants } from 'node:http2';\nconst { NGHTTP2_REFUSED_STREAM, NGHTTP2_CONNECT_ERROR } = constants;\nimport { connect } from 'node:net';\n\nconst proxy = createServer();\nproxy.on('stream', (stream, headers) => {\n if (headers[':method'] !== 'CONNECT') {\n // Only accept CONNECT requests\n stream.close(NGHTTP2_REFUSED_STREAM);\n return;\n }\n const auth = new URL(`tcp://${headers[':authority']}`);\n // It's a very good idea to verify that hostname and port are\n // things this proxy should be connecting to.\n const socket = connect(auth.port, auth.hostname, () => {\n stream.respond();\n socket.pipe(stream);\n stream.pipe(socket);\n });\n socket.on('error', (error) => {\n stream.close(NGHTTP2_CONNECT_ERROR);\n });\n});\n\nproxy.listen(8001);\n\nconst http2 = require('node:http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('node:net');\n\nconst proxy = http2.createServer();\nproxy.on('stream', (stream, headers) => {\n if (headers[':method'] !== 'CONNECT') {\n // Only accept CONNECT requests\n stream.close(NGHTTP2_REFUSED_STREAM);\n return;\n }\n const auth = new URL(`tcp://${headers[':authority']}`);\n // It's a very good idea to verify that hostname and port are\n // things this proxy should be connecting to.\n const socket = net.connect(auth.port, auth.hostname, () => {\n stream.respond();\n socket.pipe(stream);\n stream.pipe(socket);\n });\n socket.on('error', (error) => {\n stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);\n });\n});\n\nproxy.listen(8001);\n\nAn HTTP/2 CONNECT client:
\nimport { connect, constants } from 'node:http2';\n\nconst client = connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n ':method': 'CONNECT',\n ':authority': 'localhost:8000',\n});\n\nreq.on('response', (headers) => {\n console.log(headers[constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n console.log(`The server says: ${data}`);\n client.close();\n});\nreq.end('Jane');\n\nconst http2 = require('node:http2');\n\nconst client = http2.connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n ':method': 'CONNECT',\n ':authority': 'localhost:8000',\n});\n\nreq.on('response', (headers) => {\n console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n console.log(`The server says: ${data}`);\n client.close();\n});\nreq.end('Jane');\n",
"displayName": "Supporting the `CONNECT` method"
},
{
"textRaw": "The extended `CONNECT` protocol",
"name": "the_extended_`connect`_protocol",
"type": "module",
"desc": "RFC 8441 defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an Http2Stream using the CONNECT\nmethod as a tunnel for other communication protocols (such as WebSockets).
The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:
import { createServer } from 'node:http2';\nconst settings = { enableConnectProtocol: true };\nconst server = createServer({ settings });\n\nconst http2 = require('node:http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n\nOnce the client receives the SETTINGS frame from the server indicating that\nthe extended CONNECT may be used, it may send CONNECT requests that use the\n':protocol' HTTP/2 pseudo-header:
import { connect } from 'node:http2';\nconst client = connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n if (settings.enableConnectProtocol) {\n const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n // ...\n }\n});\n\nconst http2 = require('node:http2');\nconst client = http2.connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n if (settings.enableConnectProtocol) {\n const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n // ...\n }\n});\n",
"displayName": "The extended `CONNECT` protocol"
}
],
"classes": [
{
"textRaw": "Class: `Http2Session`",
"name": "Http2Session",
"type": "class",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "<EventEmitter>Instances of the http2.Http2Session class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are not\nintended to be constructed directly by user code.
Each Http2Session instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\nhttp2session.type property can be used to determine the mode in which an\nHttp2Session is operating. On the server side, user code should rarely\nhave occasion to work with the Http2Session object directly, with most\nactions typically taken through interactions with either the Http2Server or\nHttp2Stream objects.
User code will not create Http2Session instances directly. Server-side\nHttp2Session instances are created by the Http2Server instance when a\nnew HTTP/2 connection is received. Client-side Http2Session instances are\ncreated using the http2.connect() method.
Every Http2Session instance is associated with exactly one net.Socket or\ntls.TLSSocket when it is created. When either the Socket or the\nHttp2Session are destroyed, both will be destroyed.
Because of the specific serialization and processing requirements imposed\nby the HTTP/2 protocol, it is not recommended for user code to read data from\nor write data to a Socket instance bound to a Http2Session. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.
Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.
The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.
The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.
User code will typically not listen for this event directly.
" }, { "textRaw": "Event: `'error'`", "name": "error", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.
The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame on the session. If the frame that could not be sent is associated\nwith a specific Http2Stream, an attempt to emit a 'frameError' event on the\nHttp2Stream is made.
If the 'frameError' event is associated with a stream, the stream will be\nclosed and destroyed immediately following the 'frameError' event. If the\nevent is not associated with a stream, the Http2Session will be shut down\nimmediately following the 'frameError' event.
The 'goaway' event is emitted when a GOAWAY frame is received.
The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.
The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.
When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n /* Use the new settings */\n});\n"
},
{
"textRaw": "Event: `'ping'`",
"name": "ping",
"type": "event",
"meta": {
"added": [
"v10.12.0"
],
"changes": []
},
"params": [
{
"textRaw": "`payload` {Buffer} The `PING` frame 8-byte payload",
"name": "payload",
"type": "Buffer",
"desc": "The `PING` frame 8-byte payload"
}
],
"desc": "The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.
The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.
session.on('remoteSettings', (settings) => {\n /* Use the new settings */\n});\n"
},
{
"textRaw": "Event: `'stream'`",
"name": "stream",
"type": "event",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"params": [
{
"textRaw": "`stream` {Http2Stream} A reference to the stream",
"name": "stream",
"type": "Http2Stream",
"desc": "A reference to the stream"
},
{
"textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers",
"name": "headers",
"type": "HTTP/2 Headers Object",
"desc": "An object describing the headers"
},
{
"textRaw": "`flags` {number} The associated numeric flags",
"name": "flags",
"type": "number",
"desc": "The associated numeric flags"
},
{
"textRaw": "`rawHeaders` {HTTP/2 Raw Headers} An array containing the raw headers",
"name": "rawHeaders",
"type": "HTTP/2 Raw Headers",
"desc": "An array containing the raw headers"
}
],
"desc": "The 'stream' event is emitted when a new Http2Stream is created.
session.on('stream', (stream, headers, flags) => {\n const method = headers[':method'];\n const path = headers[':path'];\n // ...\n stream.respond({\n ':status': 200,\n 'content-type': 'text/plain; charset=utf-8',\n });\n stream.write('hello ');\n stream.end('world');\n});\n\nOn the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the 'stream' event emitted by the\nnet.Server or tls.Server instances returned by http2.createServer() and\nhttp2.createSecureServer(), respectively, as in the example below:
import { createServer } from 'node:http2';\n\n// Create an unencrypted HTTP/2 server\nconst server = createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.on('error', (error) => console.error(error));\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8000);\n\nconst http2 = require('node:http2');\n\n// Create an unencrypted HTTP/2 server\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.on('error', (error) => console.error(error));\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8000);\n\nEven though HTTP/2 streams and network sockets are not in a 1:1 correspondence,\na network error will destroy each individual stream and must be handled on the\nstream level, as shown above.
" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "After the http2session.setTimeout() method is used to set the timeout period\nfor this Http2Session, the 'timeout' event is emitted if there is no\nactivity on the Http2Session after the configured number of milliseconds.\nIts listener does not expect any arguments.
session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n"
}
],
"properties": [
{
"textRaw": "Type: {string|undefined}",
"name": "alpnProtocol",
"type": "string|undefined",
"meta": {
"added": [
"v9.4.0"
],
"changes": []
},
"desc": "Value will be undefined if the Http2Session is not yet connected to a\nsocket, h2c if the Http2Session is not connected to a TLSSocket, or\nwill return the value of the connected TLSSocket's own alpnProtocol\nproperty.
Will be true if this Http2Session instance has been closed, otherwise\nfalse.
Will be true if this Http2Session instance is still connecting, will be set\nto false before emitting connect event and/or calling the http2.connect\ncallback.
Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.
Value is undefined if the Http2Session session socket has not yet been\nconnected, true if the Http2Session is connected with a TLSSocket,\nand false if the Http2Session is connected to any other kind of socket\nor stream.
A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.
If the Http2Session is connected to a TLSSocket, the originSet property\nwill return an Array of origins for which the Http2Session may be\nconsidered authoritative.
The originSet property is only available when using a secure TLS connection.
Indicates whether the Http2Session is currently waiting for acknowledgment of\na sent SETTINGS frame. Will be true after calling the\nhttp2session.settings() method. Will be false once all sent SETTINGS\nframes have been acknowledged.
A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.
Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\nlimits available methods to ones safe to use with HTTP/2.
destroy, emit, end, pause, read, resume, and write will throw\nan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See\nHttp2Session and Sockets for more information.
setTimeout method will be called on this Http2Session.
All other interactions will be routed directly to the socket.
" }, { "textRaw": "Type: {Object}", "name": "state", "type": "Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Provides miscellaneous information about the current state of the\nHttp2Session.
An object describing the current status of this Http2Session.
The http2session.type will be equal to\nhttp2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a\nserver, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a\nclient.
Gracefully closes the Http2Session, allowing any existing streams to\ncomplete on their own and preventing new Http2Stream instances from being\ncreated. Once closed, http2session.destroy() might be called if there\nare no open Http2Stream instances.
If specified, the callback function is registered as a handler for the\n'close' event.
Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.
Once destroyed, the Http2Session will emit the 'close' event. If error\nis not undefined, an 'error' event will be emitted immediately before the\n'close' event.
If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.
Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.
Sends a PING frame to the connected HTTP/2 peer. A callback function must\nbe provided. The method will return true if the PING was sent, false\notherwise.
The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.
If provided, the payload must be a Buffer, TypedArray, or DataView\ncontaining 8 bytes of data that will be transmitted with the PING and\nreturned with the ping acknowledgment.
The callback will be invoked with three arguments: an error argument that will\nbe null if the PING was successfully acknowledged, a duration argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a Buffer containing the 8-byte PING\npayload.
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {\n if (!err) {\n console.log(`Ping acknowledged in ${duration} milliseconds`);\n console.log(`With payload '${payload.toString()}'`);\n }\n});\n\nIf the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.
Calls ref() on this Http2Session\ninstance's underlying net.Socket.
Sets the local endpoint's window size.\nThe windowSize is the total window size to set, not\nthe delta.
import { createServer } from 'node:http2';\n\nconst server = createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('session', (session) => {\n\n // Set local window size to be 2 ** 20\n session.setLocalWindowSize(expectedWindowSize);\n});\n\nconst http2 = require('node:http2');\n\nconst server = http2.createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('session', (session) => {\n\n // Set local window size to be 2 ** 20\n session.setLocalWindowSize(expectedWindowSize);\n});\n\nFor http2 clients the proper event is either 'connect' or 'remoteSettings'.
Used to set a callback function that is called when there is no activity on\nthe Http2Session after msecs milliseconds. The given callback is\nregistered as a listener on the 'timeout' event.
Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.
Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.
The new settings will not become effective until the SETTINGS acknowledgment\nis received and the 'localSettings' event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.
Calls unref() on this Http2Session\ninstance's underlying net.Socket.
<Http2Session>Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.
import { createServer } from 'node:http2';\n\nconst server = createServer();\nserver.on('session', (session) => {\n // Set altsvc for origin https://example.org:80\n session.altsvc('h2=\":8000\"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n // Set altsvc for a specific stream\n stream.session.altsvc('h2=\":8000\"', stream.id);\n});\n\nconst http2 = require('node:http2');\n\nconst server = http2.createServer();\nserver.on('session', (session) => {\n // Set altsvc for origin https://example.org:80\n session.altsvc('h2=\":8000\"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n // Set altsvc for a specific stream\n stream.session.altsvc('h2=\":8000\"', stream.id);\n});\n\nSending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.
The alt and origin string must contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value 'clear'\nmay be passed to clear any previously set alternative service for a given\ndomain.
When a string is passed for the originOrStream argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL 'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.
A URL object, or any object with an origin property, may be passed as\noriginOrStream, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.
origins { string | URL | Object } One or more URL Strings passed as\nseparate arguments.Submits an ORIGIN frame (as defined by RFC 8336) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.
import { createSecureServer } from 'node:http2';\nconst options = getSecureOptionsSomehow();\nconst server = createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\nserver.on('session', (session) => {\n session.origin('https://example.com', 'https://example.org');\n});\n\nconst http2 = require('node:http2');\nconst options = getSecureOptionsSomehow();\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\nserver.on('session', (session) => {\n session.origin('https://example.com', 'https://example.org');\n});\n\nWhen a string is passed as an origin, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.
A URL object, or any object with an origin property, may be passed as\nan origin, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.
Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:
import { createSecureServer } from 'node:http2';\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\n\nconst http2 = require('node:http2');\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\n"
}
],
"modules": [
{
"textRaw": "Specifying alternative services",
"name": "specifying_alternative_services",
"type": "module",
"desc": "The format of the alt parameter is strictly defined by RFC 7838 as an\nASCII string containing a comma-delimited list of \"alternative\" protocols\nassociated with a specific host and port.
For example, the value 'h2=\"example.org:81\"' indicates that the HTTP/2\nprotocol is available on the host 'example.org' on TCP/IP port 81. The\nhost and port must be contained within the quote (\") characters.
Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.
The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.
The syntax of these values is not validated by the Node.js implementation and\nare passed through as provided by the user or received from the peer.
", "displayName": "Specifying alternative services" } ] }, { "textRaw": "Class: `ClientHttp2Session`", "name": "ClientHttp2Session", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<Http2Session>The 'altsvc' event is emitted whenever an ALTSVC frame is received by\nthe client. The event is emitted with the ALTSVC value, origin, and stream\nID. If no origin is provided in the ALTSVC frame, origin will\nbe an empty string.
import { connect } from 'node:http2';\nconst client = connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n console.log(alt);\n console.log(origin);\n console.log(streamId);\n});\n\nconst http2 = require('node:http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n console.log(alt);\n console.log(origin);\n console.log(streamId);\n});\n"
},
{
"textRaw": "Event: `'origin'`",
"name": "origin",
"type": "event",
"meta": {
"added": [
"v10.12.0"
],
"changes": []
},
"params": [
{
"textRaw": "`origins` {string[]}",
"name": "origins",
"type": "string[]"
}
],
"desc": "The 'origin' event is emitted whenever an ORIGIN frame is received by\nthe client. The event is emitted with an array of origin strings. The\nhttp2session.originSet will be updated to include the received\norigins.
import { connect } from 'node:http2';\nconst client = connect('https://example.org');\n\nclient.on('origin', (origins) => {\n for (let n = 0; n < origins.length; n++)\n console.log(origins[n]);\n});\n\nconst http2 = require('node:http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('origin', (origins) => {\n for (let n = 0; n < origins.length; n++)\n console.log(origins[n]);\n});\n\nThe 'origin' event is only emitted when using a secure TLS connection.
For HTTP/2 Client Http2Session instances only, the http2session.request()\ncreates and returns an Http2Stream instance that can be used to send an\nHTTP/2 request to the connected server.
When a ClientHttp2Session is first created, the socket may not yet be\nconnected. if clienthttp2session.request() is called during this time, the\nactual request will be deferred until the socket is ready to go.\nIf the session is closed before the actual request be executed, an\nERR_HTTP2_GOAWAY_SESSION is thrown.
This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.
import { connect, constants } from 'node:http2';\nconst clientSession = connect('https://localhost:1234');\nconst {\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n} = constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n console.log(headers[HTTP2_HEADER_STATUS]);\n req.on('data', (chunk) => { /* .. */ });\n req.on('end', () => { /* .. */ });\n});\n\nconst http2 = require('node:http2');\nconst clientSession = http2.connect('https://localhost:1234');\nconst {\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n} = http2.constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n console.log(headers[HTTP2_HEADER_STATUS]);\n req.on('data', (chunk) => { /* .. */ });\n req.on('end', () => { /* .. */ });\n});\n\nWhen the options.waitForTrailers option is set, the 'wantTrailers' event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe http2stream.sendTrailers() method can then be called to send trailing\nheaders to the peer.
When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.
When options.signal is set with an AbortSignal and then abort on the\ncorresponding AbortController is called, the request will emit an 'error'\nevent with an AbortError error.
The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:
:method = 'GET':path = /<stream.Duplex>Each instance of the Http2Stream class represents a bidirectional HTTP/2\ncommunications stream over an Http2Session instance. Any single Http2Session\nmay have up to 231-1 Http2Stream instances over its lifetime.
User code will not construct Http2Stream instances directly. Rather, these\nare created, managed, and provided to user code through the Http2Session\ninstance. On the server, Http2Stream instances are created either in response\nto an incoming HTTP request (and handed off to user code via the 'stream'\nevent), or in response to a call to the http2stream.pushStream() method.\nOn the client, Http2Stream instances are created and returned when either the\nhttp2session.request() method is called, or in response to an incoming\n'push' event.
The Http2Stream class is a base for the ServerHttp2Stream and\nClientHttp2Stream classes, each of which is used specifically by either\nthe Server or Client side, respectively.
All Http2Stream instances are Duplex streams. The Writable side of the\nDuplex is used to send data to the connected peer, while the Readable side\nis used to receive data sent by the connected peer.
The default text character encoding for an Http2Stream is UTF-8. When using an\nHttp2Stream to send text, use the 'content-type' header to set the character\nencoding.
stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n});\n",
"modules": [
{
"textRaw": "`Http2Stream` Lifecycle",
"name": "`http2stream`_lifecycle",
"type": "module",
"modules": [
{
"textRaw": "Creation",
"name": "creation",
"type": "module",
"desc": "On the server side, instances of ServerHttp2Stream are created either\nwhen:
HEADERS frame with a previously unused stream ID is received;http2stream.pushStream() method is called.On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.
On the client, the Http2Stream instance returned by http2session.request()\nmay not be immediately ready for use if the parent Http2Session has not yet\nbeen fully established. In such cases, operations called on the Http2Stream\nwill be buffered until the 'ready' event is emitted. User code should rarely,\nif ever, need to handle the 'ready' event directly. The ready status of an\nHttp2Stream can be determined by checking the value of http2stream.id. If\nthe value is undefined, the stream is not yet ready for use.
All Http2Stream instances are destroyed either when:
RST_STREAM frame for the stream is received by the connected peer,\nand (for client streams only) pending data has been read.http2stream.close() method is called, and (for client streams only)\npending data has been read.http2stream.destroy() or http2session.destroy() methods are called.When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.
When the Http2Stream instance is destroyed, the 'close' event will\nbe emitted. Because Http2Stream is an instance of stream.Duplex, the\n'end' event will also be emitted if the stream data is currently flowing.\nThe 'error' event may also be emitted if http2stream.destroy() was called\nwith an Error passed as the first argument.
After the Http2Stream has been destroyed, the http2stream.destroyed\nproperty will be true and the http2stream.rstCode property will specify the\nRST_STREAM error code. The Http2Stream instance is no longer usable once\ndestroyed.
The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.
The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.
The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.
The HTTP/2 error code used when closing the stream can be retrieved using\nthe http2stream.rstCode property. If the code is any value other than\nNGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.
The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.
The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame. When invoked, the handler function will receive an integer\nargument identifying the frame type, and an integer argument identifying the\nerror code. The Http2Stream instance will be destroyed immediately after the\n'frameError' event is emitted.
The 'ready' event is emitted when the Http2Stream has been opened, has\nbeen assigned an id, and can be used. The listener does not expect any\narguments.
The 'timeout' event is emitted after no activity is received for this\nHttp2Stream within the number of milliseconds set using\nhttp2stream.setTimeout().\nIts listener does not expect any arguments.
The 'trailers' event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\nHTTP/2 Headers Object and flags associated with the headers.
This event might not be emitted if http2stream.end() is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.
stream.on('trailers', (headers, flags) => {\n console.log(headers);\n});\n"
},
{
"textRaw": "Event: `'wantTrailers'`",
"name": "wantTrailers",
"type": "event",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"params": [],
"desc": "The 'wantTrailers' event is emitted when the Http2Stream has queued the\nfinal DATA frame to be sent on a frame and the Http2Stream is ready to send\ntrailing headers. When initiating a request or response, the waitForTrailers\noption must be set for this event to be emitted.
Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.
This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.
Set to true if the Http2Stream instance has been closed.
Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.
Set to true if the END_STREAM flag was set in the request or response\nHEADERS frame received, indicating that no additional data should be received\nand the readable side of the Http2Stream will be closed.
The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.
Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.
Set to the RST_STREAM error code reported when the Http2Stream is\ndestroyed after either receiving an RST_STREAM frame from the connected peer,\ncalling http2stream.close(), or http2stream.destroy(). Will be\nundefined if the Http2Stream has not been closed.
An object containing the outbound headers sent for this Http2Stream.
An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.
An object containing the outbound trailers sent for this HttpStream.
A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.
Provides miscellaneous information about the current state of the\nHttp2Stream.
A current state of this Http2Stream.
Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.
Empty method, only there to maintain some backward compatibility.
" }, { "textRaw": "`http2stream.setTimeout(msecs, callback)`", "name": "setTimeout", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "import { connect, constants } from 'node:http2';\nconst client = connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n\nconst http2 = require('node:http2');\nconst client = http2.connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = http2.constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n"
},
{
"textRaw": "`http2stream.sendTrailers(headers)`",
"name": "sendTrailers",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object"
}
]
}
],
"desc": "Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method\nwill cause the Http2Stream to be immediately closed and must only be\ncalled after the 'wantTrailers' event has been emitted. When sending a\nrequest or sending a response, the options.waitForTrailers option must be set\nin order to keep the Http2Stream open after the final DATA frame so that\ntrailers can be sent.
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n stream.respond(undefined, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ xyz: 'abc' });\n });\n stream.end('Hello World');\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond(undefined, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ xyz: 'abc' });\n });\n stream.end('Hello World');\n});\n\nThe HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).
<Http2Stream>The ClientHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Clients. Http2Stream instances on the client\nprovide events such as 'response' and 'push' that are only relevant on\nthe client.
Emitted when the server sends a 100 Continue status, usually because\nthe request contained Expect: 100-continue. This is an instruction that\nthe client should send the request body.
The 'headers' event is emitted when an additional block of headers is received\nfor a stream, such as when a block of 1xx informational headers is received.\nThe listener callback is passed the HTTP/2 Headers Object, flags associated\nwith the headers, and the headers in raw format (see HTTP/2 Raw Headers).
stream.on('headers', (headers, flags) => {\n console.log(headers);\n});\n"
},
{
"textRaw": "Event: `'push'`",
"name": "push",
"type": "event",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"params": [
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object"
},
{
"textRaw": "`flags` {number}",
"name": "flags",
"type": "number"
}
],
"desc": "The 'push' event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the HTTP/2 Headers Object and\nflags associated with the headers.
stream.on('push', (headers, flags) => {\n console.log(headers);\n});\n"
},
{
"textRaw": "Event: `'response'`",
"name": "response",
"type": "event",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"params": [
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object"
},
{
"textRaw": "`flags` {number}",
"name": "flags",
"type": "number"
},
{
"textRaw": "`rawHeaders` {HTTP/2 Raw Headers}",
"name": "rawHeaders",
"type": "HTTP/2 Raw Headers"
}
],
"desc": "The 'response' event is emitted when a response HEADERS frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with three arguments: an Object containing the received\nHTTP/2 Headers Object, flags associated with the headers, and the headers\nin raw format (see HTTP/2 Raw Headers).
import { connect } from 'node:http2';\nconst client = connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n console.log(headers[':status']);\n});\n\nconst http2 = require('node:http2');\nconst client = http2.connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n console.log(headers[':status']);\n});\n"
}
]
},
{
"textRaw": "Class: `ServerHttp2Stream`",
"name": "ServerHttp2Stream",
"type": "class",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "<Http2Stream>The ServerHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Servers. Http2Stream instances on the server\nprovide additional methods such as http2stream.pushStream() and\nhttp2stream.respond() that are only relevant on the server.
Sends an additional informational HEADERS frame to the connected HTTP/2 peer.
Initiates a push stream. The callback is invoked with the new Http2Stream\ninstance created for the push stream passed as the second argument, or an\nError passed as the first argument.
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n if (err) throw err;\n pushStream.respond({ ':status': 200 });\n pushStream.end('some pushed data');\n });\n stream.end('some data');\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n if (err) throw err;\n pushStream.respond({ ':status': 200 });\n pushStream.end('some pushed data');\n });\n stream.end('some data');\n});\n\nSetting the weight of a push stream is not allowed in the HEADERS frame. Pass\na weight value to http2stream.priority with the silent option set to\ntrue to enable server-side bandwidth balancing between concurrent streams.
Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.end('some data');\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.end('some data');\n});\n\nInitiates a response. When the options.waitForTrailers option is set, the\n'wantTrailers' event will be emitted immediately after queuing the last chunk\nof payload data to be sent. The http2stream.sendTrailers() method can then be\nused to sent trailing header fields to the peer.
When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 }, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n stream.end('some data');\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 }, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n stream.end('some data');\n});\n"
},
{
"textRaw": "`http2stream.respondWithFD(fd[, headers[, options]])`",
"name": "respondWithFD",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": [
"v14.5.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/33160",
"description": "Allow explicitly setting date headers."
},
{
"version": "v12.12.0",
"pr-url": "https://github.com/nodejs/node/pull/29876",
"description": "The `fd` option may now be a `FileHandle`."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18936",
"description": "Any readable file descriptor, not necessarily for a regular file, is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`fd` {number|FileHandle} A readable file descriptor.",
"name": "fd",
"type": "number|FileHandle",
"desc": "A readable file descriptor."
},
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`statCheck` {Function}",
"name": "statCheck",
"type": "Function"
},
{
"textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.",
"name": "waitForTrailers",
"type": "boolean",
"desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent."
},
{
"textRaw": "`offset` {number} The offset position at which to begin reading.",
"name": "offset",
"type": "number",
"desc": "The offset position at which to begin reading."
},
{
"textRaw": "`length` {number} The amount of data from the fd to send.",
"name": "length",
"type": "number",
"desc": "The amount of data from the fd to send."
}
],
"optional": true
}
]
}
],
"desc": "Initiates a response whose data is read from the given file descriptor. No\nvalidation is performed on the given file descriptor. If an error occurs while\nattempting to read data using the file descriptor, the Http2Stream will be\nclosed using an RST_STREAM frame using the standard INTERNAL_ERROR code.
When used, the Http2Stream object's Duplex interface will be closed\nautomatically.
import { createServer } from 'node:http2';\nimport { openSync, fstatSync, closeSync } from 'node:fs';\n\nconst server = createServer();\nserver.on('stream', (stream) => {\n const fd = openSync('/some/file', 'r');\n\n const stat = fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8',\n };\n stream.respondWithFD(fd, headers);\n stream.on('close', () => closeSync(fd));\n});\n\nconst http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8',\n };\n stream.respondWithFD(fd, headers);\n stream.on('close', () => fs.closeSync(fd));\n});\n\nThe optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given fd. If the statCheck function is provided, the\nhttp2stream.respondWithFD() method will perform an fs.fstat() call to\ncollect details on the provided file descriptor.
The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.
The file descriptor or FileHandle is not closed when the stream is closed,\nso it will need to be closed manually once it is no longer needed.\nUsing the same file descriptor concurrently for multiple streams\nis not supported and may result in data loss. Re-using a file descriptor\nafter a stream has finished is supported.
When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.
When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.
import { createServer } from 'node:http2';\nimport { openSync, fstatSync, closeSync } from 'node:fs';\n\nconst server = createServer();\nserver.on('stream', (stream) => {\n const fd = openSync('/some/file', 'r');\n\n const stat = fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8',\n };\n stream.respondWithFD(fd, headers, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n\n stream.on('close', () => closeSync(fd));\n});\n\nconst http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8',\n };\n stream.respondWithFD(fd, headers, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n\n stream.on('close', () => fs.closeSync(fd));\n});\n"
},
{
"textRaw": "`http2stream.respondWithFile(path[, headers[, options]])`",
"name": "respondWithFile",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": [
"v14.5.0",
"v12.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/33160",
"description": "Allow explicitly setting date headers."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18936",
"description": "Any readable file, not necessarily a regular file, is supported now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string|Buffer|URL}",
"name": "path",
"type": "string|Buffer|URL"
},
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`statCheck` {Function}",
"name": "statCheck",
"type": "Function"
},
{
"textRaw": "`onError` {Function} Callback function invoked in the case of an error before send.",
"name": "onError",
"type": "Function",
"desc": "Callback function invoked in the case of an error before send."
},
{
"textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.",
"name": "waitForTrailers",
"type": "boolean",
"desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent."
},
{
"textRaw": "`offset` {number} The offset position at which to begin reading.",
"name": "offset",
"type": "number",
"desc": "The offset position at which to begin reading."
},
{
"textRaw": "`length` {number} The amount of data from the fd to send.",
"name": "length",
"type": "number",
"desc": "The amount of data from the fd to send."
}
],
"optional": true
}
]
}
],
"desc": "Sends a regular file as the response. The path must specify a regular file\nor an 'error' event will be emitted on the Http2Stream object.
When used, the Http2Stream object's Duplex interface will be closed\nautomatically.
The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given file:
If an error occurs while attempting to read the file data, the Http2Stream\nwill be closed using an RST_STREAM frame using the standard INTERNAL_ERROR\ncode. If the onError callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.
Example using a file path:
\nimport { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n headers['last-modified'] = stat.mtime.toUTCString();\n }\n\n function onError(err) {\n // stream.respond() can throw if the stream has been destroyed by\n // the other side.\n try {\n if (err.code === 'ENOENT') {\n stream.respond({ ':status': 404 });\n } else {\n stream.respond({ ':status': 500 });\n }\n } catch (err) {\n // Perform actual error handling.\n console.error(err);\n }\n stream.end();\n }\n\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck, onError });\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n headers['last-modified'] = stat.mtime.toUTCString();\n }\n\n function onError(err) {\n // stream.respond() can throw if the stream has been destroyed by\n // the other side.\n try {\n if (err.code === 'ENOENT') {\n stream.respond({ ':status': 404 });\n } else {\n stream.respond({ ':status': 500 });\n }\n } catch (err) {\n // Perform actual error handling.\n console.error(err);\n }\n stream.end();\n }\n\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck, onError });\n});\n\nThe options.statCheck function may also be used to cancel the send operation\nby returning false. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n304 response:
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n // Check the stat here...\n stream.respond({ ':status': 304 });\n return false; // Cancel the send operation\n }\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck });\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n // Check the stat here...\n stream.respond({ ':status': 304 });\n return false; // Cancel the send operation\n }\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck });\n});\n\nThe content-length header field will be automatically set.
The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.
The options.onError function may also be used to handle all the errors\nthat could happen before the delivery of the file is initiated. The\ndefault behavior is to destroy the stream.
When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.
When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n});\n"
}
],
"properties": [
{
"textRaw": "Type: {boolean}",
"name": "headersSent",
"type": "boolean",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "True if headers were sent, false otherwise (read-only).
" }, { "textRaw": "Type: {boolean}", "name": "pushAllowed", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote\nclient's most recent SETTINGS frame. Will be true if the remote peer\naccepts push streams, false otherwise. Settings are the same for every\nHttp2Stream in the same Http2Session.
<net.Server>Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the\nnode:http2 module.
If a 'request' listener is registered or http2.createServer() is\nsupplied a callback function, the 'checkContinue' event is emitted each time\na request with an HTTP Expect: 100-continue is received. If this event is\nnot listened for, the server will automatically respond with a status\n100 Continue as appropriate.
Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event.
This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.
Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.
" }, { "textRaw": "Event: `'session'`", "name": "session", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.
The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.
The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.
See also Http2Session's 'stream' event.
import { createServer, constants } from 'node:http2';\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE,\n} = constants;\n\nconst server = createServer();\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',\n });\n stream.write('hello ');\n stream.end('world');\n});\n\nconst http2 = require('node:http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE,\n} = http2.constants;\n\nconst server = http2.createServer();\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',\n });\n stream.write('hello ');\n stream.end('world');\n});\n"
},
{
"textRaw": "Event: `'timeout'`",
"name": "timeout",
"type": "event",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v13.0.0",
"pr-url": "https://github.com/nodejs/node/pull/27558",
"description": "The default timeout changed from 120s to 0 (no timeout)."
}
]
},
"params": [],
"desc": "The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().\nDefault: 0 (no timeout)
Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.
If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\nnet.Server.close() for more details.
Calls server.close() and returns a promise that fulfills when the\nserver has closed.
Used to set the timeout value for http2 server requests,\nand sets a callback function that is called when there is no activity\non the Http2Server after msecs milliseconds.
The given callback is registered as a listener on the 'timeout' event.
In case if callback is not a function, a new ERR_INVALID_ARG_TYPE\nerror will be thrown.
Used to update the server with the provided settings.
\nThrows ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.
Throws ERR_INVALID_ARG_TYPE for invalid settings argument.
The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nA value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." } ] }, { "textRaw": "Class: `Http2SecureServer`", "name": "Http2SecureServer", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "<tls.Server>Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the node:http2 module.
If a 'request' listener is registered or http2.createSecureServer()\nis supplied a callback function, the 'checkContinue' event is emitted each\ntime a request with an HTTP Expect: 100-continue is received. If this event\nis not listened for, the server will automatically respond with a status\n100 Continue as appropriate.
Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.
This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.
Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.
" }, { "textRaw": "Event: `'session'`", "name": "session", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.
The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.
The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.
See also Http2Session's 'stream' event.
import { createSecureServer, constants } from 'node:http2';\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE,\n} = constants;\n\nconst options = getOptionsSomehow();\n\nconst server = createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',\n });\n stream.write('hello ');\n stream.end('world');\n});\n\nconst http2 = require('node:http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE,\n} = http2.constants;\n\nconst options = getOptionsSomehow();\n\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',\n });\n stream.write('hello ');\n stream.end('world');\n});\n"
},
{
"textRaw": "Event: `'timeout'`",
"name": "timeout",
"type": "event",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"params": [],
"desc": "The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 2 minutes.
The 'unknownProtocol' event is emitted when a connecting client fails to\nnegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler\nreceives the socket for handling. If no listener is registered for this event,\nthe connection is terminated. A timeout may be specified using the\n'unknownProtocolTimeout' option passed to http2.createSecureServer().
In earlier versions of Node.js, this event would be emitted if allowHTTP1 is\nfalse and, during the TLS handshake, the client either does not send an ALPN\nextension or sends an ALPN extension that does not include HTTP/2 (h2). Newer\nversions of Node.js only emit this event if allowHTTP1 is false and the\nclient does not send an ALPN extension. If the client sends an ALPN extension\nthat does not include HTTP/2 (or HTTP/1.1 if allowHTTP1 is true), the TLS\nhandshake will fail and no secure connection will be established.
See the Compatibility API.
" } ], "methods": [ { "textRaw": "`server.close([callback])`", "name": "close", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.
If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\ntls.Server.close() for more details.
Used to set the timeout value for http2 secure server requests,\nand sets a callback function that is called when there is no activity\non the Http2SecureServer after msecs milliseconds.
The given callback is registered as a listener on the 'timeout' event.
In case if callback is not a function, a new ERR_INVALID_ARG_TYPE\nerror will be thrown.
Used to update the server with the provided settings.
\nThrows ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.
Throws ERR_INVALID_ARG_TYPE for invalid settings argument.
The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nA value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." } ] } ], "methods": [ { "textRaw": "`http2.createServer([options][, onRequestHandler])`", "name": "createServer", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/59917", "description": "Added the `strictSingleValueFields` option." }, { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/61713", "description": "Added `http1Options` option. The `Http1IncomingMessage` and `Http1ServerResponse` options are now deprecated." }, { "version": [ "v23.0.0", "v22.10.0" ], "pr-url": "https://github.com/nodejs/node/pull/54875", "description": "Added `streamResetBurst` and `streamResetRate`." }, { "version": [ "v15.10.0", "v14.16.0", "v12.21.0", "v10.24.0" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/246", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": [ "v14.4.0", "v12.18.0", "v10.21.0" ], "commit": "3948830ce6408be620b09a70bf66158623022af0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionRejectedStreams` option with a default of 100." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionInvalidFrames` option with a default of 1000." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29144", "description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed." }, { "version": "v12.4.0", "pr-url": "https://github.com/nodejs/node/pull/27782", "description": "The `options` parameter now supports `net.createServer()` options." }, { "version": "v9.6.0", "pr-url": "https://github.com/nodejs/node/pull/15752", "description": "Added the `Http1IncomingMessage` and `Http1ServerResponse` option." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." }, { "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. While this sets the maximum allowed size to the entire block of headers, `nghttp2` (the internal http2 library) has a limit of `65536` for each decompressed key/value pair.", "name": "maxSendHeaderBlockLength", "type": "number", "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. While this sets the maximum allowed size to the entire block of headers, `nghttp2` (the internal http2 library) has a limit of `65536` for each decompressed key/value pair." }, { "textRaw": "`paddingStrategy` {number} The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "options": [ { "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.", "name": "http2.constants.PADDING_STRATEGY_NONE", "desc": "No padding is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.", "name": "http2.constants.PADDING_STRATEGY_MAX", "desc": "The maximum amount of padding, determined by the internal implementation, is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.", "name": "http2.constants.PADDING_STRATEGY_ALIGNED", "desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes." } ] }, { "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", "name": "peerMaxConcurrentStreams", "type": "number", "default": "`100`", "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." }, { "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", "name": "maxSessionInvalidFrames", "type": "integer", "default": "`1000`", "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." }, { "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", "name": "maxSessionRejectedStreams", "type": "integer", "default": "`100`", "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." }, { "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The initial settings to send to the remote peer upon connection." }, { "textRaw": "`streamResetBurst` {number} and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively.", "name": "streamResetBurst", "type": "number", "desc": "and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively." }, { "textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.", "name": "remoteCustomSettings", "type": "Array", "desc": "The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types." }, { "textRaw": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`. **Deprecated.** Use `http1Options.IncomingMessage` instead. See DEP0202.", "name": "Http1IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`. **Deprecated.** Use `http1Options.IncomingMessage` instead. See DEP0202", "desc": "Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`." }, { "textRaw": "`Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`. **Deprecated.** Use `http1Options.ServerResponse` instead. See DEP0202.", "name": "Http1ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`. **Deprecated.** Use `http1Options.ServerResponse` instead. See DEP0202", "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." }, { "textRaw": "`http1Options` {Object} An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "name": "http1Options", "type": "Object", "desc": "An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "options": [ { "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to use for HTTP/1 fallback. **Default:** `http.IncomingMessage`.", "name": "IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`", "desc": "Specifies the `IncomingMessage` class to use for HTTP/1 fallback." }, { "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to use for HTTP/1 fallback. **Default:** `http.ServerResponse`.", "name": "ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`", "desc": "Specifies the `ServerResponse` class to use for HTTP/1 fallback." }, { "textRaw": "`keepAliveTimeout` {number} The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. **Default:** `5000`.", "name": "keepAliveTimeout", "type": "number", "default": "`5000`", "desc": "The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed." } ] }, { "textRaw": "`Http2ServerRequest` {http2.Http2ServerRequest} Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`.", "name": "Http2ServerRequest", "type": "http2.Http2ServerRequest", "default": "`Http2ServerRequest`", "desc": "Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`." }, { "textRaw": "`Http2ServerResponse` {http2.Http2ServerResponse} Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`.", "name": "Http2ServerResponse", "type": "http2.Http2ServerResponse", "default": "`Http2ServerResponse`", "desc": "Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`." }, { "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` is emitted. If the socket has not been destroyed by that time the server will destroy it." }, { "textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.", "name": "strictFieldWhitespaceValidation", "type": "boolean", "default": "`true`", "desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113." }, { "textRaw": "`strictSingleValueFields` {boolean} If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided. **Default:** `true`.", "name": "strictSingleValueFields", "type": "boolean", "default": "`true`", "desc": "If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided." }, { "textRaw": "`...options` {Object} Any `net.createServer()` option can be provided.", "name": "...options", "type": "Object", "desc": "Any `net.createServer()` option can be provided." } ], "optional": true }, { "textRaw": "`onRequestHandler` {Function} See Compatibility API", "name": "onRequestHandler", "type": "Function", "desc": "See Compatibility API", "optional": true } ], "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" } } ], "desc": "Returns a net.Server instance that creates and manages Http2Session\ninstances.
Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.
import { createServer } from 'node:http2';\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8000);\n\nconst http2 = require('node:http2');\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `http2.createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8000);\n"
},
{
"textRaw": "`http2.createSecureServer(options[, onRequestHandler])`",
"name": "createSecureServer",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v25.7.0",
"pr-url": "https://github.com/nodejs/node/pull/59917",
"description": "Added the `strictSingleValueFields` option."
},
{
"version": "v25.7.0",
"pr-url": "https://github.com/nodejs/node/pull/61713",
"description": "Added `http1Options` option."
},
{
"version": [
"v15.10.0",
"v14.16.0",
"v12.21.0",
"v10.24.0"
],
"pr-url": "https://github.com/nodejs-private/node-private/pull/246",
"description": "Added `unknownProtocolTimeout` option with a default of 10000."
},
{
"version": [
"v14.4.0",
"v12.18.0",
"v10.21.0"
],
"commit": "3948830ce6408be620b09a70bf66158623022af0",
"pr-url": "https://github.com/nodejs-private/node-private/pull/204",
"description": "Added `maxSettings` option with a default of 32."
},
{
"version": [
"v13.3.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30534",
"description": "Added `maxSessionRejectedStreams` option with a default of 100."
},
{
"version": [
"v13.3.0",
"v12.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30534",
"description": "Added `maxSessionInvalidFrames` option with a default of 1000."
},
{
"version": "v13.0.0",
"pr-url": "https://github.com/nodejs/node/pull/29144",
"description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed."
},
{
"version": "v10.12.0",
"pr-url": "https://github.com/nodejs/node/pull/22956",
"description": "Added the `origins` option to automatically send an `ORIGIN` frame on `Http2Session` startup."
},
{
"version": "v8.9.3",
"pr-url": "https://github.com/nodejs/node/pull/17105",
"description": "Added the `maxOutstandingPings` option with a default limit of 10."
},
{
"version": "v8.9.3",
"pr-url": "https://github.com/nodejs/node/pull/16676",
"description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the `'unknownProtocol'` event. See ALPN negotiation. **Default:** `false`.",
"name": "allowHTTP1",
"type": "boolean",
"default": "`false`",
"desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the `'unknownProtocol'` event. See ALPN negotiation."
},
{
"textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.",
"name": "maxDeflateDynamicTableSize",
"type": "number",
"default": "`4Kib`",
"desc": "Sets the maximum dynamic table size for deflating header fields."
},
{
"textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.",
"name": "maxSettings",
"type": "number",
"default": "`32`",
"desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`."
},
{
"textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.",
"name": "maxSessionMemory",
"type": "number",
"default": "`10`",
"desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit."
},
{
"textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`. **Default:** `128`.",
"name": "maxHeaderListPairs",
"type": "number",
"default": "`128`",
"desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`."
},
{
"textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.",
"name": "maxOutstandingPings",
"type": "number",
"default": "`10`",
"desc": "Sets the maximum number of outstanding, unacknowledged pings."
},
{
"textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.",
"name": "maxSendHeaderBlockLength",
"type": "number",
"desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed."
},
{
"textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:",
"name": "paddingStrategy",
"type": "number",
"default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:",
"desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.",
"options": [
{
"textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.",
"name": "http2.constants.PADDING_STRATEGY_NONE",
"desc": "No padding is applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.",
"name": "http2.constants.PADDING_STRATEGY_MAX",
"desc": "The maximum amount of padding, determined by the internal implementation, is applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.",
"name": "http2.constants.PADDING_STRATEGY_ALIGNED",
"desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes."
}
]
},
{
"textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.",
"name": "peerMaxConcurrentStreams",
"type": "number",
"default": "`100`",
"desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`."
},
{
"textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.",
"name": "maxSessionInvalidFrames",
"type": "integer",
"default": "`1000`",
"desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed."
},
{
"textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.",
"name": "maxSessionRejectedStreams",
"type": "integer",
"default": "`100`",
"desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer."
},
{
"textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.",
"name": "settings",
"type": "HTTP/2 Settings Object",
"desc": "The initial settings to send to the remote peer upon connection."
},
{
"textRaw": "`streamResetBurst` {number} and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively.",
"name": "streamResetBurst",
"type": "number",
"desc": "and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively."
},
{
"textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `customSettings`-property of the received remoteSettings. Please see the `customSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.",
"name": "remoteCustomSettings",
"type": "Array",
"desc": "The array of integer values determines the settings types, which are included in the `customSettings`-property of the received remoteSettings. Please see the `customSettings`-property of the `Http2Settings` object for more information, on the allowed setting types."
},
{
"textRaw": "`...options` {Object} Any `tls.createServer()` options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required.",
"name": "...options",
"type": "Object",
"desc": "Any `tls.createServer()` options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required."
},
{
"textRaw": "`origins` {string[]} An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`.",
"name": "origins",
"type": "string[]",
"desc": "An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`."
},
{
"textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.",
"name": "unknownProtocolTimeout",
"type": "number",
"default": "`10000`",
"desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it."
},
{
"textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.",
"name": "strictFieldWhitespaceValidation",
"type": "boolean",
"default": "`true`",
"desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113."
},
{
"textRaw": "`strictSingleValueFields` {boolean} If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided. **Default:** `true`.",
"name": "strictSingleValueFields",
"type": "boolean",
"default": "`true`",
"desc": "If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided."
},
{
"textRaw": "`http1Options` {Object} An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:",
"name": "http1Options",
"type": "Object",
"desc": "An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:",
"options": [
{
"textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to use for HTTP/1 fallback. **Default:** `http.IncomingMessage`.",
"name": "IncomingMessage",
"type": "http.IncomingMessage",
"default": "`http.IncomingMessage`",
"desc": "Specifies the `IncomingMessage` class to use for HTTP/1 fallback."
},
{
"textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to use for HTTP/1 fallback. **Default:** `http.ServerResponse`.",
"name": "ServerResponse",
"type": "http.ServerResponse",
"default": "`http.ServerResponse`",
"desc": "Specifies the `ServerResponse` class to use for HTTP/1 fallback."
},
{
"textRaw": "`keepAliveTimeout` {number} The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. **Default:** `5000`.",
"name": "keepAliveTimeout",
"type": "number",
"default": "`5000`",
"desc": "The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed."
}
]
}
]
},
{
"textRaw": "`onRequestHandler` {Function} See Compatibility API",
"name": "onRequestHandler",
"type": "Function",
"desc": "See Compatibility API",
"optional": true
}
],
"return": {
"textRaw": "Returns: {Http2SecureServer}",
"name": "return",
"type": "Http2SecureServer"
}
}
],
"desc": "Returns a tls.Server instance that creates and manages Http2Session\ninstances.
import { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst options = {\n key: readFileSync('server-key.pem'),\n cert: readFileSync('server-cert.pem'),\n};\n\n// Create a secure HTTP/2 server\nconst server = createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n\nconst http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst options = {\n key: fs.readFileSync('server-key.pem'),\n cert: fs.readFileSync('server-cert.pem'),\n};\n\n// Create a secure HTTP/2 server\nconst server = http2.createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200,\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n"
},
{
"textRaw": "`http2.connect(authority[, options][, listener])`",
"name": "connect",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": [
"v15.10.0",
"v14.16.0",
"v12.21.0",
"v10.24.0"
],
"pr-url": "https://github.com/nodejs-private/node-private/pull/246",
"description": "Added `unknownProtocolTimeout` option with a default of 10000."
},
{
"version": [
"v14.4.0",
"v12.18.0",
"v10.21.0"
],
"commit": "3948830ce6408be620b09a70bf66158623022af0",
"pr-url": "https://github.com/nodejs-private/node-private/pull/204",
"description": "Added `maxSettings` option with a default of 32."
},
{
"version": "v13.0.0",
"pr-url": "https://github.com/nodejs/node/pull/29144",
"description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed."
},
{
"version": "v8.9.3",
"pr-url": "https://github.com/nodejs/node/pull/17105",
"description": "Added the `maxOutstandingPings` option with a default limit of 10."
},
{
"version": "v8.9.3",
"pr-url": "https://github.com/nodejs/node/pull/16676",
"description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`authority` {string|URL} The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored.",
"name": "authority",
"type": "string|URL",
"desc": "The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.",
"name": "maxDeflateDynamicTableSize",
"type": "number",
"default": "`4Kib`",
"desc": "Sets the maximum dynamic table size for deflating header fields."
},
{
"textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.",
"name": "maxSettings",
"type": "number",
"default": "`32`",
"desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`."
},
{
"textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.",
"name": "maxSessionMemory",
"type": "number",
"default": "`10`",
"desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit."
},
{
"textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `1`. **Default:** `128`.",
"name": "maxHeaderListPairs",
"type": "number",
"default": "`128`",
"desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `1`."
},
{
"textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.",
"name": "maxOutstandingPings",
"type": "number",
"default": "`10`",
"desc": "Sets the maximum number of outstanding, unacknowledged pings."
},
{
"textRaw": "`maxReservedRemoteStreams` {number} Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value. **Default:** `200`.",
"name": "maxReservedRemoteStreams",
"type": "number",
"default": "`200`",
"desc": "Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value."
},
{
"textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.",
"name": "maxSendHeaderBlockLength",
"type": "number",
"desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed."
},
{
"textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:",
"name": "paddingStrategy",
"type": "number",
"default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:",
"desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.",
"options": [
{
"textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.",
"name": "http2.constants.PADDING_STRATEGY_NONE",
"desc": "No padding is applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.",
"name": "http2.constants.PADDING_STRATEGY_MAX",
"desc": "The maximum amount of padding, determined by the internal implementation, is applied."
},
{
"textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.",
"name": "http2.constants.PADDING_STRATEGY_ALIGNED",
"desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes."
}
]
},
{
"textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.",
"name": "peerMaxConcurrentStreams",
"type": "number",
"default": "`100`",
"desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`."
},
{
"textRaw": "`protocol` {string} The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`. **Default:** `'https:'`",
"name": "protocol",
"type": "string",
"default": "`'https:'`",
"desc": "The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`."
},
{
"textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.",
"name": "settings",
"type": "HTTP/2 Settings Object",
"desc": "The initial settings to send to the remote peer upon connection."
},
{
"textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.",
"name": "remoteCustomSettings",
"type": "Array",
"desc": "The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types."
},
{
"textRaw": "`createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any `Duplex` stream that is to be used as the connection for this session.",
"name": "createConnection",
"type": "Function",
"desc": "An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any `Duplex` stream that is to be used as the connection for this session."
},
{
"textRaw": "`...options` {Object} Any `net.connect()` or `tls.connect()` options can be provided.",
"name": "...options",
"type": "Object",
"desc": "Any `net.connect()` or `tls.connect()` options can be provided."
},
{
"textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.",
"name": "unknownProtocolTimeout",
"type": "number",
"default": "`10000`",
"desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it."
},
{
"textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.",
"name": "strictFieldWhitespaceValidation",
"type": "boolean",
"default": "`true`",
"desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113."
}
],
"optional": true
},
{
"textRaw": "`listener` {Function} Will be registered as a one-time listener of the `'connect'` event.",
"name": "listener",
"type": "Function",
"desc": "Will be registered as a one-time listener of the `'connect'` event.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {ClientHttp2Session}",
"name": "return",
"type": "ClientHttp2Session"
}
}
],
"desc": "Returns a ClientHttp2Session instance.
import { connect } from 'node:http2';\nconst client = connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n\nconst http2 = require('node:http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n"
},
{
"textRaw": "`http2.getDefaultSettings()`",
"name": "getDefaultSettings",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {HTTP/2 Settings Object}",
"name": "return",
"type": "HTTP/2 Settings Object"
}
}
],
"desc": "Returns an object containing the default settings for an Http2Session\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.
Returns a Buffer instance containing serialized representation of the given\nHTTP/2 settings as specified in the HTTP/2 specification. This is intended\nfor use with the HTTP2-Settings header field.
import { getPackedSettings } from 'node:http2';\n\nconst packed = getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n\nconst http2 = require('node:http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n"
},
{
"textRaw": "`http2.getUnpackedSettings(buf)`",
"name": "getUnpackedSettings",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`buf` {Buffer|TypedArray} The packed settings.",
"name": "buf",
"type": "Buffer|TypedArray",
"desc": "The packed settings."
}
],
"return": {
"textRaw": "Returns: {HTTP/2 Settings Object}",
"name": "return",
"type": "HTTP/2 Settings Object"
}
}
],
"desc": "Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().
Create an HTTP/2 server session from an existing socket.
" } ], "properties": [ { "textRaw": "`http2.constants`", "name": "constants", "type": "property", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "modules": [ { "textRaw": "Error codes for `RST_STREAM` and `GOAWAY`", "name": "error_codes_for_`rst_stream`_and_`goaway`", "type": "module", "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n| Value | Name | Constant |
|---|---|---|
0x00 | No Error | http2.constants.NGHTTP2_NO_ERROR |
0x01 | Protocol Error | http2.constants.NGHTTP2_PROTOCOL_ERROR |
0x02 | Internal Error | http2.constants.NGHTTP2_INTERNAL_ERROR |
0x03 | Flow Control Error | http2.constants.NGHTTP2_FLOW_CONTROL_ERROR |
0x04 | Settings Timeout | http2.constants.NGHTTP2_SETTINGS_TIMEOUT |
0x05 | Stream Closed | http2.constants.NGHTTP2_STREAM_CLOSED |
0x06 | Frame Size Error | http2.constants.NGHTTP2_FRAME_SIZE_ERROR |
0x07 | Refused Stream | http2.constants.NGHTTP2_REFUSED_STREAM |
0x08 | Cancel | http2.constants.NGHTTP2_CANCEL |
0x09 | Compression Error | http2.constants.NGHTTP2_COMPRESSION_ERROR |
0x0a | Connect Error | http2.constants.NGHTTP2_CONNECT_ERROR |
0x0b | Enhance Your Calm | http2.constants.NGHTTP2_ENHANCE_YOUR_CALM |
0x0c | Inadequate Security | http2.constants.NGHTTP2_INADEQUATE_SECURITY |
0x0d | HTTP/1.1 Required | http2.constants.NGHTTP2_HTTP_1_1_REQUIRED |
The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().
This symbol can be set as a property on the HTTP/2 headers object with an array\nvalue in order to provide a list of headers considered sensitive.\nSee Sensitive headers for more details.
" } ], "displayName": "Core API" }, { "textRaw": "Compatibility API", "name": "compatibility_api", "type": "module", "desc": "The Compatibility API has the goal of providing a similar developer experience\nof HTTP/1 when using HTTP/2, making it possible to develop applications\nthat support both HTTP/1 and HTTP/2. This API targets only the\npublic API of the HTTP/1. However many modules use internal\nmethods or state, and those are not supported as it is a completely\ndifferent implementation.
\nThe following example creates an HTTP/2 server using the compatibility\nAPI:
\nimport { createServer } from 'node:http2';\nconst server = createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n\nconst http2 = require('node:http2');\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n\nIn order to create a mixed HTTPS and HTTP/2 server, refer to the\nALPN negotiation section.\nUpgrading from non-tls HTTP/1 servers is not supported.
\nThe HTTP/2 compatibility API is composed of Http2ServerRequest and\nHttp2ServerResponse. They aim at API compatibility with HTTP/1, but\nthey do not hide the differences between the protocols. As an example,\nthe status message for HTTP codes is ignored.
ALPN negotiation allows supporting both HTTPS and HTTP/2 over\nthe same socket. The req and res objects can be either HTTP/1 or\nHTTP/2, and an application must restrict itself to the public API of\nHTTP/1, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.
The following example creates a server that supports both protocols:
\nimport { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n { cert, key, allowHTTP1: true },\n onRequest,\n).listen(8000);\n\nfunction onRequest(req, res) {\n // Detects if it is a HTTPS request or HTTP/2\n const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n req.stream.session : req;\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({\n alpnProtocol,\n httpVersion: req.httpVersion,\n }));\n}\n\nconst { createSecureServer } = require('node:http2');\nconst { readFileSync } = require('node:fs');\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n { cert, key, allowHTTP1: true },\n onRequest,\n).listen(4443);\n\nfunction onRequest(req, res) {\n // Detects if it is a HTTPS request or HTTP/2\n const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n req.stream.session : req;\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({\n alpnProtocol,\n httpVersion: req.httpVersion,\n }));\n}\n\nThe 'request' event works identically on both HTTPS and\nHTTP/2.
<stream.Readable>A Http2ServerRequest object is created by http2.Server or\nhttp2.SecureServer and passed as the first argument to the\n'request' event. It may be used to access a request status, headers, and\ndata.
The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.
The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.
Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.
The request.aborted property will be true if the request has\nbeen aborted.
The request authority pseudo header field. Because HTTP/2 allows requests\nto set either :authority or host, this value is derived from\nreq.headers[':authority'] if present. Otherwise, it is derived from\nreq.headers['host'].
The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.
See request.socket.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n\n\nIn HTTP/2, the request path, host name, protocol, and method are represented as\nspecial headers prefixed with the : character (e.g. ':path'). These special\nheaders will be included in the request.headers object. Care must be taken not\nto inadvertently modify these special headers or errors may occur. For instance,\nremoving all headers from the request will cause errors to occur:
removeAllHeaders(request.headers);\nassert(request.url); // Fails because the :path header has been removed\n"
},
{
"textRaw": "Type: {string}",
"name": "httpVersion",
"type": "string",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server. Returns\n'2.0'.
Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.
The request method as a string. Read-only. Examples: 'GET', 'DELETE'.
The raw request/response headers list exactly as they were received.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n"
},
{
"textRaw": "Type: {string[]}",
"name": "rawTrailers",
"type": "string[]",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.
The request scheme pseudo header field indicating the scheme\nportion of the target URL.
" }, { "textRaw": "Type: {net.Socket|tls.TLSSocket}", "name": "socket", "type": "net.Socket|tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.
destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.
destroy, emit, end, on and once methods will be called on\nrequest.stream.
setTimeout method will be called on request.stream.session.
pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.
All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.
The Http2Stream object backing the request.
The request/response trailers object. Only populated at the 'end' event.
Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:
\nGET /status?name=ryan HTTP/1.1\nAccept: text/plain\n\nThen request.url will be:
'/status?name=ryan'\n\nTo parse the url into its parts, new URL() can be used:
$ node\n> new URL('/status?name=ryan', 'http://example.com')\nURL {\n href: 'http://example.com/status?name=ryan',\n origin: 'http://example.com',\n protocol: 'http:',\n username: '',\n password: '',\n host: 'example.com',\n hostname: 'example.com',\n port: '',\n pathname: '/status',\n search: '?name=ryan',\n searchParams: URLSearchParams { 'name' => 'ryan' },\n hash: ''\n}\n"
}
],
"methods": [
{
"textRaw": "`request.destroy([error])`",
"name": "destroy",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`error` {Error}",
"name": "error",
"type": "Error",
"optional": true
}
]
}
],
"desc": "Calls destroy() on the Http2Stream that received\nthe Http2ServerRequest. If error is provided, an 'error' event\nis emitted and error is passed as an argument to any listeners on the event.
It does nothing if the stream was already destroyed.
" }, { "textRaw": "`request.setTimeout(msecs, callback)`", "name": "setTimeout", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ], "return": { "textRaw": "Returns: {http2.Http2ServerRequest}", "name": "return", "type": "http2.Http2ServerRequest" } } ], "desc": "Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.
If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.
<Stream>This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.
Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.
Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.
\nAfter this event, no more events will be emitted on the response object.
" } ], "methods": [ { "textRaw": "`response.addTrailers(headers)`", "name": "addTrailers", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
Append a single header value to the header object.
\nIf the value is an array, this is equivalent to calling this method multiple\ntimes.
\nIf there were no previous values for the header, this is equivalent to calling\nresponse.setHeader().
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
// Returns headers including \"set-cookie: a\" and \"set-cookie: b\"\nconst server = http2.createServer((req, res) => {\n res.setHeader('set-cookie', 'a');\n res.appendHeader('set-cookie', 'b');\n res.writeHead(200);\n res.end('ok');\n});\n"
},
{
"textRaw": "`response.createPushResponse(headers, callback)`",
"name": "createPushResponse",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers",
"name": "headers",
"type": "HTTP/2 Headers Object",
"desc": "An object describing the headers"
},
{
"textRaw": "`callback` {Function} Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method",
"name": "callback",
"type": "Function",
"desc": "Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`res` {http2.Http2ServerResponse} The newly-created `Http2ServerResponse` object",
"name": "res",
"type": "http2.Http2ServerResponse",
"desc": "The newly-created `Http2ServerResponse` object"
}
]
}
]
}
],
"desc": "Call http2stream.pushStream() with the given headers, and wrap the\ngiven Http2Stream on a newly created Http2ServerResponse as the callback\nparameter if successful. When Http2ServerRequest is closed, the callback is\ncalled with an error ERR_HTTP2_INVALID_STREAM.
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.
If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).
If callback is specified, it will be called when the response stream\nis finished.
Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.
\nconst contentType = response.getHeader('content-type');\n"
},
{
"textRaw": "`response.getHeaderNames()`",
"name": "getHeaderNames",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n"
},
{
"textRaw": "`response.getHeaders()`",
"name": "getHeaders",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`response.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
const hasContentType = response.hasHeader('content-type');\n"
},
{
"textRaw": "`response.removeHeader(name)`",
"name": "removeHeader",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Removes a header that has been queued for implicit sending.
\nresponse.removeHeader('Content-Encoding');\n"
},
{
"textRaw": "`response.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string|string[]}",
"name": "value",
"type": "string|string[]"
}
]
}
],
"desc": "Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.
\nresponse.setHeader('Content-Type', 'text/html; charset=utf-8');\n\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n"
},
{
"textRaw": "`response.setTimeout(msecs[, callback])`",
"name": "setTimeout",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {number}",
"name": "msecs",
"type": "number"
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http2.Http2ServerResponse}",
"name": "return",
"type": "http2.Http2ServerResponse"
}
}
],
"desc": "Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.
If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.
If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nIn the node:http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.
chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'. callback will be called when this chunk\nof data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.
\nThe first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.
Sends a status 103 Early Hints to the client with a Link header,\nindicating that the user agent can preload/preconnect the linked resources.\nThe hints is an object containing the values of headers to be sent with\nearly hints message.
Example
\nconst earlyHintsLink = '</styles.css>; rel=preload; as=style';\nresponse.writeEarlyHints({\n 'link': earlyHintsLink,\n});\n\nconst earlyHintsLinks = [\n '</styles.css>; rel=preload; as=style',\n '</scripts.js>; rel=preload; as=script',\n];\nresponse.writeEarlyHints({\n 'link': earlyHintsLinks,\n});\n"
},
{
"textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`",
"name": "writeHead",
"type": "method",
"meta": {
"added": [
"v8.4.0"
],
"changes": [
{
"version": [
"v11.10.0",
"v10.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/25974",
"description": "Return `this` from `writeHead()` to allow chaining with `end()`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`statusCode` {number}",
"name": "statusCode",
"type": "number"
},
{
"textRaw": "`statusMessage` {string}",
"name": "statusMessage",
"type": "string",
"optional": true
},
{
"textRaw": "`headers` {HTTP/2 Headers Object}",
"name": "headers",
"type": "HTTP/2 Headers Object",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http2.Http2ServerResponse}",
"name": "return",
"type": "http2.Http2ServerResponse"
}
}
],
"desc": "Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.
Returns a reference to the Http2ServerResponse, so that calls can be chained.
For compatibility with HTTP/1, a human-readable statusMessage may be\npassed as the second argument. However, because the statusMessage has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.
const body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain; charset=utf-8',\n});\n\nContent-Length is given in bytes not characters. The\nBuffer.byteLength() API may be used to determine the number of bytes in a\ngiven encoding. On outbound messages, Node.js does not check if Content-Length\nand the length of the body being transmitted are equal or not. However, when\nreceiving messages, Node.js will automatically reject messages when the\nContent-Length does not match the actual payload size.
This method may be called at most one time on a message before\nresponse.end() is called.
If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
See response.socket.
Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.
True if headers were sent, false otherwise (read-only).
" }, { "textRaw": "Type: {http2.Http2ServerRequest}", "name": "req", "type": "http2.Http2ServerRequest", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "A reference to the original HTTP2 request object.
When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; HTTP requires the Date header\nin responses.
" }, { "textRaw": "Type: {net.Socket|tls.TLSSocket}", "name": "socket", "type": "net.Socket|tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.
destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.
destroy, emit, end, on and once methods will be called on\nresponse.stream.
setTimeout method will be called on response.stream.session.
pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.
All other interactions will be routed directly to the socket.
\nimport { createServer } from 'node:http2';\nconst server = createServer((req, res) => {\n const ip = req.socket.remoteAddress;\n const port = req.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n\nconst http2 = require('node:http2');\nconst server = http2.createServer((req, res) => {\n const ip = req.socket.remoteAddress;\n const port = req.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n"
},
{
"textRaw": "Type: {number}",
"name": "statusCode",
"type": "number",
"meta": {
"added": [
"v8.4.0"
],
"changes": []
},
"desc": "When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
response.statusCode = 404;\n\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
" }, { "textRaw": "Type: {string}", "name": "statusMessage", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns\nan empty string.
" }, { "textRaw": "Type: {Http2Stream}", "name": "stream", "type": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "The Http2Stream object backing the response.
Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.
The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.
import { PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((items) => {\n const entry = items.getEntries()[0];\n console.log(entry.entryType); // prints 'http2'\n if (entry.name === 'Http2Session') {\n // Entry contains statistics about the Http2Session\n } else if (entry.name === 'Http2Stream') {\n // Entry contains statistics about the Http2Stream\n }\n});\nobs.observe({ entryTypes: ['http2'] });\n\nconst { PerformanceObserver } = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n const entry = items.getEntries()[0];\n console.log(entry.entryType); // prints 'http2'\n if (entry.name === 'Http2Session') {\n // Entry contains statistics about the Http2Session\n } else if (entry.name === 'Http2Stream') {\n // Entry contains statistics about the Http2Stream\n }\n});\nobs.observe({ entryTypes: ['http2'] });\n\nThe entryType property of the PerformanceEntry will be equal to 'http2'.
The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.
If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:
bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.id <number> The identifier of the associated Http2StreamtimeToFirstByte <number> The number of milliseconds elapsed between the PerformanceEntry startTime and the reception of the first DATA frame.timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.timeToFirstHeader <number> The number of milliseconds elapsed between the PerformanceEntry startTime and the reception of the first header.If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:
bytesRead <number> The number of bytes received for this Http2Session.bytesWritten <number> The number of bytes sent for this Http2Session.framesReceived <number> The number of HTTP/2 frames received by the Http2Session.framesSent <number> The number of HTTP/2 frames sent by the Http2Session.maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.pingRTT <number> The number of milliseconds elapsed since the transmission\nof a PING frame and the reception of its acknowledgment. Only present if\na PING frame has been sent on the Http2Session.streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.HTTP/2 requires requests to have either the :authority pseudo-header\nor the host header. Prefer :authority when constructing an HTTP/2\nrequest directly, and host when converting from HTTP/1 (in proxies,\nfor instance).
The compatibility API falls back to host if :authority is not\npresent. See request.authority for more information. However,\nif you don't use the compatibility API (or use req.headers directly),\nyou need to implement any fall-back behavior yourself.
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.
", "modules": [ { "textRaw": "Determining if crypto support is unavailable", "name": "determining_if_crypto_support_is_unavailable", "type": "module", "desc": "It is possible for Node.js to be built without including support for the\nnode:crypto module. In such cases, attempting to import from https or\ncalling require('node:https') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
\nlet https;\ntry {\n https = require('node:https');\n} catch (err) {\n console.error('https support is disabled!');\n}\n\nWhen using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made (using, for instance,\na preload module).
When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:
let https;\ntry {\n https = await import('node:https');\n} catch (err) {\n console.error('https support is disabled!');\n}\n",
"displayName": "Determining if crypto support is unavailable"
}
],
"classes": [
{
"textRaw": "Class: `https.Agent`",
"name": "https.Agent",
"type": "class",
"meta": {
"added": [
"v0.4.5"
],
"changes": [
{
"version": "v5.3.0",
"pr-url": "https://github.com/nodejs/node/pull/4252",
"description": "support `0` `maxCachedSessions` to disable TLS session caching."
},
{
"version": "v2.5.0",
"pr-url": "https://github.com/nodejs/node/pull/2228",
"description": "parameter `maxCachedSessions` added to `options` for TLS sessions reuse."
}
]
},
"desc": "An Agent object for HTTPS similar to http.Agent. See\nhttps.request() for more information.
Like http.Agent, the createConnection(options[, callback]) method can be overridden\nto customize how TLS connections are established.
\n", "signatures": [ { "textRaw": "`new Agent([options])`", "name": "Agent", "type": "ctor", "meta": { "changes": [ { "version": [ "v24.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/58980", "description": "Add support for `proxyEnv`." }, { "version": [ "v24.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/58980", "description": "Add support for `defaultPort` and `protocol`." }, { "version": "v12.5.0", "pr-url": "https://github.com/nodejs/node/pull/28209", "description": "do not automatically set servername if the target host was specified using an IP address." } ] }, "params": [ { "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the same fields as for `http.Agent(options)`, and", "name": "options", "type": "Object", "desc": "Set of configurable options to set on the agent. Can have the same fields as for `http.Agent(options)`, and", "options": [ { "textRaw": "`maxCachedSessions` {number} maximum number of TLS cached sessions. Use `0` to disable TLS session caching. **Default:** `100`.", "name": "maxCachedSessions", "type": "number", "default": "`100`", "desc": "maximum number of TLS cached sessions. Use `0` to disable TLS session caching." }, { "textRaw": "`servername` {string} the value of Server Name Indication extension to be sent to the server. Use empty string `''` to disable sending the extension. **Default:** host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See `Session Resumption` for information about TLS session reuse.", "name": "servername", "type": "string", "default": "host name of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).See `Session Resumption` for information about TLS session reuse", "desc": "the value of Server Name Indication extension to be sent to the server. Use empty string `''` to disable sending the extension." } ], "optional": true } ], "events": [ { "textRaw": "Event: `'keylog'`", "name": "keylog", "type": "event", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "params": [ { "textRaw": "`line` {Buffer} Line of ASCII text, in NSS `SSLKEYLOGFILE` format.", "name": "line", "type": "Buffer", "desc": "Line of ASCII text, in NSS `SSLKEYLOGFILE` format." }, { "textRaw": "`tlsSocket` {tls.TLSSocket} The `tls.TLSSocket` instance on which it was generated.", "name": "tlsSocket", "type": "tls.TLSSocket", "desc": "The `tls.TLSSocket` instance on which it was generated." } ], "desc": "See
\nagent.createConnection()for details on overriding this method,\nincluding asynchronous socket creation with a callback.
The keylog event is emitted when key material is generated or received by a\nconnection managed by this agent (typically before handshake has completed, but\nnot necessarily). This keying material can be stored for debugging, as it\nallows captured TLS traffic to be decrypted. It may be emitted multiple times\nfor each socket.
A typical use case is to append received lines to a common text file, which is\nlater used by software (such as Wireshark) to decrypt the traffic:
\n// ...\nhttps.globalAgent.on('keylog', (line, tlsSocket) => {\n fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });\n});\n"
}
]
}
]
},
{
"textRaw": "Class: `https.Server`",
"name": "https.Server",
"type": "class",
"meta": {
"added": [
"v0.3.4"
],
"changes": []
},
"desc": "<tls.Server>See http.Server for more information.
See server.close() in the node:http module.
Calls server.close() and returns a promise that\nfulfills when the server has closed.
See server.closeAllConnections() in the node:http module.
See server.closeIdleConnections() in the node:http module.
Starts the HTTPS server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.
See server.setTimeout() in the node:http module.
See server.headersTimeout in the node:http module.
See server.maxHeadersCount in the node:http module.
See server.requestTimeout in the node:http module.
See server.timeout in the node:http module.
See server.keepAliveTimeout in the node:http module.
// curl -k https://localhost:8000/\nimport { createServer } from 'node:https';\nimport { readFileSync } from 'node:fs';\n\nconst options = {\n key: readFileSync('private-key.pem'),\n cert: readFileSync('certificate.pem'),\n};\n\ncreateServer(options, (req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n}).listen(8000);\n\n// curl -k https://localhost:8000/\nconst https = require('node:https');\nconst fs = require('node:fs');\n\nconst options = {\n key: fs.readFileSync('private-key.pem'),\n cert: fs.readFileSync('certificate.pem'),\n};\n\nhttps.createServer(options, (req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n}).listen(8000);\n\nOr
\nimport { createServer } from 'node:https';\nimport { readFileSync } from 'node:fs';\n\nconst options = {\n pfx: readFileSync('test_cert.pfx'),\n passphrase: 'sample',\n};\n\ncreateServer(options, (req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n}).listen(8000);\n\nconst https = require('node:https');\nconst fs = require('node:fs');\n\nconst options = {\n pfx: fs.readFileSync('test_cert.pfx'),\n passphrase: 'sample',\n};\n\nhttps.createServer(options, (req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n}).listen(8000);\n\nTo generate the certificate and key for this example, run:
\nopenssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n -keyout private-key.pem -out certificate.pem\n\nThen, to generate the pfx certificate for this example, run:
openssl pkcs12 -certpbe AES-256-CBC -export -out test_cert.pfx \\\n -inkey private-key.pem -in certificate.pem -passout pass:sample\n"
},
{
"textRaw": "`https.get(options[, callback])`",
"name": "get",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`https.get(url[, options][, callback])`",
"name": "get",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string|URL}",
"name": "url",
"type": "string|URL"
},
{
"textRaw": "`options` {Object|string|URL} Accepts the same `options` as `https.request()`, with the method set to GET by default.",
"name": "options",
"type": "Object|string|URL",
"desc": "Accepts the same `options` as `https.request()`, with the method set to GET by default.",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "Like http.get() but for HTTPS.
options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.
import { get } from 'node:https';\nimport process from 'node:process';\n\nget('https://encrypted.google.com/', (res) => {\n console.log('statusCode:', res.statusCode);\n console.log('headers:', res.headers);\n\n res.on('data', (d) => {\n process.stdout.write(d);\n });\n\n}).on('error', (e) => {\n console.error(e);\n});\n\nconst https = require('node:https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n console.log('statusCode:', res.statusCode);\n console.log('headers:', res.headers);\n\n res.on('data', (d) => {\n process.stdout.write(d);\n });\n\n}).on('error', (e) => {\n console.error(e);\n});\n"
},
{
"textRaw": "`https.request(options[, callback])`",
"name": "request",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`https.request(url[, options][, callback])`",
"name": "request",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": [
"v22.4.0",
"v20.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/53329",
"description": "The `clientCertEngine` option depends on custom engine support in OpenSSL which is deprecated in OpenSSL 3."
},
{
"version": [
"v16.7.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/39310",
"description": "When using a `URL` object parsed username and password will now be properly URI decoded."
},
{
"version": [
"v14.1.0",
"v13.14.0"
],
"pr-url": "https://github.com/nodejs/node/pull/32786",
"description": "The `highWaterMark` option is accepted now."
},
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v9.3.0",
"pr-url": "https://github.com/nodejs/node/pull/14903",
"description": "The `options` parameter can now include `clientCertEngine`."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string|URL}",
"name": "url",
"type": "string|URL"
},
{
"textRaw": "`options` {Object|string|URL} Accepts all `options` from `http.request()`, with some differences in default values:",
"name": "options",
"type": "Object|string|URL",
"desc": "Accepts all `options` from `http.request()`, with some differences in default values:",
"options": [
{
"textRaw": "`protocol` **Default:** `'https:'`",
"name": "protocol",
"default": "`'https:'`"
},
{
"textRaw": "`port` **Default:** `443`",
"name": "port",
"default": "`443`"
},
{
"textRaw": "`agent` **Default:** `https.globalAgent`",
"name": "agent",
"default": "`https.globalAgent`"
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "Makes a request to a secure web server.
\nThe following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine (deprecated), crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext,\nhighWaterMark.
options can be an object, a string, or a URL object. If options is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.
https.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.
import { request } from 'node:https';\nimport process from 'node:process';\n\nconst options = {\n hostname: 'encrypted.google.com',\n port: 443,\n path: '/',\n method: 'GET',\n};\n\nconst req = request(options, (res) => {\n console.log('statusCode:', res.statusCode);\n console.log('headers:', res.headers);\n\n res.on('data', (d) => {\n process.stdout.write(d);\n });\n});\n\nreq.on('error', (e) => {\n console.error(e);\n});\nreq.end();\n\nconst https = require('node:https');\n\nconst options = {\n hostname: 'encrypted.google.com',\n port: 443,\n path: '/',\n method: 'GET',\n};\n\nconst req = https.request(options, (res) => {\n console.log('statusCode:', res.statusCode);\n console.log('headers:', res.headers);\n\n res.on('data', (d) => {\n process.stdout.write(d);\n });\n});\n\nreq.on('error', (e) => {\n console.error(e);\n});\nreq.end();\n\nExample using options from tls.connect():
const options = {\n hostname: 'encrypted.google.com',\n port: 443,\n path: '/',\n method: 'GET',\n key: fs.readFileSync('private-key.pem'),\n cert: fs.readFileSync('certificate.pem'),\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n // ...\n});\n\nAlternatively, opt out of connection pooling by not using an Agent.
const options = {\n hostname: 'encrypted.google.com',\n port: 443,\n path: '/',\n method: 'GET',\n key: fs.readFileSync('private-key.pem'),\n cert: fs.readFileSync('certificate.pem'),\n agent: false,\n};\n\nconst req = https.request(options, (res) => {\n // ...\n});\n\nExample using a URL as options:
const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n // ...\n});\n\nExample pinning on certificate fingerprint, or the public key (similar to\npin-sha256):
import { checkServerIdentity } from 'node:tls';\nimport { Agent, request } from 'node:https';\nimport { createHash } from 'node:crypto';\n\nfunction sha256(s) {\n return createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n hostname: 'github.com',\n port: 443,\n path: '/',\n method: 'GET',\n checkServerIdentity: function(host, cert) {\n // Make sure the certificate is issued to the host we are connected to\n const err = checkServerIdentity(host, cert);\n if (err) {\n return err;\n }\n\n // Pin the public key, similar to HPKP pin-sha256 pinning\n const pubkey256 = 'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8=';\n if (sha256(cert.pubkey) !== pubkey256) {\n const msg = 'Certificate verification error: ' +\n `The public key of '${cert.subject.CN}' ` +\n 'does not match our pinned fingerprint';\n return new Error(msg);\n }\n\n // Pin the exact certificate, rather than the pub key\n const cert256 = 'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:' +\n '0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65';\n if (cert.fingerprint256 !== cert256) {\n const msg = 'Certificate verification error: ' +\n `The certificate of '${cert.subject.CN}' ` +\n 'does not match our pinned fingerprint';\n return new Error(msg);\n }\n\n // This loop is informational only.\n // Print the certificate and public key fingerprints of all certs in the\n // chain. Its common to pin the public key of the issuer on the public\n // internet, while pinning the public key of the service in sensitive\n // environments.\n let lastprint256;\n do {\n console.log('Subject Common Name:', cert.subject.CN);\n console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n const hash = createHash('sha256');\n console.log(' Public key ping-sha256:', sha256(cert.pubkey));\n\n lastprint256 = cert.fingerprint256;\n cert = cert.issuerCertificate;\n } while (cert.fingerprint256 !== lastprint256);\n\n },\n};\n\noptions.agent = new Agent(options);\nconst req = request(options, (res) => {\n console.log('All OK. Server matched our pinned cert or public key');\n console.log('statusCode:', res.statusCode);\n\n res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n console.error(e.message);\n});\nreq.end();\n\nconst tls = require('node:tls');\nconst https = require('node:https');\nconst crypto = require('node:crypto');\n\nfunction sha256(s) {\n return crypto.createHash('sha256').update(s).digest('base64');\n}\nconst options = {\n hostname: 'github.com',\n port: 443,\n path: '/',\n method: 'GET',\n checkServerIdentity: function(host, cert) {\n // Make sure the certificate is issued to the host we are connected to\n const err = tls.checkServerIdentity(host, cert);\n if (err) {\n return err;\n }\n\n // Pin the public key, similar to HPKP pin-sha256 pinning\n const pubkey256 = 'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8=';\n if (sha256(cert.pubkey) !== pubkey256) {\n const msg = 'Certificate verification error: ' +\n `The public key of '${cert.subject.CN}' ` +\n 'does not match our pinned fingerprint';\n return new Error(msg);\n }\n\n // Pin the exact certificate, rather than the pub key\n const cert256 = 'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:' +\n '0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65';\n if (cert.fingerprint256 !== cert256) {\n const msg = 'Certificate verification error: ' +\n `The certificate of '${cert.subject.CN}' ` +\n 'does not match our pinned fingerprint';\n return new Error(msg);\n }\n\n // This loop is informational only.\n // Print the certificate and public key fingerprints of all certs in the\n // chain. Its common to pin the public key of the issuer on the public\n // internet, while pinning the public key of the service in sensitive\n // environments.\n do {\n console.log('Subject Common Name:', cert.subject.CN);\n console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);\n\n hash = crypto.createHash('sha256');\n console.log(' Public key ping-sha256:', sha256(cert.pubkey));\n\n lastprint256 = cert.fingerprint256;\n cert = cert.issuerCertificate;\n } while (cert.fingerprint256 !== lastprint256);\n\n },\n};\n\noptions.agent = new https.Agent(options);\nconst req = https.request(options, (res) => {\n console.log('All OK. Server matched our pinned cert or public key');\n console.log('statusCode:', res.statusCode);\n\n res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n console.error(e.message);\n});\nreq.end();\n\nOutputs for example:
\nSubject Common Name: github.com\n Certificate SHA256 fingerprint: FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65\n Public key ping-sha256: SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8=\nSubject Common Name: Sectigo ECC Domain Validation Secure Server CA\n Certificate SHA256 fingerprint: 61:E9:73:75:E9:F6:DA:98:2F:F5:C1:9E:2F:94:E6:6C:4E:35:B6:83:7C:E3:B9:14:D2:24:5C:7F:5F:65:82:5F\n Public key ping-sha256: Eep0p/AsSa9lFUH6KT2UY+9s1Z8v7voAPkQ4fGknZ2g=\nSubject Common Name: USERTrust ECC Certification Authority\n Certificate SHA256 fingerprint: A6:CF:64:DB:B4:C8:D5:FD:19:CE:48:89:60:68:DB:03:B5:33:A8:D1:33:6C:62:56:A8:7D:00:CB:B3:DE:F3:EA\n Public key ping-sha256: UJM2FOhG9aTNY0Pg4hgqjNzZ/lQBiMGRxPD5Y2/e0bw=\nSubject Common Name: AAA Certificate Services\n Certificate SHA256 fingerprint: D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4\n Public key ping-sha256: vRU+17BDT2iGsXvOi76E7TQMcTLXAqj0+jGPdW7L1vM=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\n"
}
],
"properties": [
{
"textRaw": "`https.globalAgent`",
"name": "globalAgent",
"type": "property",
"meta": {
"added": [
"v0.5.9"
],
"changes": [
{
"version": [
"v19.0.0"
],
"pr-url": "https://github.com/nodejs/node/pull/43522",
"description": "The agent now uses HTTP Keep-Alive and a 5 second timeout by default."
}
]
},
"desc": "Global instance of https.Agent for all HTTPS client requests. Diverges\nfrom a default https.Agent configuration by having keepAlive enabled and\na timeout of 5 seconds.
The node:inspector module provides an API for interacting with the V8\ninspector.
It can be accessed using:
\nimport * as inspector from 'node:inspector/promises';\n\nconst inspector = require('node:inspector/promises');\n\nor
\nimport * as inspector from 'node:inspector';\n\nconst inspector = require('node:inspector');\n",
"modules": [
{
"textRaw": "Promises API",
"name": "promises_api",
"type": "module",
"meta": {
"added": [
"v19.0.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"classes": [
{
"textRaw": "Class: `inspector.Session`",
"name": "inspector.Session",
"type": "class",
"desc": "<EventEmitter>The inspector.Session is used for dispatching messages to the V8 inspector\nback-end and receiving message responses and notifications.
Create a new instance of the inspector.Session class. The inspector session\nneeds to be connected through session.connect() before the messages\ncan be dispatched to the inspector backend.
When using Session, the object outputted by the console API will not be\nreleased, unless we performed manually Runtime.DiscardConsoleEntries\ncommand.
Emitted when any notification from the V8 Inspector is received.
\nsession.on('inspectorNotification', (message) => console.log(message.method));\n// Debugger.paused\n// Debugger.resumed\n\n\n\nCaveat Breakpoints with same-thread session is not recommended, see\nsupport of breakpoints.
\n
It is also possible to subscribe only to notifications with specific method:
" }, { "textRaw": "Event: `Emitted when an inspector notification is received that has its method field set\nto the <inspector-protocol-method> value.
The following snippet installs a listener on the 'Debugger.paused'\nevent, and prints the reason for program suspension whenever program\nexecution is suspended (through breakpoints, for example):
session.on('Debugger.paused', ({ params }) => {\n console.log(params.hitBreakpoints);\n});\n// [ '/the/file/that/has/the/breakpoint.js:11:0' ]\n\n\n" } ], "methods": [ { "textRaw": "`session.connect()`", "name": "connect", "type": "method", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Caveat Breakpoints with same-thread session is not recommended, see\nsupport of breakpoints.
\n
Connects a session to the inspector back-end.
" }, { "textRaw": "`session.connectToMainThread()`", "name": "connectToMainThread", "type": "method", "meta": { "added": [ "v12.11.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Connects a session to the main thread inspector back-end. An exception will\nbe thrown if this API was not called on a Worker thread.
" }, { "textRaw": "`session.disconnect()`", "name": "disconnect", "type": "method", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Immediately close the session. All pending message callbacks will be called\nwith an error. session.connect() will need to be called to be able to send\nmessages again. Reconnected session will lose all inspector state, such as\nenabled agents or configured breakpoints.
Posts a message to the inspector back-end.
\nimport { Session } from 'node:inspector/promises';\ntry {\n const session = new Session();\n session.connect();\n const result = await session.post('Runtime.evaluate', { expression: '2 + 2' });\n console.log(result);\n} catch (error) {\n console.error(error);\n}\n// Output: { result: { type: 'number', value: 4, description: '4' } }\n\nThe latest version of the V8 inspector protocol is published on the\nChrome DevTools Protocol Viewer.
\nNode.js inspector supports all the Chrome DevTools Protocol domains declared\nby V8. Chrome DevTools Protocol domain provides an interface for interacting\nwith one of the runtime agents used to inspect the application state and listen\nto the run-time events.
" } ], "modules": [ { "textRaw": "Example usage", "name": "example_usage", "type": "module", "desc": "Apart from the debugger, various V8 Profilers are available through the DevTools\nprotocol.
", "modules": [ { "textRaw": "CPU profiler", "name": "cpu_profiler", "type": "module", "desc": "Here's an example showing how to use the CPU Profiler:
\nimport { Session } from 'node:inspector/promises';\nimport fs from 'node:fs';\nconst session = new Session();\nsession.connect();\n\nawait session.post('Profiler.enable');\nawait session.post('Profiler.start');\n// Invoke business logic under measurement here...\n\n// some time later...\nconst { profile } = await session.post('Profiler.stop');\n\n// Write profile to disk, upload, etc.\nfs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));\n",
"displayName": "CPU profiler"
},
{
"textRaw": "Heap profiler",
"name": "heap_profiler",
"type": "module",
"desc": "Here's an example showing how to use the Heap Profiler:
\nimport { Session } from 'node:inspector/promises';\nimport fs from 'node:fs';\nconst session = new Session();\n\nconst fd = fs.openSync('profile.heapsnapshot', 'w');\n\nsession.connect();\n\nsession.on('HeapProfiler.addHeapSnapshotChunk', (m) => {\n fs.writeSync(fd, m.params.chunk);\n});\n\nconst result = await session.post('HeapProfiler.takeHeapSnapshot', null);\nconsole.log('HeapProfiler.takeHeapSnapshot done:', result);\nsession.disconnect();\nfs.closeSync(fd);\n",
"displayName": "Heap profiler"
}
],
"displayName": "Example usage"
}
]
}
],
"displayName": "Promises API"
},
{
"textRaw": "Callback API",
"name": "callback_api",
"type": "module",
"classes": [
{
"textRaw": "Class: `inspector.Session`",
"name": "inspector.Session",
"type": "class",
"desc": "<EventEmitter>The inspector.Session is used for dispatching messages to the V8 inspector\nback-end and receiving message responses and notifications.
Create a new instance of the inspector.Session class. The inspector session\nneeds to be connected through session.connect() before the messages\ncan be dispatched to the inspector backend.
When using Session, the object outputted by the console API will not be\nreleased, unless we performed manually Runtime.DiscardConsoleEntries\ncommand.
Emitted when any notification from the V8 Inspector is received.
\nsession.on('inspectorNotification', (message) => console.log(message.method));\n// Debugger.paused\n// Debugger.resumed\n\n\n\nCaveat Breakpoints with same-thread session is not recommended, see\nsupport of breakpoints.
\n
It is also possible to subscribe only to notifications with specific method:
" } ], "modules": [ { "textRaw": "Event: `<Object> The notification message objectEmitted when an inspector notification is received that has its method field set\nto the <inspector-protocol-method> value.
The following snippet installs a listener on the 'Debugger.paused'\nevent, and prints the reason for program suspension whenever program\nexecution is suspended (through breakpoints, for example):
session.on('Debugger.paused', ({ params }) => {\n console.log(params.hitBreakpoints);\n});\n// [ '/the/file/that/has/the/breakpoint.js:11:0' ]\n\n\n", "displayName": "Event: `Caveat Breakpoints with same-thread session is not recommended, see\nsupport of breakpoints.
\n
Apart from the debugger, various V8 Profilers are available through the DevTools\nprotocol.
", "modules": [ { "textRaw": "CPU profiler", "name": "cpu_profiler", "type": "module", "desc": "Here's an example showing how to use the CPU Profiler:
\nconst inspector = require('node:inspector');\nconst fs = require('node:fs');\nconst session = new inspector.Session();\nsession.connect();\n\nsession.post('Profiler.enable', () => {\n session.post('Profiler.start', () => {\n // Invoke business logic under measurement here...\n\n // some time later...\n session.post('Profiler.stop', (err, { profile }) => {\n // Write profile to disk, upload, etc.\n if (!err) {\n fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));\n }\n });\n });\n});\n",
"displayName": "CPU profiler"
},
{
"textRaw": "Heap profiler",
"name": "heap_profiler",
"type": "module",
"desc": "Here's an example showing how to use the Heap Profiler:
\nconst inspector = require('node:inspector');\nconst fs = require('node:fs');\nconst session = new inspector.Session();\n\nconst fd = fs.openSync('profile.heapsnapshot', 'w');\n\nsession.connect();\n\nsession.on('HeapProfiler.addHeapSnapshotChunk', (m) => {\n fs.writeSync(fd, m.params.chunk);\n});\n\nsession.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {\n console.log('HeapProfiler.takeHeapSnapshot done:', err, r);\n session.disconnect();\n fs.closeSync(fd);\n});\n",
"displayName": "Heap profiler"
}
],
"displayName": "Example usage"
}
],
"methods": [
{
"textRaw": "`session.connect()`",
"name": "connect",
"type": "method",
"meta": {
"added": [
"v8.0.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Connects a session to the inspector back-end.
" }, { "textRaw": "`session.connectToMainThread()`", "name": "connectToMainThread", "type": "method", "meta": { "added": [ "v12.11.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Connects a session to the main thread inspector back-end. An exception will\nbe thrown if this API was not called on a Worker thread.
" }, { "textRaw": "`session.disconnect()`", "name": "disconnect", "type": "method", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Immediately close the session. All pending message callbacks will be called\nwith an error. session.connect() will need to be called to be able to send\nmessages again. Reconnected session will lose all inspector state, such as\nenabled agents or configured breakpoints.
Posts a message to the inspector back-end. callback will be notified when\na response is received. callback is a function that accepts two optional\narguments: error and message-specific result.
session.post('Runtime.evaluate', { expression: '2 + 2' },\n (error, { result }) => console.log(result));\n// Output: { type: 'number', value: 4, description: '4' }\n\nThe latest version of the V8 inspector protocol is published on the\nChrome DevTools Protocol Viewer.
\nNode.js inspector supports all the Chrome DevTools Protocol domains declared\nby V8. Chrome DevTools Protocol domain provides an interface for interacting\nwith one of the runtime agents used to inspect the application state and listen\nto the run-time events.
\nYou can not set reportProgress to true when sending a\nHeapProfiler.takeHeapSnapshot or HeapProfiler.stopTrackingHeapObjects\ncommand to V8.
Attempts to close all remaining connections, blocking the event loop until all\nare closed. Once all connections are closed, deactivates the inspector.
" }, { "textRaw": "`inspector.open([port[, host[, wait]]])`", "name": "open", "type": "method", "meta": { "changes": [ { "version": "v20.6.0", "pr-url": "https://github.com/nodejs/node/pull/48765", "description": "inspector.open() now returns a `Disposable` object." } ] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Port to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", "name": "port", "type": "number", "default": "what was specified on the CLI", "desc": "Port to listen on for inspector connections. Optional.", "optional": true }, { "textRaw": "`host` {string} Host to listen on for inspector connections. Optional. **Default:** what was specified on the CLI.", "name": "host", "type": "string", "default": "what was specified on the CLI", "desc": "Host to listen on for inspector connections. Optional.", "optional": true }, { "textRaw": "`wait` {boolean} Block until a client has connected. Optional. **Default:** `false`.", "name": "wait", "type": "boolean", "default": "`false`", "desc": "Block until a client has connected. Optional.", "optional": true } ], "return": { "textRaw": "Returns: {Disposable} A Disposable that calls `inspector.close()`.", "name": "return", "type": "Disposable", "desc": "A Disposable that calls `inspector.close()`." } } ], "desc": "Activate inspector on host and port. Equivalent to\nnode --inspect=[[host:]port], but can be done programmatically after node has\nstarted.
If wait is true, will block until a client has connected to the inspect port\nand flow control has been passed to the debugger client.
See the security warning regarding the host\nparameter usage.
Return the URL of the active inspector, or undefined if there is none.
$ node --inspect -p 'inspector.url()'\nDebugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\nFor help, see: https://nodejs.org/en/docs/inspector\nws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34\n\n$ node --inspect=localhost:3000 -p 'inspector.url()'\nDebugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\nFor help, see: https://nodejs.org/en/docs/inspector\nws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a\n\n$ node -p 'inspector.url()'\nundefined\n"
},
{
"textRaw": "`inspector.waitForDebugger()`",
"name": "waitForDebugger",
"type": "method",
"meta": {
"added": [
"v12.7.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Blocks until a client (existing or connected later) has sent\nRuntime.runIfWaitingForDebugger command.
An exception will be thrown if there is no active inspector.
" } ], "properties": [ { "textRaw": "Type: {Object} An object to send messages to the remote inspector console.", "name": "console", "type": "Object", "desc": "require('node:inspector').console.log('a message');\n\nThe inspector console does not have API parity with Node.js\nconsole.
", "shortDesc": "An object to send messages to the remote inspector console." } ], "displayName": "Common Objects" }, { "textRaw": "Integration with DevTools", "name": "integration_with_devtools", "type": "module", "stability": 1.1, "stabilityText": "Active development", "desc": "The node:inspector module provides an API for integrating with devtools that support Chrome DevTools Protocol.\nDevTools frontends connected to a running Node.js instance can capture protocol events emitted from the instance\nand display them accordingly to facilitate debugging.\nThe following methods broadcast a protocol event to all connected frontends.\nThe params passed to the methods can be optional, depending on the protocol.
// The `Network.requestWillBeSent` event will be fired.\ninspector.Network.requestWillBeSent({\n requestId: 'request-id-1',\n timestamp: Date.now() / 1000,\n wallTime: Date.now(),\n request: {\n url: 'https://nodejs.org/en',\n method: 'GET',\n },\n});\n",
"methods": [
{
"textRaw": "`inspector.Network.dataReceived([params])`",
"name": "dataReceived",
"type": "method",
"meta": {
"added": [
"v24.2.0",
"v22.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`params` {Object}",
"name": "params",
"type": "Object",
"optional": true
}
]
}
],
"desc": "This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.dataReceived event to connected frontends, or buffers the data if\nNetwork.streamResourceContent command was not invoked for the given request yet.
Also enables Network.getResponseBody command to retrieve the response data.
This feature is only available with the --experimental-network-inspection flag enabled.
Enables Network.getRequestPostData command to retrieve the request data.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.requestWillBeSent event to connected frontends. This event indicates that\nthe application is about to send an HTTP request.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.responseReceived event to connected frontends. This event indicates that\nHTTP response is available.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.loadingFinished event to connected frontends. This event indicates that\nHTTP request has finished loading.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.loadingFailed event to connected frontends. This event indicates that\nHTTP request has failed to load.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.webSocketCreated event to connected frontends. This event indicates that\na WebSocket connection has been initiated.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.webSocketHandshakeResponseReceived event to connected frontends.\nThis event indicates that the WebSocket handshake response has been received.
This feature is only available with the --experimental-network-inspection flag enabled.
Broadcasts the Network.webSocketClosed event to connected frontends.\nThis event indicates that a WebSocket connection has been closed.
This feature is only available with the --experimental-inspector-network-resource flag enabled.
The inspector.NetworkResources.put method is used to provide a response for a loadNetworkResource\nrequest issued via the Chrome DevTools Protocol (CDP).\nThis is typically triggered when a source map is specified by URL, and a DevTools frontend—such as\nChrome—requests the resource to retrieve the source map.
\nThis method allows developers to predefine the resource content to be served in response to such CDP requests.
\nconst inspector = require('node:inspector');\n// By preemptively calling put to register the resource, a source map can be resolved when\n// a loadNetworkResource request is made from the frontend.\nasync function setNetworkResources() {\n const mapUrl = 'http://localhost:3000/dist/app.js.map';\n const tsUrl = 'http://localhost:3000/src/app.ts';\n const distAppJsMap = await fetch(mapUrl).then((res) => res.text());\n const srcAppTs = await fetch(tsUrl).then((res) => res.text());\n inspector.NetworkResources.put(mapUrl, distAppJsMap);\n inspector.NetworkResources.put(tsUrl, srcAppTs);\n};\nsetNetworkResources().then(() => {\n require('./dist/app');\n});\n\nFor more details, see the official CDP documentation: Network.loadNetworkResource
" }, { "textRaw": "`params` {Object}", "name": "domStorageItemAdded", "type": "Object", "meta": { "added": [ "v25.5.0" ], "changes": [] }, "desc": "This feature is only available with the\n--experimental-storage-inspection flag enabled.
Broadcasts the DOMStorage.domStorageItemAdded event to connected frontends.\nThis event indicates that a new item has been added to the storage.
This feature is only available with the\n--experimental-storage-inspection flag enabled.
Broadcasts the DOMStorage.domStorageItemRemoved event to connected frontends.\nThis event indicates that an item has been removed from the storage.
This feature is only available with the\n--experimental-storage-inspection flag enabled.
Broadcasts the DOMStorage.domStorageItemUpdated event to connected frontends.\nThis event indicates that a storage item has been updated.
This feature is only available with the\n--experimental-storage-inspection flag enabled.
Broadcasts the DOMStorage.domStorageItemsCleared event to connected\nfrontends. This event indicates that all items have been cleared from the\nstorage.
This feature is only available with the\n--experimental-storage-inspection flag enabled.
The Chrome DevTools Protocol Debugger domain allows an\ninspector.Session to attach to a program and set breakpoints to step through\nthe codes.
However, setting breakpoints with a same-thread inspector.Session, which is\nconnected by session.connect(), should be avoided as the program being\nattached and paused is exactly the debugger itself. Instead, try connect to the\nmain thread by session.connectToMainThread() and set breakpoints in a\nworker thread, or connect with a Debugger program over WebSocket\nconnection.
CommonJS modules are the original way to package JavaScript code for Node.js.\nNode.js also supports the ECMAScript modules standard used by browsers\nand other JavaScript runtimes.
\nIn Node.js, each file is treated as a separate module. For\nexample, consider a file named foo.js:
const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n\nOn the first line, foo.js loads the module circle.js that is in the same\ndirectory as foo.js.
Here are the contents of circle.js:
const { PI } = Math;\n\nexports.area = (r) => PI * r ** 2;\n\nexports.circumference = (r) => 2 * PI * r;\n\nThe module circle.js has exported the functions area() and\ncircumference(). Functions and objects are added to the root of a module\nby specifying additional properties on the special exports object.
Variables local to the module will be private, because the module is wrapped\nin a function by Node.js (see module wrapper).\nIn this example, the variable PI is private to circle.js.
The module.exports property can be assigned a new value (such as a function\nor object).
In the following code, bar.js makes use of the square module, which exports\na Square class:
const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n\nThe square module is defined in square.js:
// Assigning to exports will not modify module, must use module.exports\nmodule.exports = class Square {\n constructor(width) {\n this.width = width;\n }\n\n area() {\n return this.width ** 2;\n }\n};\n\nThe CommonJS module system is implemented in the module core module.
Node.js has two module systems: CommonJS modules and ECMAScript modules.
\nBy default, Node.js will treat the following as CommonJS modules:
\nFiles with a .cjs extension;
Files with a .js extension when the nearest parent package.json file\ncontains a top-level field \"type\" with a value of \"commonjs\".
Files with a .js extension or without an extension, when the nearest parent\npackage.json file doesn't contain a top-level field \"type\" or there is\nno package.json in any parent folder; unless the file contains syntax that\nerrors unless it is evaluated as an ES module. Package authors should include\nthe \"type\" field, even in packages where all sources are CommonJS. Being\nexplicit about the type of the package will make things easier for build\ntools and loaders to determine how the files in the package should be\ninterpreted.
Files with an extension that is not .mjs, .cjs, .json, .node, or .js\n(when the nearest parent package.json file contains a top-level field\n\"type\" with a value of \"module\", those files will be recognized as\nCommonJS modules only if they are being included via require(), not when\nused as the command-line entry point of the program).
See Determining module system for more details.
\nCalling require() always use the CommonJS module loader. Calling import()\nalways use the ECMAScript module loader.
When a file is run directly from Node.js, require.main is set to its\nmodule. That means that it is possible to determine whether a file has been\nrun directly by testing require.main === module.
For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').
When the entry point is not a CommonJS module, require.main is undefined,\nand the main module is out of reach.
The semantics of the Node.js require() function were designed to be general\nenough to support reasonable directory structures. Package manager programs\nsuch as dpkg, rpm, and npm will hopefully find it possible to build\nnative packages from Node.js modules without modification.
In the following, we give a suggested directory structure that could work:
\nLet's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.
Packages can depend on one another. In order to install package foo, it\nmay be necessary to install a specific version of package bar. The bar\npackage may itself have dependencies, and in some cases, these may even collide\nor form cyclic dependencies.
Because Node.js looks up the realpath of any modules it loads (that is, it\nresolves symlinks) and then looks for their dependencies in node_modules folders,\nthis situation can be resolved with the following architecture:
/usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3./usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends\non./usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to\n/usr/lib/node/bar/4.3.2/./usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that\nbar depends on.Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.
\nWhen the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.
Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then Node.js will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.
In order to make modules available to the Node.js REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.
To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.
Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require() does:
require(X) from module at path Y\n1. If X is a core module,\n a. return the core module\n b. STOP\n2. If X begins with '/'\n a. set Y to the file system root\n3. If X is equal to '.', or X begins with './', '/' or '../'\n a. LOAD_AS_FILE(Y + X)\n b. LOAD_AS_DIRECTORY(Y + X)\n c. THROW \"not found\"\n4. If X begins with '#'\n a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))\n5. LOAD_PACKAGE_SELF(X, dirname(Y))\n6. LOAD_NODE_MODULES(X, dirname(Y))\n7. THROW \"not found\"\n\nMAYBE_DETECT_AND_LOAD(X)\n1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.\n2. Else, if the source code of X can be parsed as ECMAScript module using\n <a href=\"esm.md#resolver-algorithm-specification\">DETECT_MODULE_SYNTAX defined in\n the ESM resolver</a>,\n a. Load X as an ECMAScript module. STOP.\n3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP.\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as its file extension format. STOP\n2. If X.js is a file,\n a. Find the closest package scope SCOPE to X.\n b. If no scope was found\n 1. MAYBE_DETECT_AND_LOAD(X.js)\n c. If the SCOPE/package.json contains \"type\" field,\n 1. If the \"type\" field is \"module\", load X.js as an ECMAScript module. STOP.\n 2. If the \"type\" field is \"commonjs\", load X.js as a CommonJS module. STOP.\n d. MAYBE_DETECT_AND_LOAD(X.js)\n3. If X.json is a file, load X.json to a JavaScript Object. STOP\n4. If X.node is a file, load X.node as binary addon. STOP\n\nLOAD_INDEX(X)\n1. If X/index.js is a file\n a. Find the closest package scope SCOPE to X.\n b. If no scope was found, load X/index.js as a CommonJS module. STOP.\n c. If the SCOPE/package.json contains \"type\" field,\n 1. If the \"type\" field is \"module\", load X/index.js as an ECMAScript module. STOP.\n 2. Else, load X/index.js as a CommonJS module. STOP.\n2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n3. If X/index.node is a file, load X/index.node as binary addon. STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n a. Parse X/package.json, and look for \"main\" field.\n b. If \"main\" is a falsy value, GOTO 2.\n c. let M = X + (json main field)\n d. LOAD_AS_FILE(M)\n e. LOAD_INDEX(M)\n f. LOAD_INDEX(X) DEPRECATED\n g. THROW \"not found\"\n2. LOAD_INDEX(X)\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS = NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n a. LOAD_PACKAGE_EXPORTS(X, DIR)\n b. LOAD_AS_FILE(DIR/X)\n c. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = []\n4. while I >= 0,\n a. if PARTS[I] = \"node_modules\", GOTO d.\n b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n c. DIRS = DIRS + DIR\n d. let I = I - 1\n5. return DIRS + GLOBAL_FOLDERS\n\nLOAD_PACKAGE_IMPORTS(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"imports\" is null or undefined, return.\n4. If `--no-require-module` is not enabled\n a. let CONDITIONS = [\"node\", \"require\", \"module-sync\"]\n b. Else, let CONDITIONS = [\"node\", \"require\"]\n5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),\n CONDITIONS) <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n6. RESOLVE_ESM_MATCH(MATCH).\n\nLOAD_PACKAGE_EXPORTS(X, DIR)\n1. Try to interpret X as a combination of NAME and SUBPATH where the name\n may have a @scope/ prefix and the subpath begins with a slash (`/`).\n2. If X does not match this pattern or DIR/NAME/package.json is not a file,\n return.\n3. Parse DIR/NAME/package.json, and look for \"exports\" field.\n4. If \"exports\" is null or undefined, return.\n5. If `--no-require-module` is not enabled\n a. let CONDITIONS = [\"node\", \"require\", \"module-sync\"]\n b. Else, let CONDITIONS = [\"node\", \"require\"]\n6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), \".\" + SUBPATH,\n `package.json` \"exports\", CONDITIONS) <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n7. RESOLVE_ESM_MATCH(MATCH)\n\nLOAD_PACKAGE_SELF(X, DIR)\n1. Find the closest package scope SCOPE to DIR.\n2. If no scope was found, return.\n3. If the SCOPE/package.json \"exports\" is null or undefined, return.\n4. If the SCOPE/package.json \"name\" is not the first segment of X, return.\n5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),\n \".\" + X.slice(\"name\".length), `package.json` \"exports\", [\"node\", \"require\"])\n <a href=\"esm.md#resolver-algorithm-specification\">defined in the ESM resolver</a>.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nRESOLVE_ESM_MATCH(MATCH)\n1. let RESOLVED_PATH = fileURLToPath(MATCH)\n2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension\n format. STOP\n3. THROW \"not found\"\n"
},
{
"textRaw": "Caching",
"name": "Caching",
"type": "misc",
"desc": "Modules are cached after the first time they are loaded. This means (among other\nthings) that every call to require('foo') will get exactly the same object\nreturned, if it would resolve to the same file.
Provided require.cache is not modified, multiple calls to require('foo')\nwill not cause the module code to be executed multiple times. This is an\nimportant feature. With it, \"partially done\" objects can be returned, thus\nallowing transitive dependencies to be loaded even when they would cause cycles.
To have a module execute code multiple times, export a function, and call that\nfunction.
", "miscs": [ { "textRaw": "Module caching caveats", "name": "Module caching caveats", "type": "misc", "desc": "Modules are cached based on their resolved filename. Since modules may resolve\nto a different filename based on the location of the calling module (loading\nfrom node_modules folders), it is not a guarantee that require('foo') will\nalways return the exact same object, if it would resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different\nresolved filenames can point to the same file, but the cache will still treat\nthem as different modules and will reload the file multiple times. For example,\nrequire('./foo') and require('./FOO') return two different objects,\nirrespective of whether or not ./foo and ./FOO are the same file.
Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.
\nThe built-in modules are defined within the Node.js source and are located in the\nlib/ folder.
Built-in modules can be identified using the node: prefix, in which case\nit bypasses the require cache. For instance, require('node:http') will\nalways return the built in HTTP module, even if there is require.cache entry\nby that name.
Some built-in modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built-in HTTP module, even if there is a file by that name.
The list of all the built-in modules can be retrieved from module.builtinModules.\nThe modules being all listed without the node: prefix, except those that mandate such\nprefix (as explained in the next section).
When being loaded by require(), some built-in modules must be requested with the\nnode: prefix. This requirement exists to prevent newly introduced built-in\nmodules from having a conflict with user land packages that already have\ntaken the name. Currently the built-in modules that requires the node: prefix are:
The list of these modules is exposed in module.builtinModules, including the prefix.
When there are circular require() calls, a module might not have finished\nexecuting when it is returned.
Consider this situation:
\na.js:
console.log('a starting');\nexports.done = false;\nconst b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');\n\nb.js:
console.log('b starting');\nexports.done = false;\nconst a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');\n\nmain.js:
console.log('main starting');\nconst a = require('./a.js');\nconst b = require('./b.js');\nconsole.log('in main, a.done = %j, b.done = %j', a.done, b.done);\n\nWhen main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop, an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.
By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done = true, b.done = true\n\nCareful planning is required to allow cyclic module dependencies to work\ncorrectly within an application.
" }, { "textRaw": "File modules", "name": "File modules", "type": "misc", "desc": "If the exact filename is not found, then Node.js will attempt to load the\nrequired filename with the added extensions: .js, .json, and finally\n.node. When loading a file that has a different extension (e.g. .cjs), its\nfull name must be passed to require(), including its file extension (e.g.\nrequire('./file.cjs')).
.json files are parsed as JSON text files, .node files are interpreted as\ncompiled addon modules loaded with process.dlopen(). Files using any other\nextension (or no extension at all) are parsed as JavaScript text files. Refer to\nthe Determining module system section to understand what parse goal will be\nused.
A required module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.
A required module prefixed with './' is relative to the file calling\nrequire(). That is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.
Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules folder.
If the given path does not exist, require() will throw a\nMODULE_NOT_FOUND error.
There are three ways in which a folder may be passed to require() as\nan argument.
The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:
{ \"name\" : \"some-library\",\n \"main\" : \"./lib/some-library.js\" }\n\nIf this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.
If there is no package.json file present in the directory, or if the\n\"main\" entry is missing or cannot be resolved, then Node.js\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the previous\nexample, then require('./some-library') would attempt to load:
./some-library/index.js./some-library/index.nodeIf these attempts fail, then Node.js will report the entire module as missing\nwith the default error:
\nError: Cannot find module 'some-library'\n\nIn all three above cases, an import('./some-library') call would result in a\nERR_UNSUPPORTED_DIR_IMPORT error. Using package subpath exports or\nsubpath imports can provide the same containment organization benefits as\nfolders as modules, and work for both require and import.
If the module identifier passed to require() is not a\nbuilt-in module, and does not begin with '/', '../', or\n'./', then Node.js starts at the directory of the current module, and\nadds /node_modules, and attempts to load the module from that location.\nNode.js will not append node_modules to a path already ending in\nnode_modules.
If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.
\nFor example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then Node.js would look in the following locations, in\nthis order:
/home/ry/projects/node_modules/bar.js/home/ry/node_modules/bar.js/home/node_modules/bar.js/node_modules/bar.jsThis allows programs to localize their dependencies, so that they do not\nclash.
\nIt is possible to require specific files or sub modules distributed with a\nmodule by including a path suffix after the module name. For instance\nrequire('example-module/path/to/file') would resolve path/to/file\nrelative to where example-module is located. The suffixed path follows the\nsame module resolution semantics.
If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then Node.js will search those paths for modules if they\nare not found elsewhere.
On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.
NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was defined.
NODE_PATH is still supported, but is less necessary now that the Node.js\necosystem has settled on a convention for locating dependent modules.\nSometimes deployments that rely on NODE_PATH show surprising behavior\nwhen people are unaware that NODE_PATH must be set. Sometimes a\nmodule's dependencies change, causing a different version (or even a\ndifferent module) to be loaded as the NODE_PATH is searched.
Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
\n$HOME/.node_modules$HOME/.node_libraries$PREFIX/lib/nodeWhere $HOME is the user's home directory, and $PREFIX is the Node.js\nconfigured node_prefix.
These are mostly for historic reasons.
\nIt is strongly encouraged to place dependencies in the local node_modules\nfolder. These will be loaded faster, and more reliably.
Before a module's code is executed, Node.js will wrap it with a function\nwrapper that looks like the following:
\n(function(exports, require, module, __filename, __dirname) {\n// Module code actually lives in here\n});\n\nBy doing this, Node.js achieves a few things:
\nvar, const, or let) scoped to\nthe module rather than the global object.module and exports objects that the implementor can use to export\nvalues from the module.__filename and __dirname, containing the\nmodule's absolute filename and directory path.The .mjs extension is reserved for ECMAScript Modules.\nSee Determining module system section for more info\nregarding which files are parsed as ECMAScript modules.
require() only supports loading ECMAScript modules that meet the following requirements:
await); and.mjs extension..js extension, and the closest package.json contains \"type\": \"module\".js extension, the closest package.json does not contain\n\"type\": \"commonjs\", and the module contains ES module syntax.If the ES Module being loaded meets the requirements, require() can load it and\nreturn the module namespace object. In this case it is similar to dynamic\nimport() but is run synchronously and returns the name space object\ndirectly.
With the following ES Modules:
\n// distance.mjs\nexport function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }\n\n// point.mjs\nexport default class Point {\n constructor(x, y) { this.x = x; this.y = y; }\n}\n\nA CommonJS module can load them with require():
const distance = require('./distance.mjs');\nconsole.log(distance);\n// [Module: null prototype] {\n// distance: [Function: distance]\n// }\n\nconst point = require('./point.mjs');\nconsole.log(point);\n// [Module: null prototype] {\n// default: [class Point],\n// __esModule: true,\n// }\n\nFor interoperability with existing tools that convert ES Modules into CommonJS,\nwhich could then load real ES Modules through require(), the returned namespace\nwould contain a __esModule: true property if it has a default export so that\nconsuming code generated by tools can recognize the default exports in real\nES Modules. If the namespace already defines __esModule, this would not be added.\nThis property is experimental and can change in the future. It should only be used\nby tools converting ES modules into CommonJS modules, following existing ecosystem\nconventions. Code authored directly in CommonJS should avoid depending on it.
The result returned by require() is the module namespace object, which places\nthe default export in the .default property, similar to the results returned by import().\nTo customize what should be returned by require(esm) directly, the ES Module can export the\ndesired value using the string name \"module.exports\".
// point.mjs\nexport default class Point {\n constructor(x, y) { this.x = x; this.y = y; }\n}\n\n// `distance` is lost to CommonJS consumers of this module, unless it's\n// added to `Point` as a static property.\nexport function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }\nexport { Point as 'module.exports' }\n\nconst Point = require('./point.mjs');\nconsole.log(Point); // [class Point]\n\n// Named exports are lost when 'module.exports' is used\nconst { distance } = require('./point.mjs');\nconsole.log(distance); // undefined\n\nNotice in the example above, when the module.exports export name is used, named exports\nwill be lost to CommonJS consumers. To allow CommonJS consumers to continue accessing\nnamed exports, the module can make sure that the default export is an object with the\nnamed exports attached to it as properties. For example with the example above,\ndistance can be attached to the default export, the Point class, as a static method.
export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }\n\nexport default class Point {\n constructor(x, y) { this.x = x; this.y = y; }\n static distance = distance;\n}\n\nexport { Point as 'module.exports' }\n\nconst Point = require('./point.mjs');\nconsole.log(Point); // [class Point]\n\nconst { distance } = require('./point.mjs');\nconsole.log(distance); // [Function: distance]\n\nIf the module being require()'d contains top-level await, or the module\ngraph it imports contains top-level await,\nERR_REQUIRE_ASYNC_MODULE will be thrown. In this case, users should\nload the asynchronous module using import().
If --experimental-print-required-tla is enabled, instead of throwing\nERR_REQUIRE_ASYNC_MODULE before evaluation, Node.js will evaluate the\nmodule, try to locate the top-level awaits, and print their location to\nhelp users fix them.
If support for loading ES modules using require() results in unexpected\nbreakage, it can be disabled using --no-require-module.\nTo print where this feature is used, use --trace-require-module.
This feature can be detected by checking if\nprocess.features.require_module is true.
<string>The directory name of the current module. This is the same as the\npath.dirname() of the __filename.
Example: running node example.js from /Users/mjr
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n",
"displayName": "`__dirname`"
},
{
"textRaw": "`__filename`",
"name": "`__filename`",
"type": "module",
"meta": {
"added": [
"v0.0.1"
],
"changes": []
},
"desc": "<string>The file name of the current module. This is the current module file's absolute\npath with symlinks resolved.
\nFor a main program this is not necessarily the same as the file name used in the\ncommand line.
\nSee __dirname for the directory name of the current module.
Examples:
\nRunning node example.js from /Users/mjr
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n\nGiven two modules: a and b, where b is a dependency of\na and there is a directory structure of:
/Users/mjr/app/a.js/Users/mjr/app/node_modules/b/b.jsReferences to __filename within b.js will return\n/Users/mjr/app/node_modules/b/b.js while references to __filename within\na.js will return /Users/mjr/app/a.js.
<Object>A reference to the module.exports that is shorter to type.\nSee the section about the exports shortcut for details on when to use\nexports and when to use module.exports.
<module>A reference to the current module, see the section about the\nmodule object. In particular, module.exports is used for defining what\na module exports and makes available through require().
Used to import modules, JSON, and local files. Modules can be imported\nfrom node_modules. Local modules and JSON files can be imported using\na relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be\nresolved against the directory named by __dirname (if defined) or\nthe current working directory. The relative paths of POSIX style are resolved\nin an OS independent fashion, meaning that the examples above will work on\nWindows in the same way they would on Unix systems.
// Importing a local module with a path relative to the `__dirname` or current\n// working directory. (On Windows, this would resolve to .\\path\\myLocalModule.)\nconst myLocalModule = require('./path/myLocalModule');\n\n// Importing a JSON file:\nconst jsonData = require('./path/filename.json');\n\n// Importing a module from node_modules or Node.js built-in module:\nconst crypto = require('node:crypto');\n",
"properties": [
{
"textRaw": "Type: {Object}",
"name": "cache",
"type": "Object",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"desc": "Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\nThis does not apply to native addons, for which reloading will result in an\nerror.
Adding or replacing entries is also possible. This cache is checked before\nbuilt-in modules and if a name matching a built-in module is added to the cache,\nonly node:-prefixed require calls are going to receive the built-in module.\nUse with care!
const assert = require('node:assert');\nconst realFs = require('node:fs');\n\nconst fakeFs = {};\nrequire.cache.fs = { exports: fakeFs };\n\nassert.strictEqual(require('fs'), fakeFs);\nassert.strictEqual(require('node:fs'), realFs);\n"
},
{
"textRaw": "Type: {Object}",
"name": "extensions",
"type": "Object",
"meta": {
"added": [
"v0.3.0"
],
"changes": [],
"deprecated": [
"v0.10.6"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"desc": "Instruct require on how to handle certain file extensions.
Process files with the extension .sjs as .js:
require.extensions['.sjs'] = require.extensions['.js'];\n\nDeprecated. In the past, this list has been used to load non-JavaScript\nmodules into Node.js by compiling them on-demand. However, in practice, there\nare much better ways to do this, such as loading modules via some other Node.js\nprogram, or compiling them to JavaScript ahead of time.
\nAvoid using require.extensions. Use could cause subtle bugs and resolving the\nextensions gets slower with each registered extension.
The Module object representing the entry script loaded when the Node.js\nprocess launched, or undefined if the entry point of the program is not a\nCommonJS module.\nSee \"Accessing the main module\".
In entry.js script:
console.log(require.main);\n\nnode entry.js\n\nModule {\n id: '.',\n path: '/absolute/path/to',\n exports: {},\n filename: '/absolute/path/to/entry.js',\n loaded: false,\n children: [],\n paths:\n [ '/absolute/path/to/node_modules',\n '/absolute/path/node_modules',\n '/absolute/node_modules',\n '/node_modules' ] }\n"
}
],
"methods": [
{
"textRaw": "`require.resolve(request[, options])`",
"name": "resolve",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": [
{
"version": "v8.9.0",
"pr-url": "https://github.com/nodejs/node/pull/16397",
"description": "The `paths` option is now supported."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`request` {string} The module path to resolve.",
"name": "request",
"type": "string",
"desc": "The module path to resolve."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`paths` {string[]} Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of GLOBAL_FOLDERS like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location.",
"name": "paths",
"type": "string[]",
"desc": "Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of GLOBAL_FOLDERS like `$HOME/.node_modules`, which are always included. Each of these paths is used as a starting point for the module resolution algorithm, meaning that the `node_modules` hierarchy is checked from this location."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
}
}
],
"desc": "Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.
If the module can not be found, a MODULE_NOT_FOUND error is thrown.
Returns an array containing the paths searched during resolution of request or\nnull if the request string references a core module, for example http or\nfs.
<Object>In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module is not actually\na global but rather local to each module.
The module objects required for the first time by this one.
" }, { "textRaw": "Type: {Object}", "name": "exports", "type": "Object", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "The module.exports object is created by the Module system. Sometimes this is\nnot acceptable; many want their module to be an instance of some class. To do\nthis, assign the desired export object to module.exports. Assigning\nthe desired object to exports will simply rebind the local exports variable,\nwhich is probably not what is desired.
For example, suppose we were making a module called a.js:
const EventEmitter = require('node:events');\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(() => {\n module.exports.emit('ready');\n}, 1000);\n\nThen in another file we could do:
\nconst a = require('./a');\na.on('ready', () => {\n console.log('module \"a\" is ready');\n});\n\nAssignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:
x.js:
setTimeout(() => {\n module.exports = { a: 'hello' };\n}, 0);\n\ny.js:
const x = require('./x');\nconsole.log(x.a);\n",
"modules": [
{
"textRaw": "`exports` shortcut",
"name": "`exports`_shortcut",
"type": "module",
"meta": {
"added": [
"v0.1.16"
],
"changes": []
},
"desc": "The exports variable is available within a module's file-level scope, and is\nassigned the value of module.exports before the module is evaluated.
It allows a shortcut, so that module.exports.f = ... can be written more\nsuccinctly as exports.f = .... However, be aware that like any variable, if a\nnew value is assigned to exports, it is no longer bound to module.exports:
module.exports.hello = true; // Exported from require of module\nexports = { hello: false }; // Not exported, only available in the module\n\nWhen the module.exports property is being completely replaced by a new\nobject, it is common to also reassign exports:
module.exports = exports = function Constructor() {\n // ... etc.\n};\n\nTo illustrate the behavior, imagine this hypothetical implementation of\nrequire(), which is quite similar to what is actually done by require():
function require(/* ... */) {\n const module = { exports: {} };\n ((module, exports) => {\n // Module code here. In this example, define a function.\n function someFunc() {}\n exports = someFunc;\n // At this point, exports is no longer a shortcut to module.exports, and\n // this module will still export an empty default object.\n module.exports = someFunc;\n // At this point, the module will now export someFunc, instead of the\n // default object.\n })(module, module.exports);\n return module.exports;\n}\n",
"displayName": "`exports` shortcut"
}
]
},
{
"textRaw": "Type: {string}",
"name": "filename",
"type": "string",
"meta": {
"added": [
"v0.1.16"
],
"changes": []
},
"desc": "The fully resolved filename of the module.
" }, { "textRaw": "Type: {string}", "name": "id", "type": "string", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "The identifier for the module. Typically this is the fully resolved\nfilename.
" }, { "textRaw": "Type: {boolean} `true` if the module is running during the Node.js preload phase.", "name": "isPreloading", "type": "boolean", "meta": { "added": [ "v15.4.0", "v14.17.0" ], "changes": [] }, "desc": "`true` if the module is running during the Node.js preload phase." }, { "textRaw": "Type: {boolean}", "name": "loaded", "type": "boolean", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "Whether or not the module is done loading, or is in the process of\nloading.
" }, { "textRaw": "Type: {module|null|undefined}", "name": "parent", "type": "module|null|undefined", "meta": { "added": [ "v0.1.16" ], "changes": [], "deprecated": [ "v14.6.0", "v12.19.0" ] }, "stability": 0, "stabilityText": "Deprecated: Please use `require.main` and `module.children` instead.", "desc": "The module that first required this one, or null if the current module is the\nentry point of the current process, or undefined if the module was loaded by\nsomething that is not a CommonJS module (E.G.: REPL or import).
The directory name of the module. This is usually the same as the\npath.dirname() of the module.id.
The search paths for the module.
" } ], "methods": [ { "textRaw": "`module.require(id)`", "name": "require", "type": "method", "meta": { "added": [ "v0.5.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string}", "name": "id", "type": "string" } ], "return": { "textRaw": "Returns: {any} exported module content", "name": "return", "type": "any", "desc": "exported module content" } } ], "desc": "The module.require() method provides a way to load a module as if\nrequire() was called from the original module.
In order to do this, it is necessary to get a reference to the module object.\nSince require() returns the module.exports, and the module is typically\nonly available within a specific module's code, it must be explicitly exported\nin order to be used.
This section was moved to\nModules: module core module.
This section was moved to\nModules: module core module.
<Object>Provides general utility methods when interacting with instances of\nModule, the module variable often seen in CommonJS modules. Accessed\nvia import 'node:module' or require('node:module').
A list of the names of all modules provided by Node.js. Can be used to verify\nif a module is maintained by a third party or not.
\nmodule in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:
// module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'node:module';\n\n// module.cjs\n// In a CommonJS module\nconst builtin = require('node:module').builtinModules;\n"
}
],
"methods": [
{
"textRaw": "`module.createRequire(filename)`",
"name": "createRequire",
"type": "method",
"meta": {
"added": [
"v12.2.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`filename` {string|URL} Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string.",
"name": "filename",
"type": "string|URL",
"desc": "Filename to be used to construct the require function. Must be a file URL object, file URL string, or absolute path string."
}
],
"return": {
"textRaw": "Returns: {require} Require function",
"name": "return",
"type": "require",
"desc": "Require function"
}
}
],
"desc": "import { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n"
},
{
"textRaw": "`module.findPackageJSON(specifier[, base])`",
"name": "findPackageJSON",
"type": "method",
"meta": {
"added": [
"v23.2.0",
"v22.14.0"
],
"changes": []
},
"stability": 1.1,
"stabilityText": "Active Development",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string|URL} The specifier for the module whose `package.json` to retrieve. When passing a _bare specifier_, the `package.json` at the root of the package is returned. When passing a _relative specifier_ or an _absolute specifier_, the closest parent `package.json` is returned.",
"name": "specifier",
"type": "string|URL",
"desc": "The specifier for the module whose `package.json` to retrieve. When passing a _bare specifier_, the `package.json` at the root of the package is returned. When passing a _relative specifier_ or an _absolute specifier_, the closest parent `package.json` is returned."
},
{
"textRaw": "`base` {string|URL} The absolute location (`file:` URL string or FS path) of the containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use `import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`.",
"name": "base",
"type": "string|URL",
"desc": "The absolute location (`file:` URL string or FS path) of the containing module. For CJS, use `__filename` (not `__dirname`!); for ESM, use `import.meta.url`. You do not need to pass it if `specifier` is an `absolute specifier`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {string|undefined} A path if the `package.json` is found. When `specifier` is a package, the package's root `package.json`; when a relative or unresolved, the closest `package.json` to the `specifier`.",
"name": "return",
"type": "string|undefined",
"desc": "A path if the `package.json` is found. When `specifier` is a package, the package's root `package.json`; when a relative or unresolved, the closest `package.json` to the `specifier`."
}
}
],
"desc": "\n\nCaveat: Do not use this to try to determine module format. There are many things affecting\nthat determination; the
\ntypefield of package.json is the least definitive (ex file extension\nsupersedes it, and a loader hook supersedes that).
\n\nCaveat: This currently leverages only the built-in default resolver; if\n
\nresolvecustomization hooks are registered, they will not affect the resolution.\nThis may change in the future.
/path/to/project\n ├ packages/\n ├ bar/\n ├ bar.js\n └ package.json // name = '@foo/bar'\n └ qux/\n ├ node_modules/\n └ some-package/\n └ package.json // name = 'some-package'\n ├ qux.js\n └ package.json // name = '@foo/qux'\n ├ main.js\n └ package.json // name = '@foo'\n\n// /path/to/project/packages/bar/bar.js\nimport { findPackageJSON } from 'node:module';\n\nfindPackageJSON('..', import.meta.url);\n// '/path/to/project/package.json'\n// Same result when passing an absolute specifier instead:\nfindPackageJSON(new URL('../', import.meta.url));\nfindPackageJSON(import.meta.resolve('../'));\n\nfindPackageJSON('some-package', import.meta.url);\n// '/path/to/project/packages/bar/node_modules/some-package/package.json'\n// When passing an absolute specifier, you might get a different result if the\n// resolved module is inside a subfolder that has nested `package.json`.\nfindPackageJSON(import.meta.resolve('some-package'));\n// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'\n\nfindPackageJSON('@foo/qux', import.meta.url);\n// '/path/to/project/packages/qux/package.json'\n\n// /path/to/project/packages/bar/bar.js\nconst { findPackageJSON } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst path = require('node:path');\n\nfindPackageJSON('..', __filename);\n// '/path/to/project/package.json'\n// Same result when passing an absolute specifier instead:\nfindPackageJSON(pathToFileURL(path.join(__dirname, '..')));\n\nfindPackageJSON('some-package', __filename);\n// '/path/to/project/packages/bar/node_modules/some-package/package.json'\n// When passing an absolute specifier, you might get a different result if the\n// resolved module is inside a subfolder that has nested `package.json`.\nfindPackageJSON(pathToFileURL(require.resolve('some-package')));\n// '/path/to/project/packages/bar/node_modules/some-package/some-subfolder/package.json'\n\nfindPackageJSON('@foo/qux', __filename);\n// '/path/to/project/packages/qux/package.json'\n"
},
{
"textRaw": "`module.isBuiltin(moduleName)`",
"name": "isBuiltin",
"type": "method",
"meta": {
"added": [
"v18.6.0",
"v16.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`moduleName` {string} name of the module",
"name": "moduleName",
"type": "string",
"desc": "name of the module"
}
],
"return": {
"textRaw": "Returns: {boolean} returns true if the module is builtin else returns false",
"name": "return",
"type": "boolean",
"desc": "returns true if the module is builtin else returns false"
}
}
],
"desc": "import { isBuiltin } from 'node:module';\nisBuiltin('node:fs'); // true\nisBuiltin('fs'); // true\nisBuiltin('wss'); // false\n"
},
{
"textRaw": "`module.register(specifier[, parentURL][, options])`",
"name": "register",
"type": "method",
"meta": {
"added": [
"v20.6.0",
"v18.19.0"
],
"changes": [
{
"version": [
"v23.6.1",
"v22.13.1",
"v20.18.2"
],
"pr-url": "https://github.com/nodejs-private/node-private/pull/629",
"description": "Using this feature with the permission model enabled requires passing `--allow-worker`."
},
{
"version": [
"v20.8.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49655",
"description": "Add support for WHATWG URL instances."
}
]
},
"stability": 1.1,
"stabilityText": "Active development",
"signatures": [
{
"params": [
{
"textRaw": "`specifier` {string|URL} Customization hooks to be registered; this should be the same string that would be passed to `import()`, except that if it is relative, it is resolved relative to `parentURL`.",
"name": "specifier",
"type": "string|URL",
"desc": "Customization hooks to be registered; this should be the same string that would be passed to `import()`, except that if it is relative, it is resolved relative to `parentURL`."
},
{
"textRaw": "`parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. **Default:** `'data:'`",
"name": "parentURL",
"type": "string|URL",
"default": "`'data:'`",
"desc": "If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`parentURL` {string|URL} If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. This property is ignored if the `parentURL` is supplied as the second argument. **Default:** `'data:'`",
"name": "parentURL",
"type": "string|URL",
"default": "`'data:'`",
"desc": "If you want to resolve `specifier` relative to a base URL, such as `import.meta.url`, you can pass that URL here. This property is ignored if the `parentURL` is supplied as the second argument."
},
{
"textRaw": "`data` {any} Any arbitrary, cloneable JavaScript value to pass into the `initialize` hook.",
"name": "data",
"type": "any",
"desc": "Any arbitrary, cloneable JavaScript value to pass into the `initialize` hook."
},
{
"textRaw": "`transferList` {Object[]} transferable objects to be passed into the `initialize` hook.",
"name": "transferList",
"type": "Object[]",
"desc": "transferable objects to be passed into the `initialize` hook."
}
],
"optional": true
}
]
}
],
"desc": "Register a module that exports hooks that customize Node.js module\nresolution and loading behavior. See Customization hooks.
\nThis feature requires --allow-worker if used with the Permission Model.
Register hooks that customize Node.js module resolution and loading behavior.\nSee Customization hooks.
" }, { "textRaw": "`module.stripTypeScriptTypes(code[, options])`", "name": "stripTypeScriptTypes", "type": "method", "meta": { "added": [ "v23.2.0", "v22.13.0" ], "changes": [] }, "stability": 1.2, "stabilityText": "Release candidate", "signatures": [ { "params": [ { "textRaw": "`code` {string} The code to strip type annotations from.", "name": "code", "type": "string", "desc": "The code to strip type annotations from." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`mode` {string} **Default:** `'strip'`. Possible values are:", "name": "mode", "type": "string", "default": "`'strip'`. Possible values are:", "options": [ { "textRaw": "`'strip'` Only strip type annotations without performing the transformation of TypeScript features.", "desc": "`'strip'` Only strip type annotations without performing the transformation of TypeScript features." }, { "textRaw": "`'transform'` Strip type annotations and transform TypeScript features to JavaScript.", "desc": "`'transform'` Strip type annotations and transform TypeScript features to JavaScript." } ] }, { "textRaw": "`sourceMap` {boolean} **Default:** `false`. Only when `mode` is `'transform'`, if `true`, a source map will be generated for the transformed code.", "name": "sourceMap", "type": "boolean", "default": "`false`. Only when `mode` is `'transform'`, if `true`, a source map will be generated for the transformed code" }, { "textRaw": "`sourceUrl` {string} Specifies the source url used in the source map.", "name": "sourceUrl", "type": "string", "desc": "Specifies the source url used in the source map." } ], "optional": true } ], "return": { "textRaw": "Returns: {string} The code with type annotations stripped.", "name": "return", "type": "string", "desc": "The code with type annotations stripped." } } ], "desc": "module.stripTypeScriptTypes() removes type annotations from TypeScript code. It\ncan be used to strip type annotations from TypeScript code before running it\nwith vm.runInContext() or vm.compileFunction().
By default, it will throw an error if the code contains TypeScript features\nthat require transformation such as Enums,\nsee type-stripping for more information.
When mode is 'transform', it also transforms TypeScript features to JavaScript,\nsee transform TypeScript features for more information.
When mode is 'strip', source maps are not generated, because locations are preserved.\nIf sourceMap is provided, when mode is 'strip', an error will be thrown.
WARNING: The output of this function should not be considered stable across Node.js versions,\ndue to changes in the TypeScript parser.
\nimport { stripTypeScriptTypes } from 'node:module';\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code);\nconsole.log(strippedCode);\n// Prints: const a = 1;\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code);\nconsole.log(strippedCode);\n// Prints: const a = 1;\n\nIf sourceUrl is provided, it will be used appended as a comment at the end of the output:
import { stripTypeScriptTypes } from 'node:module';\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });\nconsole.log(strippedCode);\n// Prints: const a = 1\\n\\n//# sourceURL=source.ts;\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = 'const a: number = 1;';\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'strip', sourceUrl: 'source.ts' });\nconsole.log(strippedCode);\n// Prints: const a = 1\\n\\n//# sourceURL=source.ts;\n\nWhen mode is 'transform', the code is transformed to JavaScript:
import { stripTypeScriptTypes } from 'node:module';\nconst code = `\n namespace MathUtil {\n export const add = (a: number, b: number) => a + b;\n }`;\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });\nconsole.log(strippedCode);\n// Prints:\n// var MathUtil;\n// (function(MathUtil) {\n// MathUtil.add = (a, b)=>a + b;\n// })(MathUtil || (MathUtil = {}));\n// # sourceMappingURL=data:application/json;base64, ...\n\nconst { stripTypeScriptTypes } = require('node:module');\nconst code = `\n namespace MathUtil {\n export const add = (a: number, b: number) => a + b;\n }`;\nconst strippedCode = stripTypeScriptTypes(code, { mode: 'transform', sourceMap: true });\nconsole.log(strippedCode);\n// Prints:\n// var MathUtil;\n// (function(MathUtil) {\n// MathUtil.add = (a, b)=>a + b;\n// })(MathUtil || (MathUtil = {}));\n// # sourceMappingURL=data:application/json;base64, ...\n"
},
{
"textRaw": "`module.syncBuiltinESMExports()`",
"name": "syncBuiltinESMExports",
"type": "method",
"meta": {
"added": [
"v12.12.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "The module.syncBuiltinESMExports() method updates all the live bindings for\nbuiltin ES Modules to match the properties of the CommonJS exports. It\ndoes not add or remove exported names from the ES Modules.
const fs = require('node:fs');\nconst assert = require('node:assert');\nconst { syncBuiltinESMExports } = require('node:module');\n\nfs.readFile = newAPI;\n\ndelete fs.readFileSync;\n\nfunction newAPI() {\n // ...\n}\n\nfs.newAPI = newAPI;\n\nsyncBuiltinESMExports();\n\nimport('node:fs').then((esmFS) => {\n // It syncs the existing readFile property with the new value\n assert.strictEqual(esmFS.readFile, newAPI);\n // readFileSync has been deleted from the required fs\n assert.strictEqual('readFileSync' in fs, false);\n // syncBuiltinESMExports() does not remove readFileSync from esmFS\n assert.strictEqual('readFileSync' in esmFS, true);\n // syncBuiltinESMExports() does not add names\n assert.strictEqual(esmFS.newAPI, undefined);\n});\n"
}
],
"displayName": "The `Module` object"
},
{
"textRaw": "Module compile cache",
"name": "module_compile_cache",
"type": "module",
"meta": {
"added": [
"v22.1.0"
],
"changes": [
{
"version": "v22.8.0",
"pr-url": "https://github.com/nodejs/node/pull/54501",
"description": "add initial JavaScript APIs for runtime access."
}
]
},
"desc": "The module compile cache can be enabled either using the module.enableCompileCache()\nmethod or the NODE_COMPILE_CACHE=dir environment variable. After it is enabled,\nwhenever Node.js compiles a CommonJS, a ECMAScript Module, or a TypeScript module, it will\nuse on-disk V8 code cache persisted in the specified directory to speed up the compilation.\nThis may slow down the first load of a module graph, but subsequent loads of the same module\ngraph may get a significant speedup if the contents of the modules do not change.
To clean up the generated compile cache on disk, simply remove the cache directory. The cache\ndirectory will be recreated the next time the same directory is used for for compile cache\nstorage. To avoid filling up the disk with stale cache, it is recommended to use a directory\nunder the os.tmpdir(). If the compile cache is enabled by a call to\nmodule.enableCompileCache() without specifying the directory, Node.js will use\nthe NODE_COMPILE_CACHE=dir environment variable if it's set, or defaults\nto path.join(os.tmpdir(), 'node-compile-cache') otherwise. To locate the compile cache\ndirectory used by a running Node.js instance, use module.getCompileCacheDir().
The enabled module compile cache can be disabled by the NODE_DISABLE_COMPILE_CACHE=1\nenvironment variable. This can be useful when the compile cache leads to unexpected or\nundesired behaviors (e.g. less precise test coverage).
At the moment, when the compile cache is enabled and a module is loaded afresh, the\ncode cache is generated from the compiled code immediately, but will only be written\nto disk when the Node.js instance is about to exit. This is subject to change. The\nmodule.flushCompileCache() method can be used to ensure the accumulated code cache\nis flushed to disk in case the application wants to spawn other Node.js instances\nand let them share the cache long before the parent exits.
The compile cache layout on disk is an implementation detail and should not be\nrelied upon. The compile cache generated is typically only reusable in the same\nversion of Node.js, and should be not assumed to be compatible across different\nversions of Node.js.
", "modules": [ { "textRaw": "Portability of the compile cache", "name": "portability_of_the_compile_cache", "type": "module", "desc": "By default, caches are invalidated when the absolute paths of the modules being\ncached are changed. To keep the cache working after moving the\nproject directory, enable portable compile cache. This allows previously compiled\nmodules to be reused across different directory locations as long as the layout relative\nto the cache directory remains the same. This would be done on a best-effort basis. If\nNode.js cannot compute the location of a module relative to the cache directory, the module\nwill not be cached.
\nThere are two ways to enable the portable mode:
\nUsing the portable option in module.enableCompileCache():
// Non-portable cache (default): cache breaks if project is moved\nmodule.enableCompileCache({ directory: '/path/to/cache/storage/dir' });\n\n// Portable cache: cache works after the project is moved\nmodule.enableCompileCache({ directory: '/path/to/cache/storage/dir', portable: true });\n\nSetting the environment variable: NODE_COMPILE_CACHE_PORTABLE=1
Currently when using the compile cache with V8 JavaScript code coverage, the\ncoverage being collected by V8 may be less precise in functions that are\ndeserialized from the code cache. It's recommended to turn this off when\nrunning tests to generate precise coverage.
\nCompilation cache generated by one version of Node.js can not be reused by a different\nversion of Node.js. Cache generated by different versions of Node.js will be stored\nseparately if the same base directory is used to persist the cache, so they can co-exist.
", "displayName": "Limitations of the compile cache" } ], "properties": [ { "textRaw": "`module.constants.compileCacheStatus`", "name": "compileCacheStatus", "type": "property", "meta": { "added": [ "v22.8.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60971", "description": "This feature is no longer experimental." } ] }, "desc": "The following constants are returned as the status field in the object returned by\nmodule.enableCompileCache() to indicate the result of the attempt to enable the\nmodule compile cache.
| Constant | Description |
|---|---|
ENABLED | \n Node.js has enabled the compile cache successfully. The directory used to store the\n compile cache will be returned in the directory field in the\n returned object.\n |
ALREADY_ENABLED | \n The compile cache has already been enabled before, either by a previous call to\n module.enableCompileCache(), or by the NODE_COMPILE_CACHE=dir\n environment variable. The directory used to store the\n compile cache will be returned in the directory field in the\n returned object.\n |
FAILED | \n Node.js fails to enable the compile cache. This can be caused by the lack of\n permission to use the specified directory, or various kinds of file system errors.\n The detail of the failure will be returned in the message field in the\n returned object.\n |
DISABLED | \n Node.js cannot enable the compile cache because the environment variable\n NODE_DISABLE_COMPILE_CACHE=1 has been set.\n |
Enable module compile cache in the current Node.js instance.
\nFor general use cases, it's recommended to call module.enableCompileCache() without\nspecifying the options.directory, so that the directory can be overridden by the\nNODE_COMPILE_CACHE environment variable when necessary.
Since compile cache is supposed to be a optimization that is not mission critical, this\nmethod is designed to not throw any exception when the compile cache cannot be enabled.\nInstead, it will return an object containing an error message in the message field to\naid debugging. If compile cache is enabled successfully, the directory field in the\nreturned object contains the path to the directory where the compile cache is stored. The\nstatus field in the returned object would be one of the module.constants.compileCacheStatus\nvalues to indicate the result of the attempt to enable the module compile cache.
This method only affects the current Node.js instance. To enable it in child worker threads,\neither call this method in child worker threads too, or set the\nprocess.env.NODE_COMPILE_CACHE value to compile cache directory so the behavior can\nbe inherited into the child workers. The directory can be obtained either from the\ndirectory field returned by this method, or with module.getCompileCacheDir().
Flush the module compile cache accumulated from modules already loaded\nin the current Node.js instance to disk. This returns after all the flushing\nfile system operations come to an end, no matter they succeed or not. If there\nare any errors, this will fail silently, since compile cache misses should not\ninterfere with the actual operation of the application.
" }, { "textRaw": "`module.getCompileCacheDir()`", "name": "getCompileCacheDir", "type": "method", "meta": { "added": [ "v22.8.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60971", "description": "This feature is no longer experimental." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string|undefined} Path to the module compile cache directory if it is enabled, or `undefined` otherwise.", "name": "return", "type": "string|undefined", "desc": "Path to the module compile cache directory if it is enabled, or `undefined` otherwise." } } ], "desc": "" } ], "displayName": "Module compile cache" }, { "textRaw": "Source Map Support", "name": "source_map_support", "type": "module", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "
Node.js supports TC39 ECMA-426 Source Map format (it was called Source map\nrevision 3 format).
\nThe APIs in this section are helpers for interacting with the source map\ncache. This cache is populated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.
\nTo enable source map parsing, Node.js must be run with the flag\n--enable-source-maps, or with code coverage enabled by setting\nNODE_V8_COVERAGE=dir, or be enabled programmatically via\nmodule.setSourceMapsSupport().
// module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'node:module';\n\n// module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('node:module');\n",
"methods": [
{
"textRaw": "`module.getSourceMapsSupport()`",
"name": "getSourceMapsSupport",
"type": "method",
"meta": {
"added": [
"v23.7.0",
"v22.14.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`enabled` {boolean} If the source maps support is enabled",
"name": "enabled",
"type": "boolean",
"desc": "If the source maps support is enabled"
},
{
"textRaw": "`nodeModules` {boolean} If the support is enabled for files in `node_modules`.",
"name": "nodeModules",
"type": "boolean",
"desc": "If the support is enabled for files in `node_modules`."
},
{
"textRaw": "`generatedCode` {boolean} If the support is enabled for generated code from `eval` or `new Function`.",
"name": "generatedCode",
"type": "boolean",
"desc": "If the support is enabled for generated code from `eval` or `new Function`."
}
]
}
}
],
"desc": "This method returns whether the Source Map v3 support for stack\ntraces is enabled.
\n" }, { "textRaw": "`module.findSourceMap(path)`", "name": "findSourceMap", "type": "method", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ], "return": { "textRaw": "Returns: {module.SourceMap|undefined} Returns `module.SourceMap` if a source map is found, `undefined` otherwise.", "name": "return", "type": "module.SourceMap|undefined", "desc": "Returns `module.SourceMap` if a source map is found, `undefined` otherwise." } } ], "desc": "path is the resolved path for the file for which a corresponding source map\nshould be fetched.
This function enables or disables the Source Map v3 support for\nstack traces.
\nIt provides same features as launching Node.js process with commandline options\n--enable-source-maps, with additional options to alter the support for files\nin node_modules or generated codes.
Only source maps in JavaScript files that are loaded after source maps has been\nenabled will be parsed and loaded. Preferably, use the commandline options\n--enable-source-maps to avoid losing track of source maps of modules loaded\nbefore this API call.
Creates a new sourceMap instance.
payload is an object with keys matching the Source map format:
file <string>version <number>sources <string[]>sourcesContent <string[]>names <string[]>mappings <string>sourceRoot <string>lineLengths is an optional array of the length of each line in the\ngenerated code.
Getter for the payload used to construct the SourceMap instance.
Given a line offset and column offset in the generated source\nfile, returns an object representing the SourceMap range in the\noriginal file if found, or an empty object if not.
\nThe object returned contains the following keys:
\ngeneratedLine <number> The line offset of the start of the\nrange in the generated sourcegeneratedColumn <number> The column offset of start of the\nrange in the generated sourceoriginalSource <string> The file name of the original source,\nas reported in the SourceMaporiginalLine <number> The line offset of the start of the\nrange in the original sourceoriginalColumn <number> The column offset of start of the\nrange in the original sourcename <string>The returned value represents the raw range as it appears in the\nSourceMap, based on zero-indexed offsets, not 1-indexed line and\ncolumn numbers as they appear in Error messages and CallSite\nobjects.
\nTo get the corresponding 1-indexed line and column numbers from a\nlineNumber and columnNumber as they are reported by Error stacks\nand CallSite objects, use sourceMap.findOrigin(lineNumber, columnNumber)
Given a 1-indexed lineNumber and columnNumber from a call site in\nthe generated source, find the corresponding call site location\nin the original source.
If the lineNumber and columnNumber provided are not found in any\nsource map, then an empty object is returned. Otherwise, the\nreturned object contains the following keys:
name <string> | <undefined> The name of the range in the\nsource map, if one was providedfileName <string> The file name of the original source, as\nreported in the SourceMaplineNumber <number> The 1-indexed lineNumber of the\ncorresponding call site in the original sourcecolumnNumber <number> The 1-indexed columnNumber of the\ncorresponding call site in the original sourceNode.js currently supports two types of module customization hooks:
\nmodule.registerHooks(options): takes synchronous hook\nfunctions that are run directly on the thread where the modules are loaded.module.register(specifier[, parentURL][, options]): takes specifier to a\nmodule that exports asynchronous hook functions. The functions are run on a\nseparate loader thread.The asynchronous hooks incur extra overhead from inter-thread communication,\nand have several caveats especially\nwhen customizing CommonJS modules in the module graph.\nIn most cases, it's recommended to use synchronous hooks via module.registerHooks()\nfor simplicity.
", "modules": [ { "textRaw": "Registration of synchronous customization hooks", "name": "registration_of_synchronous_customization_hooks", "type": "module", "desc": "
To register synchronous customization hooks, use module.registerHooks(), which\ntakes synchronous hook functions directly in-line.
// register-hooks.js\nimport { registerHooks } from 'node:module';\nregisterHooks({\n resolve(specifier, context, nextResolve) { /* implementation */ },\n load(url, context, nextLoad) { /* implementation */ },\n});\n\n// register-hooks.js\nconst { registerHooks } = require('node:module');\nregisterHooks({\n resolve(specifier, context, nextResolve) { /* implementation */ },\n load(url, context, nextLoad) { /* implementation */ },\n});\n",
"modules": [
{
"textRaw": "Registering hooks before application code runs with flags",
"name": "registering_hooks_before_application_code_runs_with_flags",
"type": "module",
"desc": "The hooks can be registered before the application code is run by using the\n--import or --require flag:
node --import ./register-hooks.js ./my-app.js\nnode --require ./register-hooks.js ./my-app.js\n\nThe specifier passed to --import or --require can also come from a package:
node --import some-package/register ./my-app.js\nnode --require some-package/register ./my-app.js\n\nWhere some-package has an \"exports\" field defining the /register\nexport to map to a file that calls registerHooks(), like the\nregister-hooks.js examples above.
Using --import or --require ensures that the hooks are registered before any\napplication code is loaded, including the entry point of the application and for\nany worker threads by default as well.
Alternatively, registerHooks() can be called from the entry point.
If the entry point needs to load other modules and the loading process needs to be\ncustomized, load them using either require() or dynamic import() after the hooks\nare registered. Do not use static import statements to load modules that need to be\ncustomized in the same module that registers the hooks, because static import statements\nare evaluated before any code in the importer module is run, including the call to\nregisterHooks(), regardless of where the static import statements appear in the importer\nmodule.
import { registerHooks } from 'node:module';\n\nregisterHooks({ /* implementation of synchronous hooks */ });\n\n// If loaded using static import, the hooks would not be applied when loading\n// my-app.mjs, because statically imported modules are all executed before its\n// importer regardless of where the static import appears.\n// import './my-app.mjs';\n\n// my-app.mjs must be loaded dynamically to ensure the hooks are applied.\nawait import('./my-app.mjs');\n\nconst { registerHooks } = require('node:module');\n\nregisterHooks({ /* implementation of synchronous hooks */ });\n\nimport('./my-app.mjs');\n// Or, if my-app.mjs does not have top-level await or it's a CommonJS module,\n// require() can also be used:\n// require('./my-app.mjs');\n",
"displayName": "Registering hooks before application code runs programmatically"
},
{
"textRaw": "Registering hooks before application code runs with a `data:` URL",
"name": "registering_hooks_before_application_code_runs_with_a_`data:`_url",
"type": "module",
"desc": "Alternatively, inline JavaScript code can be embedded in data: URLs to register\nthe hooks before the application code runs. For example,
node --import 'data:text/javascript,import {registerHooks} from \"node:module\"; registerHooks(/* hooks code */);' ./my-app.js\n",
"displayName": "Registering hooks before application code runs with a `data:` URL"
}
],
"displayName": "Registration of synchronous customization hooks"
},
{
"textRaw": "Convention of hooks and chaining",
"name": "convention_of_hooks_and_chaining",
"type": "module",
"desc": "Hooks are part of a chain, even if that chain consists of only one\ncustom (user-provided) hook and the default hook, which is always present.
\nHook functions nest: each one must always return a plain object, and chaining happens\nas a result of each function calling next<hookName>(), which is a reference to\nthe subsequent loader's hook (in LIFO order).
It's possible to call registerHooks() more than once:
// entrypoint.mjs\nimport { registerHooks } from 'node:module';\n\nconst hook1 = { /* implementation of hooks */ };\nconst hook2 = { /* implementation of hooks */ };\n// hook2 runs before hook1.\nregisterHooks(hook1);\nregisterHooks(hook2);\n\n// entrypoint.cjs\nconst { registerHooks } = require('node:module');\n\nconst hook1 = { /* implementation of hooks */ };\nconst hook2 = { /* implementation of hooks */ };\n// hook2 runs before hook1.\nregisterHooks(hook1);\nregisterHooks(hook2);\n\nIn this example, the registered hooks will form chains. These chains run\nlast-in, first-out (LIFO). If both hook1 and hook2 define a resolve\nhook, they will be called like so (note the right-to-left,\nstarting with hook2.resolve, then hook1.resolve, then the Node.js default):
Node.js default resolve ← hook1.resolve ← hook2.resolve
The same applies to all the other hooks.
\nA hook that returns a value lacking a required property triggers an exception. A\nhook that returns without calling next<hookName>() and without returning\nshortCircuit: true also triggers an exception. These errors are to help\nprevent unintentional breaks in the chain. Return shortCircuit: true from a\nhook to signal that the chain is intentionally ending at your hook.
If a hook should be applied when loading other hook modules, the other hook\nmodules should be loaded after the hook is registered.
", "displayName": "Convention of hooks and chaining" }, { "textRaw": "Hook functions accepted by `module.registerHooks()`", "name": "hook_functions_accepted_by_`module.registerhooks()`", "type": "module", "meta": { "added": [ "v23.5.0", "v22.15.0" ], "changes": [] }, "desc": "The module.registerHooks() method accepts the following synchronous hook functions.
function resolve(specifier, context, nextResolve) {\n // Take an `import` or `require` specifier and resolve it to a URL.\n}\n\nfunction load(url, context, nextLoad) {\n // Take a resolved URL and return the source code to be evaluated.\n}\n\nSynchronous hooks are run in the same thread and the same realm where the modules\nare loaded, the code in the hook function can pass values to the modules being referenced\ndirectly via global variables or other shared states.
\nUnlike the asynchronous hooks, the synchronous hooks are not inherited into child worker\nthreads by default, though if the hooks are registered using a file preloaded by\n--import or --require, child worker threads can inherit the preloaded scripts\nvia process.execArgv inheritance. See the documentation of Worker for details.
specifier <string>context <Object>\nconditions <string[]> Export conditions of the relevant package.jsonimportAttributes <Object> An object whose key-value pairs represent the\nattributes for the module to importparentURL <string> | <undefined> The module importing this one, or undefined\nif this is the Node.js entry pointnextResolve <Function> The subsequent resolve hook in the chain, or the\nNode.js default resolve hook after the last user-supplied resolve hook\nspecifier <string>context <Object> | <undefined> When omitted, the defaults are provided. When provided, defaults\nare merged in with preference to the provided properties.<Object>\nformat <string> | <null> | <undefined> A hint to the load hook (it might be ignored). It can be a\nmodule format (such as 'commonjs' or 'module') or an arbitrary value like 'css' or\n'yaml'.importAttributes <Object> | <undefined> The import attributes to use when\ncaching the module (optional; if excluded the input will be used)shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve hooks. Default: falseurl <string> The absolute URL to which this input resolvesThe resolve hook chain is responsible for telling Node.js where to find and\nhow to cache a given import statement or expression, or require call. It can\noptionally return a format (such as 'module') as a hint to the load hook. If\na format is specified, the load hook is ultimately responsible for providing\nthe final format value (and it is free to ignore the hint provided by\nresolve); if resolve provides a format, a custom load hook is required\neven if only to pass the value to the Node.js default load hook.
Import type attributes are part of the cache key for saving loaded modules into\nthe internal module cache. The resolve hook is responsible for returning an\nimportAttributes object if the module should be cached with different\nattributes than were present in the source code.
The conditions property in context is an array of conditions that will be used\nto match package exports conditions for this resolution\nrequest. They can be used for looking up conditional mappings elsewhere or to\nmodify the list when calling the default resolution logic.
The current package exports conditions are always in\nthe context.conditions array passed into the hook. To guarantee default\nNode.js module specifier resolution behavior when calling defaultResolve, the\ncontext.conditions array passed to it must include all elements of the\ncontext.conditions array originally passed into the resolve hook.
import { registerHooks } from 'node:module';\n\nfunction resolve(specifier, context, nextResolve) {\n // When calling `defaultResolve`, the arguments can be modified. For example,\n // to change the specifier or to add applicable export conditions.\n if (specifier.includes('foo')) {\n specifier = specifier.replace('foo', 'bar');\n return nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // The hook can also skip default resolution and provide a custom URL.\n if (specifier === 'special-module') {\n return {\n url: 'file:///path/to/special-module.mjs',\n format: 'module',\n shortCircuit: true, // This is mandatory if nextResolve() is not called.\n };\n }\n\n // If no customization is needed, defer to the next hook in the chain which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier);\n}\n\nregisterHooks({ resolve });\n",
"displayName": "Synchronous `resolve(specifier, context, nextResolve)`"
},
{
"textRaw": "Synchronous `load(url, context, nextLoad)`",
"name": "synchronous_`load(url,_context,_nextload)`",
"type": "module",
"meta": {
"changes": [
{
"version": [
"v23.5.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/55698",
"description": "Add support for synchronous and in-thread version."
}
]
},
"desc": "url <string> The URL returned by the resolve chaincontext <Object>\nconditions <string[]> Export conditions of the relevant package.jsonformat <string> | <null> | <undefined> The format optionally supplied by the resolve hook chain. This can be any string value as an input; input values do not need to\nconform to the list of acceptable return values described below.importAttributes <Object>nextLoad <Function> The subsequent load hook in the chain, or the\nNode.js default load hook after the last user-supplied load hook\nurl <string>context <Object> | <undefined> When omitted, defaults are provided. When provided, defaults are\nmerged in with preference to the provided properties. In the default nextLoad, if\nthe module pointed to by url does not have explicit module type information,\ncontext.format is mandatory.\n\n<Object>\nformat <string> One of the acceptable module formats listed below.shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of load hooks. Default: falsesource <string> | <ArrayBuffer> | <TypedArray> The source for Node.js to evaluateThe load hook provides a way to define a custom method for retrieving the\nsource code of a resolved URL. This would allow a loader to potentially avoid\nreading files from disk. It could also be used to map an unrecognized format to\na supported one, for example yaml to module.
import { registerHooks } from 'node:module';\nimport { Buffer } from 'node:buffer';\n\nfunction load(url, context, nextLoad) {\n // The hook can skip default loading and provide a custom source code.\n if (url === 'special-module') {\n return {\n source: 'export const special = 42;',\n format: 'module',\n shortCircuit: true, // This is mandatory if nextLoad() is not called.\n };\n }\n\n // It's possible to modify the source code loaded by the next - possibly default - step,\n // for example, replacing 'foo' with 'bar' in the source code of the module.\n const result = nextLoad(url, context);\n const source = typeof result.source === 'string' ?\n result.source : Buffer.from(result.source).toString('utf8');\n return {\n source: source.replace(/foo/g, 'bar'),\n ...result,\n };\n}\n\nregisterHooks({ resolve });\n\nIn a more advanced scenario, this can also be used to transform an unsupported\nsource to a supported one (see Examples below).
", "modules": [ { "textRaw": "Accepted final formats returned by `load`", "name": "accepted_final_formats_returned_by_`load`", "type": "module", "desc": "The final value of format must be one of the following:
format | Description | Acceptable types for source returned by load |
|---|---|---|
'addon' | Load a Node.js addon | <null> |
'builtin' | Load a Node.js builtin module | <null> |
'commonjs-typescript' | Load a Node.js CommonJS module with TypeScript syntax | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'commonjs' | Load a Node.js CommonJS module | <string> | <ArrayBuffer> | <TypedArray> | <null> | <undefined> |
'json' | Load a JSON file | <string> | <ArrayBuffer> | <TypedArray> |
'module-typescript' | Load an ES module with TypeScript syntax | <string> | <ArrayBuffer> | <TypedArray> |
'module' | Load an ES module | <string> | <ArrayBuffer> | <TypedArray> |
'wasm' | Load a WebAssembly module | <ArrayBuffer> | <TypedArray> |
The value of source is ignored for format 'builtin' because currently it is\nnot possible to replace the value of a Node.js builtin (core) module.
\n\nThese types all correspond to classes defined in ECMAScript.
\n
<ArrayBuffer> object is a <SharedArrayBuffer>.<TypedArray> object is a <Uint8Array>.If the source value of a text-based format (i.e., 'json', 'module')\nis not a string, it is converted to a string using util.TextDecoder.
The asynchronous customization hooks have many caveats and it is uncertain if their\nissues can be resolved. Users are encouraged to use the synchronous customization hooks\nvia module.registerHooks() instead to avoid these caveats.
require() calls in the module graph.\nrequire functions created using module.createRequire() are not\naffected.load hook does not override the source for CommonJS modules\nthat go through it, the child modules loaded by those CommonJS modules via built-in\nrequire() would not be affected by the asynchronous hooks either.resolve hook and\nasynchronous load hook for details.require() calls inside CommonJS modules are customized by asynchronous hooks,\nNode.js may need to load the source code of the CommonJS module multiple times to maintain\ncompatibility with existing CommonJS monkey-patching. If the module code changes between\nloads, this may lead to unexpected behaviors.\nrequire() calls in that CommonJS module.Asynchronous customization hooks are registered using module.register() which takes\na path or URL to another module that exports the asynchronous hook functions.
Similar to registerHooks(), register() can be called in a module preloaded by --import or\n--require, or called directly within the entry point.
// Use module.register() to register asynchronous hooks in a dedicated thread.\nimport { register } from 'node:module';\nregister('./hooks.mjs', import.meta.url);\n\n// If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM\n// dependencies are evaluated before the module that imports them,\n// it's loaded _before_ the hooks are registered above and won't be affected.\n// To ensure the hooks are applied, dynamic import() must be used to load ESM\n// after the hooks are registered.\nimport('./my-app.mjs');\n\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n// Use module.register() to register asynchronous hooks in a dedicated thread.\nregister('./hooks.mjs', pathToFileURL(__filename));\n\nimport('./my-app.mjs');\n\nIn hooks.mjs:
// hooks.mjs\nexport async function resolve(specifier, context, nextResolve) {\n /* implementation */\n}\nexport async function load(url, context, nextLoad) {\n /* implementation */\n}\n\nUnlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file\nthat calls register():
// register-hooks.js\nimport { register, createRequire } from 'node:module';\nregister('./hooks.mjs', import.meta.url);\n\n// Asynchronous hooks does not affect modules loaded via custom require()\n// functions created by module.createRequire().\nconst userRequire = createRequire(__filename);\nuserRequire('./my-app-2.cjs'); // Hooks won't affect this\n\n// register-hooks.js\nconst { register, createRequire } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nregister('./hooks.mjs', pathToFileURL(__filename));\n\n// Asynchronous hooks does not affect modules loaded via built-in require()\n// in the module calling `register()`\nrequire('./my-app-2.cjs'); // Hooks won't affect this\n// .. or custom require() functions created by module.createRequire().\nconst userRequire = createRequire(__filename);\nuserRequire('./my-app-3.cjs'); // Hooks won't affect this\n\nAsynchronous hooks can also be registered using a data: URL with the --import flag:
node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(\"my-instrumentation\", pathToFileURL(\"./\"));' ./my-app.js\n",
"displayName": "Registration of asynchronous customization hooks"
},
{
"textRaw": "Chaining of asynchronous customization hooks",
"name": "chaining_of_asynchronous_customization_hooks",
"type": "module",
"desc": "Chaining of register() work similarly to registerHooks(). If synchronous and asynchronous\nhooks are mixed, the synchronous hooks are always run first before the asynchronous\nhooks start running, that is, in the last synchronous hook being run, its next\nhook includes invocation of the asynchronous hooks.
// entrypoint.mjs\nimport { register } from 'node:module';\n\nregister('./foo.mjs', import.meta.url);\nregister('./bar.mjs', import.meta.url);\nawait import('./my-app.mjs');\n\n// entrypoint.cjs\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\n\nconst parentURL = pathToFileURL(__filename);\nregister('./foo.mjs', parentURL);\nregister('./bar.mjs', parentURL);\nimport('./my-app.mjs');\n\nIf foo.mjs and bar.mjs define a resolve hook, they will be called like so\n(note the right-to-left, starting with ./bar.mjs, then ./foo.mjs, then the Node.js default):
Node.js default ← ./foo.mjs ← ./bar.mjs
When using the asynchronous hooks, the registered hooks also affect subsequent\nregister calls, which takes care of loading hook modules. In the example above,\nbar.mjs will be resolved and loaded via the hooks registered by foo.mjs\n(because foo's hooks will have already been added to the chain). This allows\nfor things like writing hooks in non-JavaScript languages, so long as\nearlier registered hooks transpile into JavaScript.
The register() method cannot be called from the thread running the hook module that\nexports the asynchronous hooks or its dependencies.
Asynchronous hooks run on a dedicated thread, separate from the main\nthread that runs application code. This means mutating global variables won't\naffect the other thread(s), and message channels must be used to communicate\nbetween the threads.
\nThe register method can be used to pass data to an initialize hook. The\ndata passed to the hook may include transferable objects like ports.
import { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\n\n// This example demonstrates how a message channel can be used to\n// communicate with the hooks, by sending `port2` to the hooks.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n console.log(msg);\n});\nport1.unref();\n\nregister('./my-hooks.mjs', {\n parentURL: import.meta.url,\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst { MessageChannel } = require('node:worker_threads');\n\n// This example showcases how a message channel can be used to\n// communicate with the hooks, by sending `port2` to the hooks.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n console.log(msg);\n});\nport1.unref();\n\nregister('./my-hooks.mjs', {\n parentURL: pathToFileURL(__filename),\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n",
"displayName": "Communication with asynchronous module customization hooks"
},
{
"textRaw": "Asynchronous hooks accepted by `module.register()`",
"name": "asynchronous_hooks_accepted_by_`module.register()`",
"type": "module",
"meta": {
"added": [
"v8.8.0"
],
"changes": [
{
"version": [
"v20.6.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/48842",
"description": "Added `initialize` hook to replace `globalPreload`."
},
{
"version": [
"v18.6.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/42623",
"description": "Add support for chaining loaders."
},
{
"version": "v16.12.0",
"pr-url": "https://github.com/nodejs/node/pull/37468",
"description": "Removed `getFormat`, `getSource`, `transformSource`, and `globalPreload`; added `load` hook and `getGlobalPreload` hook."
}
]
},
"desc": "The register method can be used to register a module that exports a set of\nhooks. The hooks are functions that are called by Node.js to customize the\nmodule resolution and loading process. The exported functions must have specific\nnames and signatures, and they must be exported as named exports.
export async function initialize({ number, port }) {\n // Receives data from `register`.\n}\n\nexport async function resolve(specifier, context, nextResolve) {\n // Take an `import` or `require` specifier and resolve it to a URL.\n}\n\nexport async function load(url, context, nextLoad) {\n // Take a resolved URL and return the source code to be evaluated.\n}\n\nAsynchronous hooks are run in a separate thread, isolated from the main thread where\napplication code runs. That means it is a different realm. The hooks thread\nmay be terminated by the main thread at any time, so do not depend on\nasynchronous operations (like console.log) to complete. They are inherited into\nchild workers by default.
specifier <string>context <Object>\nconditions <string[]> Export conditions of the relevant package.jsonimportAttributes <Object> An object whose key-value pairs represent the\nattributes for the module to importparentURL <string> | <undefined> The module importing this one, or undefined\nif this is the Node.js entry pointnextResolve <Function> The subsequent resolve hook in the chain, or the\nNode.js default resolve hook after the last user-supplied resolve hook\nspecifier <string>context <Object> | <undefined> When omitted, the defaults are provided. When provided, defaults\nare merged in with preference to the provided properties.<Object> | <Promise> The asynchronous version takes either an object containing the\nfollowing properties, or a Promise that will resolve to such an object.\nformat <string> | <null> | <undefined> A hint to the load hook (it might be ignored). It can be a\nmodule format (such as 'commonjs' or 'module') or an arbitrary value like 'css' or\n'yaml'.importAttributes <Object> | <undefined> The import attributes to use when\ncaching the module (optional; if excluded the input will be used)shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of resolve hooks. Default: falseurl <string> The absolute URL to which this input resolvesThe asynchronous version works similarly to the synchronous version, only that the\nnextResolve function returns a Promise, and the resolve hook itself can return a Promise.
\n\nWarning In the case of the asynchronous version, despite support for returning\npromises and async functions, calls to
\nresolvemay still block the main thread which\ncan impact performance.
\n\nWarning The
\nresolvehook invoked forrequire()calls inside CommonJS modules\ncustomized by asynchronous hooks does not receive the original specifier passed to\nrequire(). Instead, it receives a URL already fully resolved using the default\nCommonJS resolution.
\n\nWarning In the CommonJS modules that are customized by the asynchronous customization hooks,\n
\nrequire.resolve()andrequire()will use\"import\"export condition instead of\n\"require\", which may cause unexpected behaviors when loading dual packages.
export async function resolve(specifier, context, nextResolve) {\n // When calling `defaultResolve`, the arguments can be modified. For example,\n // to change the specifier or add conditions.\n if (specifier.includes('foo')) {\n specifier = specifier.replace('foo', 'bar');\n return nextResolve(specifier, {\n ...context,\n conditions: [...context.conditions, 'another-condition'],\n });\n }\n\n // The hook can also skips default resolution and provide a custom URL.\n if (specifier === 'special-module') {\n return {\n url: 'file:///path/to/special-module.mjs',\n format: 'module',\n shortCircuit: true, // This is mandatory if not calling nextResolve().\n };\n }\n\n // If no customization is needed, defer to the next hook in the chain which would be the\n // Node.js default resolve if this is the last user-specified loader.\n return nextResolve(specifier);\n}\n",
"displayName": "Asynchronous `resolve(specifier, context, nextResolve)`"
},
{
"textRaw": "Asynchronous `load(url, context, nextLoad)`",
"name": "asynchronous_`load(url,_context,_nextload)`",
"type": "module",
"meta": {
"changes": [
{
"version": "v22.6.0",
"pr-url": "https://github.com/nodejs/node/pull/56350",
"description": "Add support for `source` with format `commonjs-typescript` and `module-typescript`."
},
{
"version": "v20.6.0",
"pr-url": "https://github.com/nodejs/node/pull/47999",
"description": "Add support for `source` with format `commonjs`."
},
{
"version": [
"v18.6.0",
"v16.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/42623",
"description": "Add support for chaining load hooks. Each hook must either call `nextLoad()` or include a `shortCircuit` property set to `true` in its return."
}
]
},
"desc": "url <string> The URL returned by the resolve chaincontext <Object>\nconditions <string[]> Export conditions of the relevant package.jsonformat <string> | <null> | <undefined> The format optionally supplied by the resolve hook chain. This can be any string value as an input; input values do not need to\nconform to the list of acceptable return values described below.importAttributes <Object>nextLoad <Function> The subsequent load hook in the chain, or the\nNode.js default load hook after the last user-supplied load hook\nurl <string>context <Object> | <undefined> When omitted, defaults are provided. When provided, defaults are\nmerged in with preference to the provided properties. In the default nextLoad, if\nthe module pointed to by url does not have explicit module type information,\ncontext.format is mandatory.\n\n<Promise> The asynchronous version takes either an object containing the\nfollowing properties, or a Promise that will resolve to such an object.\nformat <string>shortCircuit <undefined> | <boolean> A signal that this hook intends to\nterminate the chain of load hooks. Default: falsesource <string> | <ArrayBuffer> | <TypedArray> The source for Node.js to evaluate\n\nWarning: The asynchronous
\nloadhook and namespaced exports from CommonJS\nmodules are incompatible. Attempting to use them together will result in an empty\nobject from the import. This may be addressed in the future. This does not apply\nto the synchronousloadhook, in which case exports can be used as usual.
The asynchronous version works similarly to the synchronous version, though\nwhen using the asynchronous load hook, omitting vs providing a source for\n'commonjs' has very different effects:
source is provided, all require calls from this module will be\nprocessed by the ESM loader with registered resolve and load hooks; all\nrequire.resolve calls from this module will be processed by the ESM loader\nwith registered resolve hooks; only a subset of the CommonJS API will be\navailable (e.g. no require.extensions, no require.cache, no\nrequire.resolve.paths) and monkey-patching on the CommonJS module loader\nwill not apply.source is undefined or null, it will be handled by the CommonJS module\nloader and require/require.resolve calls will not go through the\nregistered hooks. This behavior for nullish source is temporary — in the\nfuture, nullish source will not be supported.These caveats do not apply to the synchronous load hook, in which case\nthe complete set of CommonJS APIs available to the customized CommonJS\nmodules, and require/require.resolve always go through the registered\nhooks.
The Node.js internal asynchronous load implementation, which is the value of next for the\nlast hook in the load chain, returns null for source when format is\n'commonjs' for backward compatibility. Here is an example hook that would\nopt-in to using the non-default behavior:
import { readFile } from 'node:fs/promises';\n\n// Asynchronous version accepted by module.register(). This fix is not needed\n// for the synchronous version accepted by module.registerHooks().\nexport async function load(url, context, nextLoad) {\n const result = await nextLoad(url, context);\n if (result.format === 'commonjs') {\n result.source ??= await readFile(new URL(result.responseURL ?? url));\n }\n return result;\n}\n\nThis doesn't apply to the synchronous load hook either, in which case the\nsource returned contains source code loaded by the next hook, regardless\nof module format.
The initialize hook is only accepted by register. registerHooks() does\nnot support nor need it since initialization done for synchronous hooks can be run\ndirectly before the call to registerHooks().
The initialize hook provides a way to define a custom function that runs in\nthe hooks thread when the hooks module is initialized. Initialization happens\nwhen the hooks module is registered via register.
This hook can receive data from a register invocation, including\nports and other transferable objects. The return value of initialize can be a\n<Promise>, in which case it will be awaited before the main application thread\nexecution resumes.
Module customization code:
\n// path-to-my-hooks.js\n\nexport async function initialize({ number, port }) {\n port.postMessage(`increment: ${number + 1}`);\n}\n\nCaller code:
\nimport assert from 'node:assert';\nimport { register } from 'node:module';\nimport { MessageChannel } from 'node:worker_threads';\n\n// This example showcases how a message channel can be used to communicate\n// between the main (application) thread and the hooks running on the hooks\n// thread, by sending `port2` to the `initialize` hook.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n assert.strictEqual(msg, 'increment: 2');\n});\nport1.unref();\n\nregister('./path-to-my-hooks.js', {\n parentURL: import.meta.url,\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n\nconst assert = require('node:assert');\nconst { register } = require('node:module');\nconst { pathToFileURL } = require('node:url');\nconst { MessageChannel } = require('node:worker_threads');\n\n// This example showcases how a message channel can be used to communicate\n// between the main (application) thread and the hooks running on the hooks\n// thread, by sending `port2` to the `initialize` hook.\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (msg) => {\n assert.strictEqual(msg, 'increment: 2');\n});\nport1.unref();\n\nregister('./path-to-my-hooks.js', {\n parentURL: pathToFileURL(__filename),\n data: { number: 1, port: port2 },\n transferList: [port2],\n});\n"
}
],
"displayName": "Asynchronous customization hooks"
},
{
"textRaw": "Examples",
"name": "examples",
"type": "misc",
"desc": "The various module customization hooks can be used together to accomplish\nwide-ranging customizations of the Node.js code loading and evaluation\nbehaviors.
", "modules": [ { "textRaw": "Import from HTTPS", "name": "import_from_https", "type": "module", "desc": "The hook below registers hooks to enable rudimentary support for such\nspecifiers. While this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using these hooks:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.
\n// https-hooks.mjs\nimport { get } from 'node:https';\n\nexport function load(url, context, nextLoad) {\n // For JavaScript to be loaded over the network, we need to fetch and\n // return it.\n if (url.startsWith('https://')) {\n return new Promise((resolve, reject) => {\n get(url, (res) => {\n let data = '';\n res.setEncoding('utf8');\n res.on('data', (chunk) => data += chunk);\n res.on('end', () => resolve({\n // This example assumes all network-provided JavaScript is ES module\n // code.\n format: 'module',\n shortCircuit: true,\n source: data,\n }));\n }).on('error', (err) => reject(err));\n });\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url);\n}\n\n// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n\nWith the preceding hooks module, running\nnode --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./https-hooks.mjs\"));' ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.
Sources that are in formats Node.js doesn't understand can be converted into\nJavaScript using the load hook.
This is less performant than transpiling source files before running Node.js;\ntranspiler hooks should only be used for development and testing purposes.
", "modules": [ { "textRaw": "Asynchronous version", "name": "asynchronous_version", "type": "module", "desc": "// coffeescript-hooks.mjs\nimport { readFile } from 'node:fs/promises';\nimport { findPackageJSON } from 'node:module';\nimport coffeescript from 'coffeescript';\n\nconst extensionsRegex = /\\.(coffee|litcoffee|coffee\\.md)$/;\n\nexport async function load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\n // CoffeeScript files can be either CommonJS or ES modules. Use a custom format\n // to tell Node.js not to detect its module type.\n const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' });\n // This hook converts CoffeeScript source code into JavaScript source code\n // for all imported CoffeeScript files.\n const transformedSource = coffeescript.compile(rawSource.toString(), url);\n\n // To determine how Node.js would interpret the transpilation result,\n // search up the file system for the nearest parent package.json file\n // and read its \"type\" field.\n return {\n format: await getPackageType(url),\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url, context);\n}\n\nasync function getPackageType(url) {\n // `url` is only a file path during the first iteration when passed the\n // resolved url from the load() hook\n // an actual file path from load() will contain a file extension as it's\n // required by the spec\n // this simple truthy check for whether `url` contains a file extension will\n // work for most projects but does not cover some edge-cases (such as\n // extensionless files or a url ending in a trailing space)\n const pJson = findPackageJSON(url);\n\n return readFile(pJson, 'utf8')\n .then(JSON.parse)\n .then((json) => json?.type)\n .catch(() => undefined);\n}\n",
"displayName": "Asynchronous version"
},
{
"textRaw": "Synchronous version",
"name": "synchronous_version",
"type": "module",
"desc": "// coffeescript-sync-hooks.mjs\nimport { readFileSync } from 'node:fs';\nimport { registerHooks, findPackageJSON } from 'node:module';\nimport coffeescript from 'coffeescript';\n\nconst extensionsRegex = /\\.(coffee|litcoffee|coffee\\.md)$/;\n\nfunction load(url, context, nextLoad) {\n if (extensionsRegex.test(url)) {\n const { source: rawSource } = nextLoad(url, { ...context, format: 'coffee' });\n const transformedSource = coffeescript.compile(rawSource.toString(), url);\n\n return {\n format: getPackageType(url),\n shortCircuit: true,\n source: transformedSource,\n };\n }\n\n return nextLoad(url, context);\n}\n\nfunction getPackageType(url) {\n const pJson = findPackageJSON(url);\n if (!pJson) {\n return undefined;\n }\n try {\n const file = readFileSync(pJson, 'utf-8');\n return JSON.parse(file)?.type;\n } catch {\n return undefined;\n }\n}\n\nregisterHooks({ load });\n",
"displayName": "Synchronous version"
}
],
"displayName": "Transpilation"
},
{
"textRaw": "Running hooks",
"name": "running_hooks",
"type": "module",
"desc": "# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'node:process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n\n# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n\nFor the sake of running the example, add a package.json file containing the\nmodule type of the CoffeeScript files.
{\n \"type\": \"module\"\n}\n\nThis is only for running the example. In real world loaders, getPackageType() must be\nable to return an format known to Node.js even in the absence of an explicit type in a\npackage.json, or otherwise the nextLoad call would throw ERR_UNKNOWN_FILE_EXTENSION\n(if undefined) or ERR_UNKNOWN_MODULE_FORMAT (if it's not a known format listed in\nthe load hook documentation).
With the preceding hooks modules, running\nnode --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./coffeescript-hooks.mjs\"));' ./main.coffee\nor node --import ./coffeescript-sync-hooks.mjs ./main.coffee\ncauses main.coffee to be turned into JavaScript after its source code is\nloaded from disk but before Node.js executes it; and so on for any .coffee,\n.litcoffee or .coffee.md files referenced via import statements of any\nloaded file.
The previous two examples defined load hooks. This is an example of a\nresolve hook. This hooks module reads an import-map.json file that defines\nwhich specifiers to override to other URLs (this is a very simplistic\nimplementation of a small subset of the \"import maps\" specification).
// import-map-hooks.js\nimport fs from 'node:fs/promises';\n\nconst { imports } = JSON.parse(await fs.readFile('import-map.json'));\n\nexport async function resolve(specifier, context, nextResolve) {\n if (Object.hasOwn(imports, specifier)) {\n return nextResolve(imports[specifier], context);\n }\n\n return nextResolve(specifier, context);\n}\n",
"displayName": "Asynchronous version"
},
{
"textRaw": "Synchronous version",
"name": "synchronous_version",
"type": "module",
"desc": "// import-map-sync-hooks.js\nimport fs from 'node:fs/promises';\nimport module from 'node:module';\n\nconst { imports } = JSON.parse(fs.readFileSync('import-map.json', 'utf-8'));\n\nfunction resolve(specifier, context, nextResolve) {\n if (Object.hasOwn(imports, specifier)) {\n return nextResolve(imports[specifier], context);\n }\n\n return nextResolve(specifier, context);\n}\n\nmodule.registerHooks({ resolve });\n",
"displayName": "Synchronous version"
},
{
"textRaw": "Using the hooks",
"name": "using_the_hooks",
"type": "module",
"desc": "With these files:
\n// main.js\nimport 'a-module';\n\n// import-map.json\n{\n \"imports\": {\n \"a-module\": \"./some-module.js\"\n }\n}\n\n// some-module.js\nconsole.log('some module!');\n\nRunning node --import 'data:text/javascript,import { register } from \"node:module\"; import { pathToFileURL } from \"node:url\"; register(pathToFileURL(\"./import-map-hooks.js\"));' main.js\nor node --import ./import-map-sync-hooks.js main.js\nshould print some module!.
There are two ways to enable runtime TypeScript support in Node.js:
\nFor full support of all of TypeScript's syntax and features, including\nusing any version of TypeScript, use a third-party package.
\nFor lightweight support, you can use the built-in support for\ntype stripping.
\nTo use TypeScript with full support for all TypeScript features, including\ntsconfig.json, you can use a third-party package. These instructions use\ntsx as an example but there are many other similar libraries available.
Install the package as a development dependency using whatever package\nmanager you're using for your project. For example, with npm:
npm install --save-dev tsx\n\nThen you can run your TypeScript code via:
\nnpx tsx your-file.ts\n\nOr alternatively, you can run with node via:
node --import=tsx your-file.ts\n\nBy default Node.js will execute TypeScript files that contains only\nerasable TypeScript syntax.\nNode.js will replace TypeScript syntax with whitespace,\nand no type checking is performed.\nTo enable the transformation of non erasable TypeScript syntax, which requires JavaScript code generation,\nsuch as enum declarations, parameter properties use the flag --experimental-transform-types.\nTo disable this feature, use the flag --no-strip-types.
Node.js ignores tsconfig.json files and therefore\nfeatures that depend on settings within tsconfig.json,\nsuch as paths or converting newer JavaScript syntax to older standards, are\nintentionally unsupported. To get full TypeScript support, see Full TypeScript support.
The type stripping feature is designed to be lightweight.\nBy intentionally not supporting syntaxes that require JavaScript code\ngeneration, and by replacing inline types with whitespace, Node.js can run\nTypeScript code without the need for source maps.
\nType stripping is compatible with most versions of TypeScript\nbut we recommend version 5.8 or newer with the following tsconfig.json settings:
{\n \"compilerOptions\": {\n \"noEmit\": true, // Optional - see note below\n \"target\": \"esnext\",\n \"module\": \"nodenext\",\n \"rewriteRelativeImportExtensions\": true,\n \"erasableSyntaxOnly\": true,\n \"verbatimModuleSyntax\": true\n }\n}\n\nUse the noEmit option if you intend to only execute *.ts files, for example\na build script. You won't need this flag if you intend to distribute *.js\nfiles.
Node.js supports both CommonJS and ES Modules syntax in TypeScript\nfiles. Node.js will not convert from one module system to another; if you want\nyour code to run as an ES module, you must use import and export syntax, and\nif you want your code to run as CommonJS you must use require and\nmodule.exports.
.ts files will have their module system determined the same way as .js\nfiles. To use import and export syntax, add \"type\": \"module\" to the\nnearest parent package.json..mts files will always be run as ES modules, similar to .mjs files..cts files will always be run as CommonJS modules, similar to .cjs files..tsx files are unsupported.As in JavaScript files, file extensions are mandatory in import statements\nand import() expressions: import './file.ts', not import './file'. Because\nof backward compatibility, file extensions are also mandatory in require()\ncalls: require('./file.ts'), not require('./file'), similar to how the\n.cjs extension is mandatory in require calls in CommonJS files.
The tsconfig.json option allowImportingTsExtensions will allow the\nTypeScript compiler tsc to type-check files with import specifiers that\ninclude the .ts extension.
Since Node.js is only removing inline types, any TypeScript features that\ninvolve replacing TypeScript syntax with new JavaScript syntax will error,\nunless the flag --experimental-transform-types is passed.
The most prominent features that require transformation are:
\nEnum declarationsnamespace with runtime codenamespaces that do not contain runtime code are supported.\nThis example will work correctly:
// This namespace is exporting a type\nnamespace TypeOnly {\n export type A = string;\n}\n\nThis will result in ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX error:
// This namespace is exporting a value\nnamespace A {\n export let x = 1\n}\n\nSince Decorators are currently a TC39 Stage 3 proposal,\nthey are not transformed and will result in a parser error.\nNode.js does not provide polyfills and thus will not support decorators until\nthey are supported natively in JavaScript.
\nIn addition, Node.js does not read tsconfig.json files and does not support\nfeatures that depend on settings within tsconfig.json, such as paths or\nconverting newer JavaScript syntax into older standards.
Due to the nature of type stripping, the type keyword is necessary to\ncorrectly strip type imports. Without the type keyword, Node.js will treat the\nimport as a value import, which will result in a runtime error. The tsconfig\noption verbatimModuleSyntax can be used to match this behavior.
This example will work correctly:
\nimport type { Type1, Type2 } from './module.ts';\nimport { fn, type FnParams } from './fn.ts';\n\nThis will result in a runtime error:
\nimport { Type1, Type2 } from './module.ts';\nimport { fn, FnParams } from './fn.ts';\n",
"displayName": "Importing types without `type` keyword"
},
{
"textRaw": "Non-file forms of input",
"name": "non-file_forms_of_input",
"type": "module",
"desc": "Type stripping can be enabled for --eval and STDIN. The module system\nwill be determined by --input-type, as it is for JavaScript.
TypeScript syntax is unsupported in the REPL, --check, and\ninspect.
Since inline types are replaced by whitespace, source maps are unnecessary for\ncorrect line numbers in stack traces; and Node.js does not generate them.\nWhen --experimental-transform-types is enabled, source-maps\nare enabled by default.
To discourage package authors from publishing packages written in TypeScript,\nNode.js refuses to handle TypeScript files inside folders under a node_modules\npath.
tsconfig \"paths\" won't be transformed and therefore produce an error. The closest\nfeature available is subpath imports with the limitation that they need to start\nwith #.
The node:net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).
It can be accessed using:
\nimport net from 'node:net';\n\nconst net = require('node:net');\n",
"modules": [
{
"textRaw": "IPC support",
"name": "ipc_support",
"type": "module",
"meta": {
"changes": [
{
"version": "v20.8.0",
"pr-url": "https://github.com/nodejs/node/pull/49667",
"description": "Support binding to abstract Unix domain socket path like `\\0abstract`. We can bind '\\0' for Node.js `< v20.4.0`."
}
]
},
"desc": "The node:net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.
net.connect(), net.createConnection(), server.listen(), and\nsocket.connect() take a path parameter to identify IPC endpoints.
On Unix, the local domain is also known as the Unix domain. The path is a\nfile system pathname. It will throw an error when the length of pathname is\ngreater than the length of sizeof(sockaddr_un.sun_path). Typical values are\n107 bytes on Linux and 103 bytes on macOS. If a Node.js API abstraction creates\nthe Unix domain socket, it will unlink the Unix domain socket as well. For\nexample, net.createServer() may create a Unix domain socket and\nserver.close() will unlink it. But if a user creates the Unix domain\nsocket outside of these abstractions, the user will need to remove it. The same\napplies when a Node.js API creates a Unix domain socket but the program then\ncrashes. In short, a Unix domain socket will be visible in the file system and\nwill persist until unlinked. On Linux, You can use Unix abstract socket by adding\n\\0 to the beginning of the path, such as \\0abstract. The path to the Unix\nabstract socket is not visible in the file system and it will disappear automatically\nwhen all open references to the socket are closed.
On Windows, the local domain is implemented using a named pipe. The path must\nrefer to an entry in \\\\?\\pipe\\ or \\\\.\\pipe\\. Any characters are permitted,\nbut the latter may do some processing of pipe names, such as resolving ..\nsequences. Despite how it might look, the pipe namespace is flat. Pipes will\nnot persist. They are removed when the last reference to them is closed.\nUnlike Unix domain sockets, Windows will close and remove the pipe when the\nowning process exits.
JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:
\nnet.createServer().listen(\n path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n",
"displayName": "Identifying paths for IPC connections"
}
],
"displayName": "IPC support"
}
],
"classes": [
{
"textRaw": "Class: `net.BlockList`",
"name": "net.BlockList",
"type": "class",
"meta": {
"added": [
"v15.0.0",
"v14.18.0"
],
"changes": []
},
"desc": "The BlockList object can be used with some network APIs to specify rules for\ndisabling inbound or outbound access to specific IP addresses, IP ranges, or\nIP subnets.
Adds a rule to block the given IP address.
" }, { "textRaw": "`blockList.addRange(start, end[, type])`", "name": "addRange", "type": "method", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`start` {string|net.SocketAddress} The starting IPv4 or IPv6 address in the range.", "name": "start", "type": "string|net.SocketAddress", "desc": "The starting IPv4 or IPv6 address in the range." }, { "textRaw": "`end` {string|net.SocketAddress} The ending IPv4 or IPv6 address in the range.", "name": "end", "type": "string|net.SocketAddress", "desc": "The ending IPv4 or IPv6 address in the range." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ] } ], "desc": "Adds a rule to block a range of IP addresses from start (inclusive) to\nend (inclusive).
Adds a rule to block a range of IP addresses specified as a subnet mask.
" }, { "textRaw": "`blockList.check(address[, type])`", "name": "check", "type": "method", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`address` {string|net.SocketAddress} The IP address to check", "name": "address", "type": "string|net.SocketAddress", "desc": "The IP address to check" }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`.", "optional": true } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "Returns true if the given IP address matches any of the rules added to the\nBlockList.
const blockList = new net.BlockList();\nblockList.addAddress('123.123.123.123');\nblockList.addRange('10.0.0.1', '10.0.0.10');\nblockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');\n\nconsole.log(blockList.check('123.123.123.123')); // Prints: true\nconsole.log(blockList.check('10.0.0.3')); // Prints: true\nconsole.log(blockList.check('222.111.111.222')); // Prints: false\n\n// IPv6 notation for IPv4 addresses works:\nconsole.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true\nconsole.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true\n"
},
{
"textRaw": "`BlockList.isBlockList(value)`",
"name": "isBlockList",
"type": "method",
"meta": {
"added": [
"v23.4.0",
"v22.13.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} Any JS value",
"name": "value",
"type": "any",
"desc": "Any JS value"
}
],
"return": {
"textRaw": "Returns `true` if the `value` is a `net.BlockList`.",
"name": "return",
"desc": "`true` if the `value` is a `net.BlockList`."
}
}
]
},
{
"textRaw": "`blockList.fromJSON(value)`",
"name": "fromJSON",
"type": "method",
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"name": "value"
}
]
}
],
"desc": " \nconst blockList = new net.BlockList();\nconst data = [\n 'Subnet: IPv4 192.168.1.0/24',\n 'Address: IPv4 10.0.0.5',\n 'Range: IPv4 192.168.2.1-192.168.2.10',\n 'Range: IPv4 10.0.0.1-10.0.0.10',\n];\nblockList.fromJSON(data);\nblockList.fromJSON(JSON.stringify(data));\n\nvalue Blocklist.rulesThe list of rules added to the blocklist.
" } ] }, { "textRaw": "Class: `net.SocketAddress`", "name": "net.SocketAddress", "type": "class", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "textRaw": "`new net.SocketAddress([options])`", "name": "net.SocketAddress", "type": "ctor", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`address` {string} The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`.", "name": "address", "type": "string", "desc": "The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`." }, { "textRaw": "`family` {string} One of either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.", "name": "family", "type": "string", "desc": "One of either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`." }, { "textRaw": "`flowlabel` {number} An IPv6 flow-label used only if `family` is `'ipv6'`.", "name": "flowlabel", "type": "number", "desc": "An IPv6 flow-label used only if `family` is `'ipv6'`." }, { "textRaw": "`port` {number} An IP port.", "name": "port", "type": "number", "desc": "An IP port." } ], "optional": true } ] } ], "properties": [ { "textRaw": "Type: {string}", "name": "address", "type": "string", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } }, { "textRaw": "Type: {string} Either `'ipv4'` or `'ipv6'`.", "name": "family", "type": "string", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "Type: {number}", "name": "flowlabel", "type": "number", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } }, { "textRaw": "Type: {number}", "name": "port", "type": "number", "meta": { "added": [ "v15.14.0", "v14.18.0" ], "changes": [] } } ], "methods": [ { "textRaw": "`SocketAddress.parse(input)`", "name": "parse", "type": "method", "meta": { "added": [ "v23.4.0", "v22.13.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`input` {string} An input string containing an IP address and optional port, e.g. `123.1.2.3:1234` or `[1::1]:1234`.", "name": "input", "type": "string", "desc": "An input string containing an IP address and optional port, e.g. `123.1.2.3:1234` or `[1::1]:1234`." } ], "return": { "textRaw": "Returns: {net.SocketAddress} Returns a `SocketAddress` if parsing was successful. Otherwise returns `undefined`.", "name": "return", "type": "net.SocketAddress", "desc": "Returns a `SocketAddress` if parsing was successful. Otherwise returns `undefined`." } } ] } ] }, { "textRaw": "Class: `net.Server`", "name": "net.Server", "type": "class", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "<EventEmitter>This class is used to create a TCP or IPC server.
", "signatures": [ { "textRaw": "`new net.Server([options][, connectionListener])`", "name": "net.Server", "type": "ctor", "params": [ { "textRaw": "`options` {Object} See `net.createServer([options][, connectionListener])`.", "name": "options", "type": "Object", "desc": "See `net.createServer([options][, connectionListener])`.", "optional": true }, { "textRaw": "`connectionListener` {Function} Automatically set as a listener for the `'connection'` event.", "name": "connectionListener", "type": "Function", "desc": "Automatically set as a listener for the `'connection'` event.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "desc": "net.Server is an EventEmitter with the following events:
Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.
" }, { "textRaw": "Event: `'connection'`", "name": "connection", "type": "event", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "Type: {net.Socket} The connection object", "name": "type", "type": "net.Socket", "desc": "The connection object" } ], "desc": "Emitted when a new connection is made. socket is an instance of\nnet.Socket.
Emitted when an error occurs. Unlike net.Socket, the 'close'\nevent will not be emitted directly following this event unless\nserver.close() is manually called. See the example in discussion of\nserver.listen().
Emitted when the server has been bound after calling server.listen().
When the number of connections reaches the threshold of server.maxConnections,\nthe server will drop new connections and emit 'drop' event instead. If it is a\nTCP server, the argument is as follows, otherwise the argument is undefined.
Returns the bound address, the address family name, and port of the server\nas reported by the operating system if listening on an IP socket\n(useful to find which port was assigned when getting an OS-assigned address):\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.
For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.
\nconst server = net.createServer((socket) => {\n socket.end('goodbye\\n');\n}).on('error', (err) => {\n // Handle errors here.\n throw err;\n});\n\n// Grab an arbitrary unused port.\nserver.listen(() => {\n console.log('opened server on', server.address());\n});\n\nserver.address() returns null before the 'listening' event has been\nemitted or after calling server.close().
Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally closed\nwhen all connections are ended and the server emits a 'close' event.\nThe optional callback will be called once the 'close' event occurs. Unlike\nthat event, it will be called with an Error as its only argument if the server\nwas not open when it was closed.
Calls server.close() and returns a promise that fulfills when the\nserver has closed.
Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.
\nCallback should take two arguments err and count.
Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.
Possible signatures:
\nserver.listen(handle[, backlog][, callback])server.listen(options[, callback])server.listen(path[, backlog][, callback])\nfor IPC serversserver.listen([port[, host[, backlog]]][, callback])\nfor TCP serversThis function is asynchronous. When the server starts listening, the\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.
All listen() methods can take a backlog parameter to specify the maximum\nlength of the queue of pending connections. The actual length will be determined\nby the OS through sysctl settings such as tcp_max_syn_backlog and somaxconn\non Linux. The default value of this parameter is 511 (not 512).
All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).
The server.listen() method can be called again if and only if there was an\nerror during the first server.listen() call or server.close() has been\ncalled. Otherwise, an ERR_SERVER_ALREADY_LISTEN error will be thrown.
One of the most common errors raised when listening is EADDRINUSE.\nThis happens when another server is already listening on the requested\nport/path/handle. One way to handle this would be to retry\nafter a certain amount of time:
server.on('error', (e) => {\n if (e.code === 'EADDRINUSE') {\n console.error('Address in use, retrying...');\n setTimeout(() => {\n server.close();\n server.listen(PORT, HOST);\n }, 1000);\n }\n});\n",
"methods": [
{
"textRaw": "`server.listen(handle[, backlog][, callback])`",
"name": "listen",
"type": "method",
"meta": {
"added": [
"v0.5.10"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`handle` {Object}",
"name": "handle",
"type": "Object"
},
{
"textRaw": "`backlog` {number} Common parameter of `server.listen()` functions",
"name": "backlog",
"type": "number",
"desc": "Common parameter of `server.listen()` functions",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
}
}
],
"desc": "Start a server listening for connections on a given handle that has\nalready been bound to a port, a Unix domain socket, or a Windows named pipe.
The handle object can be either a server, a socket (anything with an\nunderlying _handle member), or an object with an fd member that is a\nvalid file descriptor.
Listening on a file descriptor is not supported on Windows.
" }, { "textRaw": "`server.listen(options[, callback])`", "name": "listen", "type": "method", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": [ "v23.1.0", "v22.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/55408", "description": "The `reusePort` option is supported." }, { "version": "v15.6.0", "pr-url": "https://github.com/nodejs/node/pull/36623", "description": "AbortSignal support was added." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/23798", "description": "The `ipv6Only` option is supported." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Required. Supports the following properties:", "name": "options", "type": "Object", "desc": "Required. Supports the following properties:", "options": [ { "textRaw": "`backlog` {number} Common parameter of `server.listen()` functions.", "name": "backlog", "type": "number", "desc": "Common parameter of `server.listen()` functions." }, { "textRaw": "`exclusive` {boolean} **Default:** `false`", "name": "exclusive", "type": "boolean", "default": "`false`" }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "textRaw": "`ipv6Only` {boolean} For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound. **Default:** `false`.", "name": "ipv6Only", "type": "boolean", "default": "`false`", "desc": "For TCP servers, setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to host `::` won't make `0.0.0.0` be bound." }, { "textRaw": "`reusePort` {boolean} For TCP servers, setting `reusePort` to `true` allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. On unsupported platforms, this option raises an error. **Default:** `false`.", "name": "reusePort", "type": "boolean", "default": "`false`", "desc": "For TCP servers, setting `reusePort` to `true` allows multiple sockets on the same host to bind to the same port. Incoming connections are distributed by the operating system to listening sockets. This option is available only on some platforms, such as Linux 3.9+, DragonFlyBSD 3.6+, FreeBSD 12.0+, Solaris 11.4, and AIX 7.2.5+. On unsupported platforms, this option raises an error." }, { "textRaw": "`path` {string} Will be ignored if `port` is specified. See Identifying paths for IPC connections.", "name": "path", "type": "string", "desc": "Will be ignored if `port` is specified. See Identifying paths for IPC connections." }, { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`readableAll` {boolean} For IPC servers makes the pipe readable for all users. **Default:** `false`.", "name": "readableAll", "type": "boolean", "default": "`false`", "desc": "For IPC servers makes the pipe readable for all users." }, { "textRaw": "`signal` {AbortSignal} An AbortSignal that may be used to close a listening server.", "name": "signal", "type": "AbortSignal", "desc": "An AbortSignal that may be used to close a listening server." }, { "textRaw": "`writableAll` {boolean} For IPC servers makes the pipe writable for all users. **Default:** `false`.", "name": "writableAll", "type": "boolean", "default": "`false`", "desc": "For IPC servers makes the pipe writable for all users." } ] }, { "textRaw": "`callback` {Function} functions.", "name": "callback", "type": "Function", "desc": "functions.", "optional": true } ], "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" } } ], "desc": "If port is specified, it behaves the same as\nserver.listen([port[, host[, backlog]]][, callback]).\nOtherwise, if path is specified, it behaves the same as\nserver.listen(path[, backlog][, callback]).\nIf none of them is specified, an error will be thrown.
If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.
server.listen({\n host: 'localhost',\n port: 80,\n exclusive: true,\n});\n\nWhen exclusive is true and the underlying handle is shared, it is\npossible that several workers query a handle with different backlogs.\nIn this case, the first backlog passed to the master process will be used.
Starting an IPC server as root may cause the server path to be inaccessible for\nunprivileged users. Using readableAll and writableAll will make the server\naccessible for all users.
If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the server:
const controller = new AbortController();\nserver.listen({\n host: 'localhost',\n port: 80,\n signal: controller.signal,\n});\n// Later, when you want to close the server.\ncontroller.abort();\n"
},
{
"textRaw": "`server.listen(path[, backlog][, callback])`",
"name": "listen",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} Path the server should listen to. See Identifying paths for IPC connections.",
"name": "path",
"type": "string",
"desc": "Path the server should listen to. See Identifying paths for IPC connections."
},
{
"textRaw": "`backlog` {number} Common parameter of `server.listen()` functions.",
"name": "backlog",
"type": "number",
"desc": "Common parameter of `server.listen()` functions.",
"optional": true
},
{
"textRaw": "`callback` {Function}.",
"name": "callback",
"type": "Function",
"desc": ".",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Server}",
"name": "return",
"type": "net.Server"
}
}
],
"desc": "Start an IPC server listening for connections on the given path.
Start a TCP server listening for connections on the given port and host.
If port is omitted or is 0, the operating system will assign an arbitrary\nunused port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.
If host is omitted, the server will accept connections on the\nunspecified IPv6 address (::) when IPv6 is available, or the\nunspecified IPv4 address (0.0.0.0) otherwise.
In most operating systems, listening to the unspecified IPv6 address (::)\nmay cause the net.Server to also listen on the unspecified IPv4 address\n(0.0.0.0).
Opposite of unref(), calling ref() on a previously unrefed server will\nnot let the program exit if it's the only server left (the default behavior).\nIf the server is refed calling ref() again will have no effect.
Calling unref() on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefed calling\nunref() again will have no effect.
When the number of connections reaches the server.maxConnections threshold:
If the process is not running in cluster mode, Node.js will close the connection.
\nIf the process is running in cluster mode, Node.js will, by default, route the connection to another worker process. To close the connection instead, set server.dropMaxConnection to true.
It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().
Set this property to true to begin closing connections once the number of connections reaches the server.maxConnections threshold. This setting is only effective in cluster mode.
<stream.Duplex>This class is an abstraction of a TCP socket or a streaming IPC endpoint\n(uses named pipes on Windows, and Unix domain sockets otherwise). It is also\nan EventEmitter.
A net.Socket can be created by the user and used directly to interact with\na server. For example, it is returned by net.createConnection(),\nso 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\nis received. For example, it is passed to the listeners of a\n'connection' event emitted on a net.Server, so the user can use\nit to interact with the client.
Creates a new socket object.
\nThe newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.
Emitted once the socket is fully closed. The argument hadError is a boolean\nwhich says if the socket was closed due to a transmission error.
Emitted when a socket connection is successfully established.\nSee net.createConnection().
Emitted when a new connection attempt is started. This may be emitted multiple times\nif the family autoselection algorithm is enabled in socket.connect(options).
Emitted when a connection attempt failed. This may be emitted multiple times\nif the family autoselection algorithm is enabled in socket.connect(options).
Emitted when a connection attempt timed out. This is only emitted (and may be\nemitted multiple times) if the family autoselection algorithm is enabled\nin socket.connect(options).
Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().
The data will be lost if there is no listener when a Socket\nemits a 'data' event.
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
\nSee also: the return values of socket.write().
Emitted when the other end of the socket signals the end of transmission, thus\nending the readable side of the socket.
\nBy default (allowHalfOpen is false) the socket will send an end of\ntransmission packet back and destroy its file descriptor once it has written out\nits pending write queue. However, if allowHalfOpen is set to true, the\nsocket will not automatically end() its writable side,\nallowing the user to write arbitrary amounts of data. The user must call\nend() explicitly to close the connection (i.e. sending a\nFIN packet back).
Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.
Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.
" }, { "textRaw": "Event: `'ready'`", "name": "ready", "type": "event", "meta": { "added": [ "v9.11.0" ], "changes": [] }, "params": [], "desc": "Emitted when a socket is ready to be used.
\nTriggered immediately after 'connect'.
Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.
\nSee also: socket.setTimeout().
Returns the bound address, the address family name and port of the\nsocket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
Initiate a connection on a given socket.
\nPossible signatures:
\nsocket.connect(options[, connectListener])socket.connect(path[, connectListener])\nfor IPC connections.socket.connect(port[, host][, connectListener])\nfor TCP connections.<net.Socket> The socket itself.This function is asynchronous. When the connection is established, the\n'connect' event will be emitted. If there is a problem connecting,\ninstead of a 'connect' event, an 'error' event will be emitted with\nthe error passed to the 'error' listener.\nThe last parameter connectListener, if supplied, will be added as a listener\nfor the 'connect' event once.
This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.
Initiate a connection on a given socket. Normally this method is not needed,\nthe socket should be created and opened with net.createConnection(). Use\nthis only when implementing a custom Socket.
For TCP connections, available options are:
autoSelectFamily <boolean>: If set to true, it enables a family\nautodetection algorithm that loosely implements section 5 of RFC 8305. The\nall option passed to lookup is set to true and the sockets attempts to\nconnect to all obtained IPv6 and IPv4 addresses, in sequence, until a\nconnection is established. The first returned AAAA address is tried first,\nthen the first returned A address, then the second returned AAAA address and\nso on. Each connection attempt (but the last one) is given the amount of time\nspecified by the autoSelectFamilyAttemptTimeout option before timing out and\ntrying the next address. Ignored if the family option is not 0 or if\nlocalAddress is set. Connection errors are not emitted if at least one\nconnection succeeds. If all connections attempts fails, a single\nAggregateError with all failed attempts is emitted. Default:\nnet.getDefaultAutoSelectFamily().autoSelectFamilyAttemptTimeout <number>: The amount of time in milliseconds\nto wait for a connection attempt to finish before trying the next address when\nusing the autoSelectFamily option. If set to a positive integer less than\n10, then the value 10 will be used instead. Default:\nnet.getDefaultAutoSelectFamilyAttemptTimeout().family <number>: Version of IP stack. Must be 4, 6, or 0. The value\n0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0.hints <number> Optional dns.lookup() hints.host <string> Host the socket should connect to. Default: 'localhost'.localAddress <string> Local address the socket should connect from.localPort <number> Local port the socket should connect from.lookup <Function> Custom lookup function. Default: dns.lookup().port <number> Required. Port the socket should connect to.For IPC connections, available options are:
path <string> Required. Path the client should connect to.\nSee Identifying paths for IPC connections. If provided, the TCP-specific\noptions above are ignored.Initiate an IPC connection on the given socket.
\nAlias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.
Initiate a TCP connection on the given socket.
\nAlias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.
Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.
\nSee writable.destroy() for further details.
Destroys the socket after all data is written. If the 'finish' event was\nalready emitted the socket is destroyed immediately. If the socket is still\nwritable it implicitly calls socket.end().
Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.
\nSee writable.end() for further details.
Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.
Opposite of unref(), calling ref() on a previously unrefed socket will\nnot let the program exit if it's the only socket left (the default behavior).\nIf the socket is refed calling ref again will have no effect.
Close the TCP connection by sending an RST packet and destroy the stream.\nIf this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.\nOtherwise, it will call socket.destroy with an ERR_SOCKET_CLOSED Error.\nIf this is not a TCP socket (for example, a pipe), calling this method will immediately throw an ERR_INVALID_HANDLE_TYPE Error.
Resumes reading after a call to socket.pause().
Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.
Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.
\nSet initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting.
Enabling the keep-alive functionality will set the following socket options:
\nSO_KEEPALIVE=1TCP_KEEPIDLE=initialDelayTCP_KEEPCNT=10TCP_KEEPINTVL=1Enable/disable the use of Nagle's algorithm.
\nWhen a TCP connection is created, it will have Nagle's algorithm enabled.
\nNagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.
\nPassing true for noDelay or not passing an argument will disable Nagle's\nalgorithm for the socket. Passing false for noDelay will enable Nagle's\nalgorithm.
Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually call\nsocket.end() or socket.destroy() to end the connection.
socket.setTimeout(3000);\nsocket.on('timeout', () => {\n console.log('socket timeout');\n socket.end();\n});\n\nIf timeout is 0, then the existing idle timeout is disabled.
The optional callback parameter will be added as a one-time listener for the\n'timeout' event.
Returns the current Type of Service (TOS) field for IPv4 packets or Traffic\nClass for IPv6 packets for this socket.
\nsetTypeOfService() may be called before the socket is connected; the value\nwill be cached and applied when the socket establishes a connection.\ngetTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored,\nand behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers\nshould verify platform-specific semantics.
" }, { "textRaw": "`socket.setTypeOfService(tos)`", "name": "setTypeOfService", "type": "method", "meta": { "added": [ "v25.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`tos` {integer} The TOS value to set (0-255).", "name": "tos", "type": "integer", "desc": "The TOS value to set (0-255)." } ], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6\nPackets sent from this socket. This can be used to prioritize network traffic.
\nsetTypeOfService() may be called before the socket is connected; the value\nwill be cached and applied when the socket establishes a connection.\ngetTypeOfService() will return the currently set value even before connection.
On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored,\nand behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers\nshould verify platform-specific semantics.
" }, { "textRaw": "`socket.unref()`", "name": "unref", "type": "method", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." } } ], "desc": "Calling unref() on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefed calling\nunref() again will have no effect.
Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.
\nReturns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.
The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.
See Writable stream write() method for more\ninformation.
This property is only present if the family autoselection algorithm is enabled in\nsocket.connect(options) and it is an array of the addresses that have been attempted.
Each address is a string in the form of $IP:$PORT. If the connection was successful,\nthen the last address is the one that the socket is currently connected to.
This property shows the number of characters buffered for writing. The buffer\nmay contain strings whose length after encoding is not yet known. So this number\nis only an approximation of the number of bytes in the buffer.
\nnet.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket. The network connection\nsimply might be too slow. Node.js will internally queue up the data written to a\nsocket and send it out over the wire when it is possible.
The consequence of this internal buffering is that memory may grow.\nUsers who experience large or growing bufferSize should attempt to\n\"throttle\" the data flows in their program with\nsocket.pause() and socket.resume().
The amount of received bytes.
" }, { "textRaw": "Type: {integer}", "name": "bytesWritten", "type": "integer", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "The amount of bytes sent.
" }, { "textRaw": "Type: {boolean}", "name": "connecting", "type": "boolean", "meta": { "added": [ "v6.1.0" ], "changes": [] }, "desc": "If true,\nsocket.connect(options[, connectListener]) was\ncalled and has not yet finished. It will stay true until the socket becomes\nconnected, then it is set to false and the 'connect' event is emitted. Note\nthat the\nsocket.connect(options[, connectListener])\ncallback is a listener for the 'connect' event.
See writable.destroyed for further details.
The string representation of the local IP address the remote client is\nconnecting on. For example, in a server listening on '0.0.0.0', if a client\nconnects on '192.168.1.1', the value of socket.localAddress would be\n'192.168.1.1'.
The numeric representation of the local port. For example, 80 or 21.
The string representation of the local IP family. 'IPv4' or 'IPv6'.
This is true if the socket is not connected yet, either because .connect()\nhas not yet been called or because it is still in the process of connecting\n(see socket.connecting).
The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
The string representation of the remote IP family. 'IPv4' or 'IPv6'. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
The numeric representation of the remote port. For example, 80 or 21. Value may be undefined if\nthe socket is destroyed (for example, if the client disconnected).
The socket timeout in milliseconds as set by socket.setTimeout().\nIt is undefined if a timeout has not been set.
This property represents the state of the connection as a string.
\nsocket.readyState is opening.open.readOnly.writeOnly.Aliases to\nnet.createConnection().
Possible signatures:
\nnet.connect(options[, connectListener])net.connect(path[, connectListener]) for IPC\nconnections.net.connect(port[, host][, connectListener])\nfor TCP connections.Alias to\nnet.createConnection(options[, connectListener]).
Alias to\nnet.createConnection(path[, connectListener]).
Alias to\nnet.createConnection(port[, host][, connectListener]).
A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.
When the connection is established, a 'connect' event will be emitted\non the returned socket. The last parameter connectListener, if supplied,\nwill be added as a listener for the 'connect' event once.
Possible signatures:
\nnet.createConnection(options[, connectListener])net.createConnection(path[, connectListener])\nfor IPC connections.net.createConnection(port[, host][, connectListener])\nfor TCP connections.The net.connect() function is an alias to this function.
For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).
Additional options:
\ntimeout <number> If set, will be used to call socket.setTimeout(timeout) after the socket is created, but before\nit starts the connection.Following is an example of a client of the echo server described\nin the net.createServer() section:
import net from 'node:net';\nconst client = net.createConnection({ port: 8124 }, () => {\n // 'connect' listener.\n console.log('connected to server!');\n client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n console.log(data.toString());\n client.end();\n});\nclient.on('end', () => {\n console.log('disconnected from server');\n});\n\nconst net = require('node:net');\nconst client = net.createConnection({ port: 8124 }, () => {\n // 'connect' listener.\n console.log('connected to server!');\n client.write('world!\\r\\n');\n});\nclient.on('data', (data) => {\n console.log(data.toString());\n client.end();\n});\nclient.on('end', () => {\n console.log('disconnected from server');\n});\n\nTo connect on the socket /tmp/echo.sock:
const client = net.createConnection({ path: '/tmp/echo.sock' });\n\nFollowing is an example of a client using the port and onread\noption. In this case, the onread option will be only used to call\nnew net.Socket([options]) and the port option will be used to\ncall socket.connect(options[, connectListener]).
import net from 'node:net';\nimport { Buffer } from 'node:buffer';\nnet.createConnection({\n port: 8124,\n onread: {\n // Reuses a 4KiB Buffer for every read from the socket.\n buffer: Buffer.alloc(4 * 1024),\n callback: function(nread, buf) {\n // Received data is available in `buf` from 0 to `nread`.\n console.log(buf.toString('utf8', 0, nread));\n },\n },\n});\n\nconst net = require('node:net');\nnet.createConnection({\n port: 8124,\n onread: {\n // Reuses a 4KiB Buffer for every read from the socket.\n buffer: Buffer.alloc(4 * 1024),\n callback: function(nread, buf) {\n // Received data is available in `buf` from 0 to `nread`.\n console.log(buf.toString('utf8', 0, nread));\n },\n },\n});\n"
},
{
"textRaw": "`net.createConnection(path[, connectListener])`",
"name": "createConnection",
"type": "method",
"meta": {
"added": [
"v0.1.90"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} Path the socket should connect to. Will be passed to `socket.connect(path[, connectListener])`. See Identifying paths for IPC connections.",
"name": "path",
"type": "string",
"desc": "Path the socket should connect to. Will be passed to `socket.connect(path[, connectListener])`. See Identifying paths for IPC connections."
},
{
"textRaw": "`connectListener` {Function} Common parameter of the `net.createConnection()` functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to `socket.connect(path[, connectListener])`.",
"name": "connectListener",
"type": "Function",
"desc": "Common parameter of the `net.createConnection()` functions, an \"once\" listener for the `'connect'` event on the initiating socket. Will be passed to `socket.connect(path[, connectListener])`.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {net.Socket} The newly created socket used to start the connection.",
"name": "return",
"type": "net.Socket",
"desc": "The newly created socket used to start the connection."
}
}
],
"desc": "Initiates an IPC connection.
\nThis function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(path[, connectListener]),\nthen returns the net.Socket that starts the connection.
Initiates a TCP connection.
\nThis function creates a new net.Socket with all options set to default,\nimmediately initiates connection with\nsocket.connect(port[, host][, connectListener]),\nthen returns the net.Socket that starts the connection.
Creates a new TCP or IPC server.
\nIf allowHalfOpen is set to true, when the other end of the socket\nsignals the end of transmission, the server will only send back the end of\ntransmission when socket.end() is explicitly called. For example, in the\ncontext of TCP, when a FIN packed is received, a FIN packed is sent\nback only when socket.end() is explicitly called. Until then the\nconnection is half-closed (non-readable but still writable). See 'end'\nevent and RFC 1122 (section 4.2.2.13) for more information.
If pauseOnConnect is set to true, then the socket associated with each\nincoming connection will be paused, and no data will be read from its handle.\nThis allows connections to be passed between processes without any data being\nread by the original process. To begin reading data from a paused socket, call\nsocket.resume().
The server can be a TCP server or an IPC server, depending on what it\nlisten() to.
Here is an example of a TCP echo server which listens for connections\non port 8124:
\nimport net from 'node:net';\nconst server = net.createServer((c) => {\n // 'connection' listener.\n console.log('client connected');\n c.on('end', () => {\n console.log('client disconnected');\n });\n c.write('hello\\r\\n');\n c.pipe(c);\n});\nserver.on('error', (err) => {\n throw err;\n});\nserver.listen(8124, () => {\n console.log('server bound');\n});\n\nconst net = require('node:net');\nconst server = net.createServer((c) => {\n // 'connection' listener.\n console.log('client connected');\n c.on('end', () => {\n console.log('client disconnected');\n });\n c.write('hello\\r\\n');\n c.pipe(c);\n});\nserver.on('error', (err) => {\n throw err;\n});\nserver.listen(8124, () => {\n console.log('server bound');\n});\n\nTest this by using telnet:
telnet localhost 8124\n\nTo listen on the socket /tmp/echo.sock:
server.listen('/tmp/echo.sock', () => {\n console.log('server bound');\n});\n\nUse nc to connect to a Unix domain socket server:
nc -U /tmp/echo.sock\n"
},
{
"textRaw": "`net.getDefaultAutoSelectFamily()`",
"name": "getDefaultAutoSelectFamily",
"type": "method",
"meta": {
"added": [
"v19.4.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {boolean} The current default value of the `autoSelectFamily` option.",
"name": "return",
"type": "boolean",
"desc": "The current default value of the `autoSelectFamily` option."
}
}
],
"desc": "Gets the current default value of the autoSelectFamily option of socket.connect(options).\nThe initial default value is true, unless the command line option\n--no-network-family-autoselection is provided.
Sets the default value of the autoSelectFamily option of socket.connect(options).
Gets the current default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).\nThe initial default value is 500 or the value specified via the command line\noption --network-family-autoselection-attempt-timeout.
Sets the default value of the autoSelectFamilyAttemptTimeout option of socket.connect(options).
Returns 6 if input is an IPv6 address. Returns 4 if input is an IPv4\naddress in dot-decimal notation with no leading zeroes. Otherwise, returns\n0.
net.isIP('::1'); // returns 6\nnet.isIP('127.0.0.1'); // returns 4\nnet.isIP('127.000.000.001'); // returns 0\nnet.isIP('127.0.0.1/24'); // returns 0\nnet.isIP('fhqwhgads'); // returns 0\n"
},
{
"textRaw": "`net.isIPv4(input)`",
"name": "isIPv4",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if input is an IPv4 address in dot-decimal notation with no\nleading zeroes. Otherwise, returns false.
net.isIPv4('127.0.0.1'); // returns true\nnet.isIPv4('127.000.000.001'); // returns false\nnet.isIPv4('127.0.0.1/24'); // returns false\nnet.isIPv4('fhqwhgads'); // returns false\n"
},
{
"textRaw": "`net.isIPv6(input)`",
"name": "isIPv6",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`input` {string}",
"name": "input",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if input is an IPv6 address. Otherwise, returns false.
net.isIPv6('::1'); // returns true\nnet.isIPv6('fhqwhgads'); // returns false\n"
}
],
"displayName": "Net",
"source": "doc/api/net.md"
},
{
"textRaw": "OS",
"name": "os",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:os module provides operating system-related utility methods and\nproperties. It can be accessed using:
import os from 'node:os';\n\nconst os = require('node:os');\n",
"properties": [
{
"textRaw": "Type: {string}",
"name": "EOL",
"type": "string",
"meta": {
"added": [
"v0.7.8"
],
"changes": []
},
"desc": "The operating system-specific end-of-line marker.
\n\\n on POSIX\\r\\n on WindowsContains commonly used operating system-specific constants for error codes,\nprocess signals, and so on. The specific constants defined are described in\nOS constants.
" }, { "textRaw": "Type: {string}", "name": "devNull", "type": "string", "meta": { "added": [ "v16.3.0", "v14.18.0" ], "changes": [] }, "desc": "The platform-specific file path of the null device.
\n\\\\.\\nul on Windows/dev/null on POSIXReturns an estimate of the default amount of parallelism a program should use.\nAlways returns a value greater than zero.
\nThis function is a small wrapper about libuv's uv_available_parallelism().
Returns the operating system CPU architecture for which the Node.js binary was\ncompiled. Possible values are 'arm', 'arm64', 'ia32', 'loong64',\n'mips', 'mipsel', 'ppc64', 'riscv64', 's390x', and 'x64'.
The return value is equivalent to process.arch.
Returns an array of objects containing information about each logical CPU core.\nThe array will be empty if no CPU information is available, such as if the\n/proc file system is unavailable.
The properties included on each object include:
\nmodel <string>speed <number> (in MHz)times <Object>\nuser <number> The number of milliseconds the CPU has spent in user mode.nice <number> The number of milliseconds the CPU has spent in nice mode.sys <number> The number of milliseconds the CPU has spent in sys mode.idle <number> The number of milliseconds the CPU has spent in idle mode.irq <number> The number of milliseconds the CPU has spent in irq mode.[\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 252020,\n nice: 0,\n sys: 30340,\n idle: 1070356870,\n irq: 0,\n },\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 306960,\n nice: 0,\n sys: 26980,\n idle: 1071569080,\n irq: 0,\n },\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 248450,\n nice: 0,\n sys: 21750,\n idle: 1070919370,\n irq: 0,\n },\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 256880,\n nice: 0,\n sys: 19430,\n idle: 1070905480,\n irq: 20,\n },\n },\n]\n\nnice values are POSIX-only. On Windows, the nice values of all processors\nare always 0.
os.cpus().length should not be used to calculate the amount of parallelism\navailable to an application. Use\nos.availableParallelism() for this purpose.
Returns a string identifying the endianness of the CPU for which the Node.js\nbinary was compiled.
\nPossible values are 'BE' for big endian and 'LE' for little endian.
Returns the amount of free system memory in bytes as an integer.
" }, { "textRaw": "`os.getPriority([pid])`", "name": "getPriority", "type": "method", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`pid` {integer} The process ID to retrieve scheduling priority for. **Default:** `0`.", "name": "pid", "type": "integer", "default": "`0`", "desc": "The process ID to retrieve scheduling priority for.", "optional": true } ], "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" } } ], "desc": "Returns the scheduling priority for the process specified by pid. If pid is\nnot provided or is 0, the priority of the current process is returned.
Returns the string path of the current user's home directory.
\nOn POSIX, it uses the $HOME environment variable if defined. Otherwise it\nuses the effective UID to look up the user's home directory.
On Windows, it uses the USERPROFILE environment variable if defined.\nOtherwise it uses the path to the profile directory of the current user.
Returns the host name of the operating system as a string.
" }, { "textRaw": "`os.loadavg()`", "name": "loadavg", "type": "method", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {number[]}", "name": "return", "type": "number[]" } } ], "desc": "Returns an array containing the 1, 5, and 15 minute load averages.
\nThe load average is a measure of system activity calculated by the operating\nsystem and expressed as a fractional number.
\nThe load average is a Unix-specific concept. On Windows, the return value is\nalways [0, 0, 0].
Returns the machine type as a string, such as arm, arm64, aarch64,\nmips, mips64, ppc64, ppc64le, s390x, i386, i686, x86_64.
On POSIX systems, the machine type is determined by calling\nuname(3). On Windows, RtlGetVersion() is used, and if it is not\navailable, GetVersionExW() will be used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.
Returns an object containing network interfaces that have been assigned a\nnetwork address.
\nEach key on the returned object identifies a network interface. The associated\nvalue is an array of objects that each describe an assigned network address.
\nThe properties available on the assigned network address object include:
\naddress <string> The assigned IPv4 or IPv6 addressnetmask <string> The IPv4 or IPv6 network maskfamily <string> Either IPv4 or IPv6mac <string> The MAC address of the network interfaceinternal <boolean> true if the network interface is a loopback or\nsimilar interface that is not remotely accessible; otherwise falsescopeid <number> The numeric IPv6 scope ID (only specified when family\nis IPv6)cidr <string> The assigned IPv4 or IPv6 address with the routing prefix\nin CIDR notation. If the netmask is invalid, this property is set\nto null.{\n lo: [\n {\n address: '127.0.0.1',\n netmask: '255.0.0.0',\n family: 'IPv4',\n mac: '00:00:00:00:00:00',\n internal: true,\n cidr: '127.0.0.1/8'\n },\n {\n address: '::1',\n netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',\n family: 'IPv6',\n mac: '00:00:00:00:00:00',\n scopeid: 0,\n internal: true,\n cidr: '::1/128'\n }\n ],\n eth0: [\n {\n address: '192.168.1.108',\n netmask: '255.255.255.0',\n family: 'IPv4',\n mac: '01:02:03:0a:0b:0c',\n internal: false,\n cidr: '192.168.1.108/24'\n },\n {\n address: 'fe80::a00:27ff:fe4e:66a1',\n netmask: 'ffff:ffff:ffff:ffff::',\n family: 'IPv6',\n mac: '01:02:03:0a:0b:0c',\n scopeid: 1,\n internal: false,\n cidr: 'fe80::a00:27ff:fe4e:66a1/64'\n }\n ]\n}\n"
},
{
"textRaw": "`os.platform()`",
"name": "platform",
"type": "method",
"meta": {
"added": [
"v0.5.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
}
}
],
"desc": "Returns a string identifying the operating system platform for which\nthe Node.js binary was compiled. The value is set at compile time.\nPossible values are 'aix', 'darwin', 'freebsd','linux',\n'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\noperating system. Android support is experimental.
Returns the operating system as a string.
\nOn POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, GetVersionExW() is used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.
Attempts to set the scheduling priority for the process specified by pid. If\npid 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\n(low priority). Due to differences between Unix priority levels and Windows\npriority classes, priority is mapped to one of six priority constants in\nos.constants.priority. When retrieving a process priority level, this range\nmapping may cause the return value to be slightly different on Windows. To avoid\nconfusion, set priority to one of the priority constants.
On Windows, setting priority to PRIORITY_HIGHEST requires elevated user\nprivileges. Otherwise the set priority will be silently reduced to\nPRIORITY_HIGH.
Returns the operating system's default directory for temporary files as a\nstring.
\nOn Windows, the result can be overridden by TEMP and TMP environment variables, and\nTEMP takes precedence over TMP. If neither is set, it defaults to %SystemRoot%\\temp\nor %windir%\\temp.
On non-Windows platforms, TMPDIR, TMP and TEMP environment variables will be checked\nto override the result of this method, in the described order. If none of them is set, it\ndefaults to /tmp.
Some operating system distributions would either configure TMPDIR (non-Windows) or\nTEMP and TMP (Windows) by default without additional configurations by the system\nadministrators. The result of os.tmpdir() typically reflects the system preference\nunless it's explicitly overridden by the users.
Returns the total amount of system memory in bytes as an integer.
" }, { "textRaw": "`os.type()`", "name": "type", "type": "method", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "Returns the operating system name as returned by uname(3). For example, it\nreturns 'Linux' on Linux, 'Darwin' on macOS, and 'Windows_NT' on Windows.
See https://en.wikipedia.org/wiki/Uname#Examples for additional information\nabout the output of running uname(3) on various operating systems.
Returns the system uptime in number of seconds.
" }, { "textRaw": "`os.userInfo([options])`", "name": "userInfo", "type": "method", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`encoding` {string} Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances." } ], "optional": true } ], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" } } ], "desc": "Returns information about the currently effective user. On POSIX platforms,\nthis is typically a subset of the password file. The returned object includes\nthe username, uid, gid, shell, and homedir. On Windows, the uid and\ngid fields are -1, and shell is null.
The value of homedir returned by os.userInfo() is provided by the operating\nsystem. This differs from the result of os.homedir(), which queries\nenvironment variables for the home directory before falling back to the\noperating system response.
Throws a SystemError if a user has no username or homedir.
Returns a string identifying the kernel version.
\nOn POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, RtlGetVersion() is used, and if it is not\navailable, GetVersionExW() will be used. See\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.
The following constants are exported by os.constants.
Not all constants will be available on every operating system.
", "modules": [ { "textRaw": "Signal constants", "name": "signal_constants", "type": "module", "meta": { "changes": [ { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/6093", "description": "Added support for `SIGINFO`." } ] }, "desc": "The following signal constants are exported by os.constants.signals.
| Constant | Description |
|---|---|
SIGHUP | Sent to indicate when a controlling terminal is closed or a parent\n process exits. |
SIGINT | Sent to indicate when a user wishes to interrupt a process\n (Ctrl+C). |
SIGQUIT | Sent to indicate when a user wishes to terminate a process and perform a\n core dump. |
SIGILL | Sent to a process to notify that it has attempted to perform an illegal,\n malformed, unknown, or privileged instruction. |
SIGTRAP | Sent to a process when an exception has occurred. |
SIGABRT | Sent to a process to request that it abort. |
SIGIOT | Synonym for SIGABRT |
SIGBUS | Sent to a process to notify that it has caused a bus error. |
SIGFPE | Sent to a process to notify that it has performed an illegal arithmetic\n operation. |
SIGKILL | Sent to a process to terminate it immediately. |
SIGUSR1 SIGUSR2 | Sent to a process to identify user-defined conditions. |
SIGSEGV | Sent to a process to notify of a segmentation fault. |
SIGPIPE | Sent to a process when it has attempted to write to a disconnected\n pipe. |
SIGALRM | Sent to a process when a system timer elapses. |
SIGTERM | Sent to a process to request termination. |
SIGCHLD | Sent to a process when a child process terminates. |
SIGSTKFLT | Sent to a process to indicate a stack fault on a coprocessor. |
SIGCONT | Sent to instruct the operating system to continue a paused process. |
SIGSTOP | Sent to instruct the operating system to halt a process. |
SIGTSTP | Sent to a process to request it to stop. |
SIGBREAK | Sent to indicate when a user wishes to interrupt a process. |
SIGTTIN | Sent to a process when it reads from the TTY while in the\n background. |
SIGTTOU | Sent to a process when it writes to the TTY while in the\n background. |
SIGURG | Sent to a process when a socket has urgent data to read. |
SIGXCPU | Sent to a process when it has exceeded its limit on CPU usage. |
SIGXFSZ | Sent to a process when it grows a file larger than the maximum\n allowed. |
SIGVTALRM | Sent to a process when a virtual timer has elapsed. |
SIGPROF | Sent to a process when a system timer has elapsed. |
SIGWINCH | Sent to a process when the controlling terminal has changed its\n size. |
SIGIO | Sent to a process when I/O is available. |
SIGPOLL | Synonym for SIGIO |
SIGLOST | Sent to a process when a file lock has been lost. |
SIGPWR | Sent to a process to notify of a power failure. |
SIGINFO | Synonym for SIGPWR |
SIGSYS | Sent to a process to notify of a bad argument. |
SIGUNUSED | Synonym for SIGSYS |
The following error constants are exported by os.constants.errno.
| Constant | Description |
|---|---|
E2BIG | Indicates that the list of arguments is longer than expected. |
EACCES | Indicates that the operation did not have sufficient permissions. |
EADDRINUSE | Indicates that the network address is already in use. |
EADDRNOTAVAIL | Indicates that the network address is currently unavailable for\n use. |
EAFNOSUPPORT | Indicates that the network address family is not supported. |
EAGAIN | Indicates that there is no data available and to try the\n operation again later. |
EALREADY | Indicates that the socket already has a pending connection in\n progress. |
EBADF | Indicates that a file descriptor is not valid. |
EBADMSG | Indicates an invalid data message. |
EBUSY | Indicates that a device or resource is busy. |
ECANCELED | Indicates that an operation was canceled. |
ECHILD | Indicates that there are no child processes. |
ECONNABORTED | Indicates that the network connection has been aborted. |
ECONNREFUSED | Indicates that the network connection has been refused. |
ECONNRESET | Indicates that the network connection has been reset. |
EDEADLK | Indicates that a resource deadlock has been avoided. |
EDESTADDRREQ | Indicates that a destination address is required. |
EDOM | Indicates that an argument is out of the domain of the function. |
EDQUOT | Indicates that the disk quota has been exceeded. |
EEXIST | Indicates that the file already exists. |
EFAULT | Indicates an invalid pointer address. |
EFBIG | Indicates that the file is too large. |
EHOSTUNREACH | Indicates that the host is unreachable. |
EIDRM | Indicates that the identifier has been removed. |
EILSEQ | Indicates an illegal byte sequence. |
EINPROGRESS | Indicates that an operation is already in progress. |
EINTR | Indicates that a function call was interrupted. |
EINVAL | Indicates that an invalid argument was provided. |
EIO | Indicates an otherwise unspecified I/O error. |
EISCONN | Indicates that the socket is connected. |
EISDIR | Indicates that the path is a directory. |
ELOOP | Indicates too many levels of symbolic links in a path. |
EMFILE | Indicates that there are too many open files. |
EMLINK | Indicates that there are too many hard links to a file. |
EMSGSIZE | Indicates that the provided message is too long. |
EMULTIHOP | Indicates that a multihop was attempted. |
ENAMETOOLONG | Indicates that the filename is too long. |
ENETDOWN | Indicates that the network is down. |
ENETRESET | Indicates that the connection has been aborted by the network. |
ENETUNREACH | Indicates that the network is unreachable. |
ENFILE | Indicates too many open files in the system. |
ENOBUFS | Indicates that no buffer space is available. |
ENODATA | Indicates that no message is available on the stream head read\n queue. |
ENODEV | Indicates that there is no such device. |
ENOENT | Indicates that there is no such file or directory. |
ENOEXEC | Indicates an exec format error. |
ENOLCK | Indicates that there are no locks available. |
ENOLINK | Indications that a link has been severed. |
ENOMEM | Indicates that there is not enough space. |
ENOMSG | Indicates that there is no message of the desired type. |
ENOPROTOOPT | Indicates that a given protocol is not available. |
ENOSPC | Indicates that there is no space available on the device. |
ENOSR | Indicates that there are no stream resources available. |
ENOSTR | Indicates that a given resource is not a stream. |
ENOSYS | Indicates that a function has not been implemented. |
ENOTCONN | Indicates that the socket is not connected. |
ENOTDIR | Indicates that the path is not a directory. |
ENOTEMPTY | Indicates that the directory is not empty. |
ENOTSOCK | Indicates that the given item is not a socket. |
ENOTSUP | Indicates that a given operation is not supported. |
ENOTTY | Indicates an inappropriate I/O control operation. |
ENXIO | Indicates no such device or address. |
EOPNOTSUPP | Indicates that an operation is not supported on the socket. Although\n ENOTSUP and EOPNOTSUPP have the same value\n on Linux, according to POSIX.1 these error values should be distinct.) |
EOVERFLOW | Indicates that a value is too large to be stored in a given data\n type. |
EPERM | Indicates that the operation is not permitted. |
EPIPE | Indicates a broken pipe. |
EPROTO | Indicates a protocol error. |
EPROTONOSUPPORT | Indicates that a protocol is not supported. |
EPROTOTYPE | Indicates the wrong type of protocol for a socket. |
ERANGE | Indicates that the results are too large. |
EROFS | Indicates that the file system is read only. |
ESPIPE | Indicates an invalid seek operation. |
ESRCH | Indicates that there is no such process. |
ESTALE | Indicates that the file handle is stale. |
ETIME | Indicates an expired timer. |
ETIMEDOUT | Indicates that the connection timed out. |
ETXTBSY | Indicates that a text file is busy. |
EWOULDBLOCK | Indicates that the operation would block. |
EXDEV | Indicates an improper link. |
The following error codes are specific to the Windows operating system.
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Constant | Description |
|---|---|
WSAEINTR | Indicates an interrupted function call. |
WSAEBADF | Indicates an invalid file handle. |
WSAEACCES | Indicates insufficient permissions to complete the operation. |
WSAEFAULT | Indicates an invalid pointer address. |
WSAEINVAL | Indicates that an invalid argument was passed. |
WSAEMFILE | Indicates that there are too many open files. |
WSAEWOULDBLOCK | Indicates that a resource is temporarily unavailable. |
WSAEINPROGRESS | Indicates that an operation is currently in progress. |
WSAEALREADY | Indicates that an operation is already in progress. |
WSAENOTSOCK | Indicates that the resource is not a socket. |
WSAEDESTADDRREQ | Indicates that a destination address is required. |
WSAEMSGSIZE | Indicates that the message size is too long. |
WSAEPROTOTYPE | Indicates the wrong protocol type for the socket. |
WSAENOPROTOOPT | Indicates a bad protocol option. |
WSAEPROTONOSUPPORT | Indicates that the protocol is not supported. |
WSAESOCKTNOSUPPORT | Indicates that the socket type is not supported. |
WSAEOPNOTSUPP | Indicates that the operation is not supported. |
WSAEPFNOSUPPORT | Indicates that the protocol family is not supported. |
WSAEAFNOSUPPORT | Indicates that the address family is not supported. |
WSAEADDRINUSE | Indicates that the network address is already in use. |
WSAEADDRNOTAVAIL | Indicates that the network address is not available. |
WSAENETDOWN | Indicates that the network is down. |
WSAENETUNREACH | Indicates that the network is unreachable. |
WSAENETRESET | Indicates that the network connection has been reset. |
WSAECONNABORTED | Indicates that the connection has been aborted. |
WSAECONNRESET | Indicates that the connection has been reset by the peer. |
WSAENOBUFS | Indicates that there is no buffer space available. |
WSAEISCONN | Indicates that the socket is already connected. |
WSAENOTCONN | Indicates that the socket is not connected. |
WSAESHUTDOWN | Indicates that data cannot be sent after the socket has been\n shutdown. |
WSAETOOMANYREFS | Indicates that there are too many references. |
WSAETIMEDOUT | Indicates that the connection has timed out. |
WSAECONNREFUSED | Indicates that the connection has been refused. |
WSAELOOP | Indicates that a name cannot be translated. |
WSAENAMETOOLONG | Indicates that a name was too long. |
WSAEHOSTDOWN | Indicates that a network host is down. |
WSAEHOSTUNREACH | Indicates that there is no route to a network host. |
WSAENOTEMPTY | Indicates that the directory is not empty. |
WSAEPROCLIM | Indicates that there are too many processes. |
WSAEUSERS | Indicates that the user quota has been exceeded. |
WSAEDQUOT | Indicates that the disk quota has been exceeded. |
WSAESTALE | Indicates a stale file handle reference. |
WSAEREMOTE | Indicates that the item is remote. |
WSASYSNOTREADY | Indicates that the network subsystem is not ready. |
WSAVERNOTSUPPORTED | Indicates that the winsock.dll version is out of\n range. |
WSANOTINITIALISED | Indicates that successful WSAStartup has not yet been performed. |
WSAEDISCON | Indicates that a graceful shutdown is in progress. |
WSAENOMORE | Indicates that there are no more results. |
WSAECANCELLED | Indicates that an operation has been canceled. |
WSAEINVALIDPROCTABLE | Indicates that the procedure call table is invalid. |
WSAEINVALIDPROVIDER | Indicates an invalid service provider. |
WSAEPROVIDERFAILEDINIT | Indicates that the service provider failed to initialized. |
WSASYSCALLFAILURE | Indicates a system call failure. |
WSASERVICE_NOT_FOUND | Indicates that a service was not found. |
WSATYPE_NOT_FOUND | Indicates that a class type was not found. |
WSA_E_NO_MORE | Indicates that there are no more results. |
WSA_E_CANCELLED | Indicates that the call was canceled. |
WSAEREFUSED | Indicates that a database query was refused. |
If available on the operating system, the following constants\nare exported in os.constants.dlopen. See dlopen(3) for detailed\ninformation.
| Constant | Description |
|---|---|
RTLD_LAZY | Perform lazy binding. Node.js sets this flag by default. |
RTLD_NOW | Resolve all undefined symbols in the library before dlopen(3)\n returns. |
RTLD_GLOBAL | Symbols defined by the library will be made available for symbol\n resolution of subsequently loaded libraries. |
RTLD_LOCAL | The converse of RTLD_GLOBAL. This is the default behavior\n if neither flag is specified. |
RTLD_DEEPBIND | Make a self-contained library use its own symbols in preference to\n symbols from previously loaded libraries. |
The following process scheduling constants are exported by\nos.constants.priority.
| Constant | Description |
|---|---|
PRIORITY_LOW | The lowest process scheduling priority. This corresponds to\n IDLE_PRIORITY_CLASS on Windows, and a nice value of\n 19 on all other platforms. |
PRIORITY_BELOW_NORMAL | The process scheduling priority above PRIORITY_LOW and\n below PRIORITY_NORMAL. This corresponds to\n BELOW_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 10 on all other platforms. |
PRIORITY_NORMAL | The default process scheduling priority. This corresponds to\n NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n 0 on all other platforms. |
PRIORITY_ABOVE_NORMAL | The process scheduling priority above PRIORITY_NORMAL and\n below PRIORITY_HIGH. This corresponds to\n ABOVE_NORMAL_PRIORITY_CLASS on Windows, and a nice value of\n -7 on all other platforms. |
PRIORITY_HIGH | The process scheduling priority above PRIORITY_ABOVE_NORMAL\n and below PRIORITY_HIGHEST. This corresponds to\n HIGH_PRIORITY_CLASS on Windows, and a nice value of\n -14 on all other platforms. |
PRIORITY_HIGHEST | The highest process scheduling priority. This corresponds to\n REALTIME_PRIORITY_CLASS on Windows, and a nice value of\n -20 on all other platforms. |
| Constant | Description |
|---|---|
UV_UDP_REUSEADDR |
The node:path module provides utilities for working with file and directory\npaths. It can be accessed using:
const path = require('node:path');\n\nimport path from 'node:path';\n",
"modules": [
{
"textRaw": "Windows vs. POSIX",
"name": "windows_vs._posix",
"type": "module",
"desc": "The default operation of the node:path module varies based on the operating\nsystem on which a Node.js application is running. Specifically, when running on\na Windows operating system, the node:path module will assume that\nWindows-style paths are being used.
So using path.basename() might yield different results on POSIX and Windows:
On POSIX:
\npath.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'C:\\\\temp\\\\myfile.html'\n\nOn Windows:
\npath.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n\nTo achieve consistent results when working with Windows file paths on any\noperating system, use path.win32:
On POSIX and Windows:
\npath.win32.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n\nTo achieve consistent results when working with POSIX file paths on any\noperating system, use path.posix:
On POSIX and Windows:
\npath.posix.basename('/tmp/myfile.html');\n// Returns: 'myfile.html'\n\nOn Windows Node.js follows the concept of per-drive working directory.\nThis behavior can be observed when using a drive path without a backslash. For\nexample, path.resolve('C:\\\\') can potentially return a different result than\npath.resolve('C:'). For more information, see\nthis MSDN page.
The path.basename() method returns the last portion of a path, similar to\nthe Unix basename command. Trailing directory separators are\nignored.
path.basename('/foo/bar/baz/asdf/quux.html');\n// Returns: 'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html');\n// Returns: 'quux'\n\nAlthough Windows usually treats file names, including file extensions, in a\ncase-insensitive manner, this function does not. For example, C:\\\\foo.html and\nC:\\\\foo.HTML refer to the same file, but basename treats the extension as a\ncase-sensitive string:
path.win32.basename('C:\\\\foo.html', '.html');\n// Returns: 'foo'\n\npath.win32.basename('C:\\\\foo.HTML', '.html');\n// Returns: 'foo.HTML'\n\nA TypeError is thrown if path is not a string or if suffix is given\nand is not a string.
The path.dirname() method returns the directory name of a path, similar to\nthe Unix dirname command. Trailing directory separators are ignored, see\npath.sep.
path.dirname('/foo/bar/baz/asdf/quux');\n// Returns: '/foo/bar/baz/asdf'\n\nA TypeError is thrown if path is not a string.
The path.extname() method returns the extension of the path, from the last\noccurrence of the . (period) character to end of string in the last portion of\nthe path. If there is no . in the last portion of the path, or if\nthere are no . characters other than the first character of\nthe basename of path (see path.basename()) , an empty string is returned.
path.extname('index.html');\n// Returns: '.html'\n\npath.extname('index.coffee.md');\n// Returns: '.md'\n\npath.extname('index.');\n// Returns: '.'\n\npath.extname('index');\n// Returns: ''\n\npath.extname('.index');\n// Returns: ''\n\npath.extname('.index.md');\n// Returns: '.md'\n\nA TypeError is thrown if path is not a string.
The path.format() method returns a path string from an object. This is the\nopposite of path.parse().
When providing properties to the pathObject remember that there are\ncombinations where one property has priority over another:
pathObject.root is ignored if pathObject.dir is providedpathObject.ext and pathObject.name are ignored if pathObject.base existsFor example, on POSIX:
\n// If `dir`, `root` and `base` are provided,\n// `${dir}${path.sep}${base}`\n// will be returned. `root` is ignored.\npath.format({\n root: '/ignored',\n dir: '/home/user/dir',\n base: 'file.txt',\n});\n// Returns: '/home/user/dir/file.txt'\n\n// `root` will be used if `dir` is not specified.\n// If only `root` is provided or `dir` is equal to `root` then the\n// platform separator will not be included. `ext` will be ignored.\npath.format({\n root: '/',\n base: 'file.txt',\n ext: 'ignored',\n});\n// Returns: '/file.txt'\n\n// `name` + `ext` will be used if `base` is not specified.\npath.format({\n root: '/',\n name: 'file',\n ext: '.txt',\n});\n// Returns: '/file.txt'\n\n// The dot will be added if it is not specified in `ext`.\npath.format({\n root: '/',\n name: 'file',\n ext: 'txt',\n});\n// Returns: '/file.txt'\n\nOn Windows:
\npath.format({\n dir: 'C:\\\\path\\\\dir',\n base: 'file.txt',\n});\n// Returns: 'C:\\\\path\\\\dir\\\\file.txt'\n"
},
{
"textRaw": "`path.matchesGlob(path, pattern)`",
"name": "matchesGlob",
"type": "method",
"meta": {
"added": [
"v22.5.0",
"v20.17.0"
],
"changes": [
{
"version": [
"v24.8.0",
"v22.20.0"
],
"pr-url": "https://github.com/nodejs/node/pull/59572",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {string} The path to glob-match against.",
"name": "path",
"type": "string",
"desc": "The path to glob-match against."
},
{
"textRaw": "`pattern` {string} The glob to check the path against.",
"name": "pattern",
"type": "string",
"desc": "The glob to check the path against."
}
],
"return": {
"textRaw": "Returns: {boolean} Whether or not the `path` matched the `pattern`.",
"name": "return",
"type": "boolean",
"desc": "Whether or not the `path` matched the `pattern`."
}
}
],
"desc": "The path.matchesGlob() method determines if path matches the pattern.
For example:
\npath.matchesGlob('/foo/bar', '/foo/*'); // true\npath.matchesGlob('/foo/bar*', 'foo/bird'); // false\n\nA TypeError is thrown if path or pattern are not strings.
The path.isAbsolute() method determines if the literal path is absolute.\nTherefore, it’s not safe for mitigating path traversals.
If the given path is a zero-length string, false will be returned.
For example, on POSIX:
\npath.isAbsolute('/foo/bar'); // true\npath.isAbsolute('/baz/..'); // true\npath.isAbsolute('/baz/../..'); // true\npath.isAbsolute('qux/'); // false\npath.isAbsolute('.'); // false\n\nOn Windows:
\npath.isAbsolute('//server'); // true\npath.isAbsolute('\\\\\\\\server'); // true\npath.isAbsolute('C:/foo/..'); // true\npath.isAbsolute('C:\\\\foo\\\\..'); // true\npath.isAbsolute('bar\\\\baz'); // false\npath.isAbsolute('bar/baz'); // false\npath.isAbsolute('.'); // false\n\nA TypeError is thrown if path is not a string.
The path.join() method joins all given path segments together using the\nplatform-specific separator as a delimiter, then normalizes the resulting path.
Zero-length path segments are ignored. If the joined path string is a\nzero-length string then '.' will be returned, representing the current\nworking directory.
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');\n// Returns: '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar');\n// Throws 'TypeError: Path must be a string. Received {}'\n\nA TypeError is thrown if any of the path segments is not a string.
The path.normalize() method normalizes the given path, resolving '..' and\n'.' segments.
When multiple, sequential path segment separation characters are found (e.g.\n/ on POSIX and either \\ or / on Windows), they are replaced by a single\ninstance of the platform-specific path segment separator (/ on POSIX and\n\\ on Windows). Trailing separators are preserved.
If the path is a zero-length string, '.' is returned, representing the\ncurrent working directory.
On POSIX, the types of normalization applied by this function do not strictly\nadhere to the POSIX specification. For example, this function will replace two\nleading forward slashes with a single slash as if it was a regular absolute\npath, whereas a few POSIX systems assign special meaning to paths beginning with\nexactly two forward slashes. Similarly, other substitutions performed by this\nfunction, such as removing .. segments, may change how the underlying system\nresolves the path.
For example, on POSIX:
\npath.normalize('/foo/bar//baz/asdf/quux/..');\n// Returns: '/foo/bar/baz/asdf'\n\nOn Windows:
\npath.normalize('C:\\\\temp\\\\\\\\foo\\\\bar\\\\..\\\\');\n// Returns: 'C:\\\\temp\\\\foo\\\\'\n\nSince Windows recognizes multiple path separators, both separators will be\nreplaced by instances of the Windows preferred separator (\\):
path.win32.normalize('C:////temp\\\\\\\\/\\\\/\\\\/foo/bar');\n// Returns: 'C:\\\\temp\\\\foo\\\\bar'\n\nA TypeError is thrown if path is not a string.
The path.parse() method returns an object whose properties represent\nsignificant elements of the path. Trailing directory separators are ignored,\nsee path.sep.
The returned object will have the following properties:
\n\nFor example, on POSIX:
\npath.parse('/home/user/dir/file.txt');\n// Returns:\n// { root: '/',\n// dir: '/home/user/dir',\n// base: 'file.txt',\n// ext: '.txt',\n// name: 'file' }\n\n┌─────────────────────┬────────────┐\n│ dir │ base │\n├──────┬ ├──────┬─────┤\n│ root │ │ name │ ext │\n\" / home/user/dir / file .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n\nOn Windows:
\npath.parse('C:\\\\path\\\\dir\\\\file.txt');\n// Returns:\n// { root: 'C:\\\\',\n// dir: 'C:\\\\path\\\\dir',\n// base: 'file.txt',\n// ext: '.txt',\n// name: 'file' }\n\n┌─────────────────────┬────────────┐\n│ dir │ base │\n├──────┬ ├──────┬─────┤\n│ root │ │ name │ ext │\n\" C:\\ path\\dir \\ file .txt \"\n└──────┴──────────────┴──────┴─────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n\nA TypeError is thrown if path is not a string.
The path.relative() method returns the relative path from from to to based\non the current working directory. If from and to each resolve to the same\npath (after calling path.resolve() on each), a zero-length string is returned.
If a zero-length string is passed as from or to, the current working\ndirectory will be used instead of the zero-length strings.
For example, on POSIX:
\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');\n// Returns: '../../impl/bbb'\n\nOn Windows:
\npath.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb');\n// Returns: '..\\\\..\\\\impl\\\\bbb'\n\nA TypeError is thrown if either from or to is not a string.
The path.resolve() method resolves a sequence of paths or path segments into\nan absolute path.
The given sequence of paths is processed from right to left, with each\nsubsequent path prepended until an absolute path is constructed.\nFor instance, given the sequence of path segments: /foo, /bar, baz,\ncalling path.resolve('/foo', '/bar', 'baz') would return /bar/baz\nbecause 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.
If, after processing all given path segments, an absolute path has not yet\nbeen generated, the current working directory is used.
The resulting path is normalized and trailing slashes are removed unless the\npath is resolved to the root directory.
\nZero-length path segments are ignored.
If no path segments are passed, path.resolve() will return the absolute path\nof the current working directory.
path.resolve('/foo/bar', './baz');\n// Returns: '/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/');\n// Returns: '/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');\n// If the current working directory is /home/myself/node,\n// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'\n\nA TypeError is thrown if any of the arguments is not a string.
On Windows systems only, returns an equivalent namespace-prefixed path for\nthe given path. If path is not a string, path will be returned without\nmodifications.
This method is meaningful only on Windows systems. On POSIX systems, the\nmethod is non-operational and always returns path without modifications.
Provides the platform-specific path delimiter:
\n; for Windows: for POSIXFor example, on POSIX:
\nconsole.log(process.env.PATH);\n// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']\n\nOn Windows:
\nconsole.log(process.env.PATH);\n// Prints: 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'\n\nprocess.env.PATH.split(path.delimiter);\n// Returns ['C:\\\\Windows\\\\system32', 'C:\\\\Windows', 'C:\\\\Program Files\\\\node\\\\']\n"
},
{
"textRaw": "Type: {Object}",
"name": "posix",
"type": "Object",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v15.3.0",
"pr-url": "https://github.com/nodejs/node/pull/34962",
"description": "Exposed as `require('path/posix')`."
}
]
},
"desc": "The path.posix property provides access to POSIX specific implementations\nof the path methods.
The API is accessible via require('node:path').posix or require('node:path/posix').
Provides the platform-specific path segment separator:
\n\\ on Windows/ on POSIXFor example, on POSIX:
\n'foo/bar/baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n\nOn Windows:
\n'foo\\\\bar\\\\baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n\nOn Windows, both the forward slash (/) and backward slash (\\) are accepted\nas path segment separators; however, the path methods only add backward\nslashes (\\).
The path.win32 property provides access to Windows-specific implementations\nof the path methods.
The API is accessible via require('node:path').win32 or require('node:path/win32').
This module provides an implementation of a subset of the W3C\nWeb Performance APIs as well as additional APIs for\nNode.js-specific performance measurements.
\nNode.js supports the following Web Performance APIs:
\n\nimport { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((items) => {\n console.log(items.getEntries()[0].duration);\n performance.clearMarks();\n});\nobs.observe({ type: 'measure' });\nperformance.measure('Start to Now');\n\nperformance.mark('A');\ndoSomeLongRunningProcess(() => {\n performance.measure('A to Now', 'A');\n\n performance.mark('B');\n performance.measure('A to B', 'A', 'B');\n});\n\nconst { PerformanceObserver, performance } = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n console.log(items.getEntries()[0].duration);\n});\nobs.observe({ type: 'measure' });\nperformance.measure('Start to Now');\n\nperformance.mark('A');\n(async function doSomeLongRunningProcess() {\n await new Promise((r) => setTimeout(r, 5000));\n performance.measure('A to Now', 'A');\n\n performance.mark('B');\n performance.measure('A to B', 'A', 'B');\n})();\n",
"properties": [
{
"textRaw": "`perf_hooks.performance`",
"name": "performance",
"type": "property",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"desc": "An object that can be used to collect performance metrics from the current\nNode.js instance. It is similar to window.performance in browsers.
If name is not provided, removes all PerformanceMark objects from the\nPerformance Timeline. If name is provided, removes only the named mark.
If name is not provided, removes all PerformanceMeasure objects from the\nPerformance Timeline. If name is provided, removes only the named measure.
If name is not provided, removes all PerformanceResourceTiming objects from\nthe Resource Timeline. If name is provided, removes only the named resource.
This is an alias of perf_hooks.eventLoopUtilization().
This property is an extension by Node.js. It is not available in Web browsers.
" }, { "textRaw": "`performance.getEntries()`", "name": "getEntries", "type": "method", "meta": { "added": [ "v16.7.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This method must be called with the `performance` object as the receiver." } ] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {PerformanceEntry[]}", "name": "return", "type": "PerformanceEntry[]" } } ], "desc": "Returns a list of PerformanceEntry objects in chronological order with\nrespect to performanceEntry.startTime. If you are only interested in\nperformance entries of certain types or that have certain names, see\nperformance.getEntriesByType() and performance.getEntriesByName().
Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.name is\nequal to name, and optionally, whose performanceEntry.entryType is equal to\ntype.
Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.entryType\nis equal to type.
Creates a new PerformanceMark entry in the Performance Timeline. A\nPerformanceMark is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'mark', and whose\nperformanceEntry.duration is always 0. Performance marks are used\nto mark specific significant moments in the Performance Timeline.
The created PerformanceMark entry is put in the global Performance Timeline\nand can be queried with performance.getEntries,\nperformance.getEntriesByName, and performance.getEntriesByType. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearMarks.
This property is an extension by Node.js. It is not available in Web browsers.
\nCreates a new PerformanceResourceTiming entry in the Resource Timeline. A\nPerformanceResourceTiming is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'resource'. Performance resources\nare used to mark moments in the Resource Timeline.
The created PerformanceMark entry is put in the global Resource Timeline\nand can be queried with performance.getEntries,\nperformance.getEntriesByName, and performance.getEntriesByType. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearResourceTimings.
Creates a new PerformanceMeasure entry in the Performance Timeline. A\nPerformanceMeasure is a subclass of PerformanceEntry whose\nperformanceEntry.entryType is always 'measure', and whose\nperformanceEntry.duration measures the number of milliseconds elapsed since\nstartMark and endMark.
The startMark argument may identify any existing PerformanceMark in the\nPerformance Timeline, or may identify any of the timestamp properties\nprovided by the PerformanceNodeTiming class. If the named startMark does\nnot exist, an error is thrown.
The optional endMark argument must identify any existing PerformanceMark\nin the Performance Timeline or any of the timestamp properties provided by the\nPerformanceNodeTiming class. endMark will be performance.now()\nif no parameter is passed, otherwise if the named endMark does not exist, an\nerror will be thrown.
The created PerformanceMeasure entry is put in the global Performance Timeline\nand can be queried with performance.getEntries,\nperformance.getEntriesByName, and performance.getEntriesByType. When the\nobservation is performed, the entries should be cleared from the global\nPerformance Timeline manually with performance.clearMeasures.
Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.
Sets the global performance resource timing buffer size to the specified number\nof \"resource\" type performance entry objects.
\nBy default the max buffer size is set to 250.
" }, { "textRaw": "`performance.timerify(fn[, options])`", "name": "timerify", "type": "method", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v25.2.0", "pr-url": "https://github.com/nodejs/node/pull/60370", "description": "Added `perf_hooks.timerify` alias." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37475", "description": "Added the histogram option." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Re-implemented to use pure-JavaScript and the ability to time async functions." } ] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function}", "name": "fn", "type": "Function" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`histogram` {RecordableHistogram} A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds.", "name": "histogram", "type": "RecordableHistogram", "desc": "A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds." } ], "optional": true } ] } ], "desc": "This is an alias of perf_hooks.timerify().
This property is an extension by Node.js. It is not available in Web browsers.
" }, { "textRaw": "`performance.toJSON()`", "name": "toJSON", "type": "method", "meta": { "added": [ "v16.1.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This method must be called with the `performance` object as the receiver." } ] }, "signatures": [ { "params": [] } ], "desc": "An object which is JSON representation of the performance object. It\nis similar to window.performance.toJSON in browsers.
The 'resourcetimingbufferfull' event is fired when the global performance\nresource timing buffer is full. Adjust resource timing buffer size with\nperformance.setResourceTimingBufferSize() or clear the buffer with\nperformance.clearResourceTimings() in the event listener to allow\nmore entries to be added to the performance timeline buffer.
This property is an extension by Node.js. It is not available in Web browsers.
\nAn instance of the PerformanceNodeTiming class that provides performance\nmetrics for specific Node.js operational milestones.
The timeOrigin specifies the high resolution millisecond timestamp at\nwhich the current node process began, measured in Unix time.
The constructor of this class is not exposed to users directly.
", "properties": [ { "textRaw": "Type: {number}", "name": "duration", "type": "number", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceEntry` object as the receiver." } ] }, "desc": "The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.
" }, { "textRaw": "Type: {string}", "name": "entryType", "type": "string", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceEntry` object as the receiver." } ] }, "desc": "The type of the performance entry. It may be one of:
\n'dns' (Node.js only)'function' (Node.js only)'gc' (Node.js only)'http2' (Node.js only)'http' (Node.js only)'mark' (available on the Web)'measure' (available on the Web)'net' (Node.js only)'node' (Node.js only)'resource' (available on the Web)The name of the performance entry.
" }, { "textRaw": "Type: {number}", "name": "startTime", "type": "number", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceEntry` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.
" } ] }, { "textRaw": "Class: `PerformanceMark`", "name": "PerformanceMark", "type": "class", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [] }, "desc": "<PerformanceEntry>Exposes marks created via the Performance.mark() method.
Additional detail specified when creating with Performance.mark() method.
<PerformanceEntry>Exposes measures created via the Performance.measure() method.
The constructor of this class is not exposed to users directly.
", "properties": [ { "textRaw": "Type: {any}", "name": "detail", "type": "any", "meta": { "added": [ "v16.0.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceMeasure` object as the receiver." } ] }, "desc": "Additional detail specified when creating with Performance.measure() method.
<PerformanceEntry>This class is an extension by Node.js. It is not available in Web browsers.
\nProvides detailed Node.js timing data.
\nThe constructor of this class is not exposed to users directly.
", "properties": [ { "textRaw": "Type: {any}", "name": "detail", "type": "any", "meta": { "added": [ "v16.0.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceNodeEntry` object as the receiver." } ] }, "desc": "Additional detail specific to the entryType.
When performanceEntry.entryType is equal to 'gc', the performance.flags\nproperty contains additional information about garbage collection operation.\nThe value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLEWhen performanceEntry.entryType is equal to 'gc', the performance.kind\nproperty identifies the type of garbage collection operation that occurred.\nThe value may be one of:
perf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCBWhen performanceEntry.type is equal to 'gc', the\nperformanceNodeEntry.detail property will be an <Object> with two properties:
kind <number> One of:\nperf_hooks.constants.NODE_PERFORMANCE_GC_MAJORperf_hooks.constants.NODE_PERFORMANCE_GC_MINORperf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTALperf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCBflags <number> One of:\nperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NOperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCEDperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSINGperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGEperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORYperf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLEWhen performanceEntry.type is equal to 'http', the\nperformanceNodeEntry.detail property will be an <Object> containing\nadditional information.
If performanceEntry.name is equal to HttpClient, the detail\nwill contain the following properties: req, res. And the req property\nwill be an <Object> containing method, url, headers, the res property\nwill be an <Object> containing statusCode, statusMessage, headers.
If performanceEntry.name is equal to HttpRequest, the detail\nwill contain the following properties: req, res. And the req property\nwill be an <Object> containing method, url, headers, the res property\nwill be an <Object> containing statusCode, statusMessage, headers.
This could add additional memory overhead and should only be used for\ndiagnostic purposes, not left turned on in production by default.
", "displayName": "HTTP ('http') Details" }, { "textRaw": "HTTP/2 ('http2') Details", "name": "http/2_('http2')_details", "type": "module", "desc": "When performanceEntry.type is equal to 'http2', the\nperformanceNodeEntry.detail property will be an <Object> containing\nadditional performance information.
If performanceEntry.name is equal to Http2Stream, the detail\nwill contain the following properties:
bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.id <number> The identifier of the associated Http2StreamtimeToFirstByte <number> The number of milliseconds elapsed between the PerformanceEntry startTime and the reception of the first DATA frame.timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.timeToFirstHeader <number> The number of milliseconds elapsed between the PerformanceEntry startTime and the reception of the first header.If performanceEntry.name is equal to Http2Session, the detail will\ncontain the following properties:
bytesRead <number> The number of bytes received for this Http2Session.bytesWritten <number> The number of bytes sent for this Http2Session.framesReceived <number> The number of HTTP/2 frames received by the Http2Session.framesSent <number> The number of HTTP/2 frames sent by the Http2Session.maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.pingRTT <number> The number of milliseconds elapsed since the transmission\nof a PING frame and the reception of its acknowledgment. Only present if\na PING frame has been sent on the Http2Session.streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.When performanceEntry.type is equal to 'function', the\nperformanceNodeEntry.detail property will be an <Array> listing\nthe input arguments to the timed function.
When performanceEntry.type is equal to 'net', the\nperformanceNodeEntry.detail property will be an <Object> containing\nadditional information.
If performanceEntry.name is equal to connect, the detail\nwill contain the following properties: host, port.
When performanceEntry.type is equal to 'dns', the\nperformanceNodeEntry.detail property will be an <Object> containing\nadditional information.
If performanceEntry.name is equal to lookup, the detail\nwill contain the following properties: hostname, family, hints, verbatim,\naddresses.
If performanceEntry.name is equal to lookupService, the detail will\ncontain the following properties: host, port, hostname, service.
If performanceEntry.name is equal to queryxxx or getHostByAddr, the detail will\ncontain the following properties: host, ttl, result. The value of result is\nsame as the result of queryxxx or getHostByAddr.
<PerformanceEntry>This property is an extension by Node.js. It is not available in Web browsers.
\nProvides timing details for Node.js itself. The constructor of this class\nis not exposed to users.
", "properties": [ { "textRaw": "Type: {number}", "name": "bootstrapComplete", "type": "number", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js process\ncompleted bootstrapping. If bootstrapping has not yet finished, the property\nhas the value of -1.
" }, { "textRaw": "Type: {number}", "name": "environment", "type": "number", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.
" }, { "textRaw": "Type: {number}", "name": "idleTime", "type": "number", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp of the amount of time the event loop\nhas been idle within the event loop's event provider (e.g. epoll_wait). This\ndoes not take CPU usage into consideration. If the event loop has not yet\nstarted (e.g., in the first tick of the main script), the property has the\nvalue of 0.
The high resolution millisecond timestamp at which the Node.js event loop\nexited. If the event loop has not yet exited, the property has the value of -1.\nIt can only have a value of not -1 in a handler of the 'exit' event.
The high resolution millisecond timestamp at which the Node.js event loop\nstarted. If the event loop has not yet started (e.g., in the first tick of the\nmain script), the property has the value of -1.
" }, { "textRaw": "Type: {number}", "name": "nodeStart", "type": "number", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "The high resolution millisecond timestamp at which the Node.js process was\ninitialized.
" }, { "textRaw": "Returns: {Object}", "name": "uvMetricsInfo", "type": "Object", "meta": { "added": [ "v22.8.0", "v20.18.0" ], "changes": [] }, "desc": "This is a wrapper to the uv_metrics_info function.\nIt returns the current set of event loop metrics.
It is recommended to use this property inside a function whose execution was\nscheduled using setImmediate to avoid collecting metrics before finishing all\noperations scheduled during the current loop iteration.
const { performance } = require('node:perf_hooks');\n\nsetImmediate(() => {\n console.log(performance.nodeTiming.uvMetricsInfo);\n});\n\nimport { performance } from 'node:perf_hooks';\n\nsetImmediate(() => {\n console.log(performance.nodeTiming.uvMetricsInfo);\n});\n",
"options": [
{
"textRaw": "`loopCount` {number} Number of event loop iterations.",
"name": "loopCount",
"type": "number",
"desc": "Number of event loop iterations."
},
{
"textRaw": "`events` {number} Number of events that have been processed by the event handler.",
"name": "events",
"type": "number",
"desc": "Number of events that have been processed by the event handler."
},
{
"textRaw": "`eventsWaiting` {number} Number of events that were waiting to be processed when the event provider was called.",
"name": "eventsWaiting",
"type": "number",
"desc": "Number of events that were waiting to be processed when the event provider was called."
}
]
},
{
"textRaw": "Type: {number}",
"name": "v8Start",
"type": "number",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"desc": "The high resolution millisecond timestamp at which the V8 platform was\ninitialized.
" } ] }, { "textRaw": "Class: `PerformanceResourceTiming`", "name": "PerformanceResourceTiming", "type": "class", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [] }, "desc": "<PerformanceEntry>Provides detailed network timing data regarding the loading of an application's\nresources.
\nThe constructor of this class is not exposed to users directly.
", "properties": [ { "textRaw": "Type: {number}", "name": "workerStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp at immediately before dispatching\nthe fetch request. If the resource is not intercepted by a worker the property\nwill always return 0.
The high resolution millisecond timestamp that represents the start time\nof the fetch which initiates the redirect.
" }, { "textRaw": "Type: {number}", "name": "redirectEnd", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp that will be created immediately after\nreceiving the last byte of the response of the last redirect.
" }, { "textRaw": "Type: {number}", "name": "fetchStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp immediately before the Node.js starts\nto fetch the resource.
" }, { "textRaw": "Type: {number}", "name": "domainLookupStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp immediately before the Node.js starts\nthe domain name lookup for the resource.
" }, { "textRaw": "Type: {number}", "name": "domainLookupEnd", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter the Node.js finished the domain name lookup for the resource.
" }, { "textRaw": "Type: {number}", "name": "connectStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts to establish the connection to the server to retrieve\nthe resource.
" }, { "textRaw": "Type: {number}", "name": "connectEnd", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter Node.js finishes establishing the connection to the server to retrieve\nthe resource.
" }, { "textRaw": "Type: {number}", "name": "secureConnectionStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js starts the handshake process to secure the current connection.
" }, { "textRaw": "Type: {number}", "name": "requestStart", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nbefore Node.js receives the first byte of the response from the server.
" }, { "textRaw": "Type: {number}", "name": "responseEnd", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "The high resolution millisecond timestamp representing the time immediately\nafter Node.js receives the last byte of the resource or immediately before\nthe transport connection is closed, whichever comes first.
" }, { "textRaw": "Type: {number}", "name": "transferSize", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "A number representing the size (in octets) of the fetched resource. The size\nincludes the response header fields plus the response payload body.
" }, { "textRaw": "Type: {number}", "name": "encodedBodySize", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "A number representing the size (in octets) received from the fetch\n(HTTP or cache), of the payload body, before removing any applied\ncontent-codings.
" }, { "textRaw": "Type: {number}", "name": "decodedBodySize", "type": "number", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This property getter must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "desc": "A number representing the size (in octets) received from the fetch\n(HTTP or cache), of the message body, after removing any applied\ncontent-codings.
" } ], "methods": [ { "textRaw": "`performanceResourceTiming.toJSON()`", "name": "toJSON", "type": "method", "meta": { "added": [ "v18.2.0", "v16.17.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44483", "description": "This method must be called with the `PerformanceResourceTiming` object as the receiver." } ] }, "signatures": [ { "params": [] } ], "desc": "Returns a object that is the JSON representation of the\nPerformanceResourceTiming object
Get supported types.
" } ], "signatures": [ { "textRaw": "`new PerformanceObserver(callback)`", "name": "PerformanceObserver", "type": "ctor", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`list` {PerformanceObserverEntryList}", "name": "list", "type": "PerformanceObserverEntryList" }, { "textRaw": "`observer` {PerformanceObserver}", "name": "observer", "type": "PerformanceObserver" } ] } ], "desc": "PerformanceObserver objects provide notifications when new\nPerformanceEntry instances have been added to the Performance Timeline.
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries());\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries());\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n\nBecause PerformanceObserver instances introduce their own additional\nperformance overhead, instances should not be left subscribed to notifications\nindefinitely. Users should disconnect observers as soon as they are no\nlonger needed.
The callback is invoked when a PerformanceObserver is\nnotified about new PerformanceEntry instances. The callback receives a\nPerformanceObserverEntryList instance and a reference to the\nPerformanceObserver.
Disconnects the PerformanceObserver instance from all notifications.
Subscribes the <PerformanceObserver> instance to notifications of new\n<PerformanceEntry> instances identified either by options.entryTypes\nor options.type:
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((list, observer) => {\n // Called once asynchronously. `list` contains three items.\n});\nobs.observe({ type: 'mark' });\n\nfor (let n = 0; n < 3; n++)\n performance.mark(`test${n}`);\n\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n // Called once asynchronously. `list` contains three items.\n});\nobs.observe({ type: 'mark' });\n\nfor (let n = 0; n < 3; n++)\n performance.mark(`test${n}`);\n"
},
{
"textRaw": "`performanceObserver.takeRecords()`",
"name": "takeRecords",
"type": "method",
"meta": {
"added": [
"v16.0.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {PerformanceEntry[]} Current list of entries stored in the performance observer, emptying it out.",
"name": "return",
"type": "PerformanceEntry[]",
"desc": "Current list of entries stored in the performance observer, emptying it out."
}
}
]
}
]
},
{
"textRaw": "Class: `PerformanceObserverEntryList`",
"name": "PerformanceObserverEntryList",
"type": "class",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"desc": "The PerformanceObserverEntryList class is used to provide access to the\nPerformanceEntry instances passed to a PerformanceObserver.\nThe constructor of this class is not exposed to users.
Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime.
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntries());\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 81.465639,\n * duration: 0,\n * detail: null\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 81.860064,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntries());\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 81.465639,\n * duration: 0,\n * detail: null\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 81.860064,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n"
},
{
"textRaw": "`performanceObserverEntryList.getEntriesByName(name[, type])`",
"name": "getEntriesByName",
"type": "method",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`type` {string}",
"name": "type",
"type": "string",
"optional": true
}
],
"return": {
"textRaw": "Returns: {PerformanceEntry[]}",
"name": "return",
"type": "PerformanceEntry[]"
}
}
],
"desc": "Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.name is\nequal to name, and optionally, whose performanceEntry.entryType is equal to\ntype.
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByName('meow'));\n /**\n * [\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 98.545991,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('nope')); // []\n\n console.log(perfObserverList.getEntriesByName('test', 'mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 63.518931,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('test', 'measure')); // []\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark', 'measure'] });\n\nperformance.mark('test');\nperformance.mark('meow');\n\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByName('meow'));\n /**\n * [\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 98.545991,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('nope')); // []\n\n console.log(perfObserverList.getEntriesByName('test', 'mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 63.518931,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n console.log(perfObserverList.getEntriesByName('test', 'measure')); // []\n\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark', 'measure'] });\n\nperformance.mark('test');\nperformance.mark('meow');\n"
},
{
"textRaw": "`performanceObserverEntryList.getEntriesByType(type)`",
"name": "getEntriesByType",
"type": "method",
"meta": {
"added": [
"v8.5.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`type` {string}",
"name": "type",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {PerformanceEntry[]}",
"name": "return",
"type": "PerformanceEntry[]"
}
}
],
"desc": "Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.entryType\nis equal to type.
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByType('mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 55.897834,\n * duration: 0,\n * detail: null\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 56.350146,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((perfObserverList, observer) => {\n console.log(perfObserverList.getEntriesByType('mark'));\n /**\n * [\n * PerformanceEntry {\n * name: 'test',\n * entryType: 'mark',\n * startTime: 55.897834,\n * duration: 0,\n * detail: null\n * },\n * PerformanceEntry {\n * name: 'meow',\n * entryType: 'mark',\n * startTime: 56.350146,\n * duration: 0,\n * detail: null\n * }\n * ]\n */\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n"
}
]
},
{
"textRaw": "Class: `Histogram`",
"name": "Histogram",
"type": "class",
"meta": {
"added": [
"v11.10.0"
],
"changes": []
},
"properties": [
{
"textRaw": "Type: {number}",
"name": "count",
"type": "number",
"meta": {
"added": [
"v17.4.0",
"v16.14.0"
],
"changes": []
},
"desc": "The number of samples recorded by the histogram.
" }, { "textRaw": "Type: {bigint}", "name": "countBigInt", "type": "bigint", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The number of samples recorded by the histogram.
" }, { "textRaw": "Type: {number}", "name": "exceeds", "type": "number", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.
" }, { "textRaw": "Type: {bigint}", "name": "exceedsBigInt", "type": "bigint", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The number of times the event loop delay exceeded the maximum 1 hour event\nloop delay threshold.
" }, { "textRaw": "Type: {number}", "name": "max", "type": "number", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The maximum recorded event loop delay.
" }, { "textRaw": "Type: {bigint}", "name": "maxBigInt", "type": "bigint", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The maximum recorded event loop delay.
" }, { "textRaw": "Type: {number}", "name": "mean", "type": "number", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The mean of the recorded event loop delays.
" }, { "textRaw": "Type: {number}", "name": "min", "type": "number", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "The minimum recorded event loop delay.
" }, { "textRaw": "Type: {bigint}", "name": "minBigInt", "type": "bigint", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "desc": "The minimum recorded event loop delay.
" }, { "textRaw": "Type: {Map}", "name": "percentiles", "type": "Map", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "Returns a Map object detailing the accumulated percentile distribution.
Returns a Map object detailing the accumulated percentile distribution.
The standard deviation of the recorded event loop delays.
" } ], "methods": [ { "textRaw": "`histogram.percentile(percentile)`", "name": "percentile", "type": "method", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`percentile` {number} A percentile value in the range (0, 100].", "name": "percentile", "type": "number", "desc": "A percentile value in the range (0, 100]." } ], "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" } } ], "desc": "Returns the value at the given percentile.
" }, { "textRaw": "`histogram.percentileBigInt(percentile)`", "name": "percentileBigInt", "type": "method", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`percentile` {number} A percentile value in the range (0, 100].", "name": "percentile", "type": "number", "desc": "A percentile value in the range (0, 100]." } ], "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" } } ], "desc": "Returns the value at the given percentile.
" }, { "textRaw": "`histogram.reset()`", "name": "reset", "type": "method", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Resets the collected histogram data.
" } ] }, { "textRaw": "Class: `IntervalHistogram extends Histogram`", "name": "IntervalHistogram extends Histogram", "type": "class", "desc": "A Histogram that is periodically updated on a given interval.
Disables the update interval timer. Returns true if the timer was\nstopped, false if it was already stopped.
Enables the update interval timer. Returns true if the timer was\nstarted, false if it was already started.
Disables the update interval timer when the histogram is disposed.
\nconst { monitorEventLoopDelay } = require('node:perf_hooks');\n{\n using hist = monitorEventLoopDelay({ resolution: 20 });\n hist.enable();\n // The histogram will be disabled when the block is exited.\n}\n"
}
],
"modules": [
{
"textRaw": "Cloning an `IntervalHistogram`",
"name": "cloning_an_`intervalhistogram`",
"type": "module",
"desc": "<IntervalHistogram> instances can be cloned via <MessagePort>. On the receiving\nend, the histogram is cloned as a plain <Histogram> object that does not\nimplement the enable() and disable() methods.
Adds the values from other to this histogram.
Calculates the amount of time (in nanoseconds) that has passed since the\nprevious call to recordDelta() and records that amount in the histogram.
Returns a <RecordableHistogram>.
The eventLoopUtilization() function returns an object that contains the\ncumulative duration of time the event loop has been both idle and active as a\nhigh resolution milliseconds timer. The utilization value is the calculated\nEvent Loop Utilization (ELU).
If bootstrapping has not yet finished on the main thread the properties have\nthe value of 0. The ELU is immediately available on Worker threads since\nbootstrap happens within the event loop.
Both utilization1 and utilization2 are optional parameters.
If utilization1 is passed, then the delta between the current call's active\nand idle times, as well as the corresponding utilization value are\ncalculated and returned (similar to process.hrtime()).
If utilization1 and utilization2 are both passed, then the delta is\ncalculated between the two arguments. This is a convenience option because,\nunlike process.hrtime(), calculating the ELU is more complex than a\nsingle subtraction.
ELU is similar to CPU utilization, except that it only measures event loop\nstatistics and not CPU usage. It represents the percentage of time the event\nloop has spent outside the event loop's event provider (e.g. epoll_wait).\nNo other CPU idle time is taken into consideration. The following is an example\nof how a mostly idle process will have a high ELU.
import { eventLoopUtilization } from 'node:perf_hooks';\nimport { spawnSync } from 'node:child_process';\n\nsetImmediate(() => {\n const elu = eventLoopUtilization();\n spawnSync('sleep', ['5']);\n console.log(eventLoopUtilization(elu).utilization);\n});\n\n'use strict';\nconst { eventLoopUtilization } = require('node:perf_hooks');\nconst { spawnSync } = require('node:child_process');\n\nsetImmediate(() => {\n const elu = eventLoopUtilization();\n spawnSync('sleep', ['5']);\n console.log(eventLoopUtilization(elu).utilization);\n});\n\nAlthough the CPU is mostly idle while running this script, the value of\nutilization is 1. This is because the call to\nchild_process.spawnSync() blocks the event loop from proceeding.
Passing in a user-defined object instead of the result of a previous call to\neventLoopUtilization() will lead to undefined behavior. The return values\nare not guaranteed to reflect any correct state of the event loop.
This property is an extension by Node.js. It is not available in Web browsers.
\nCreates an IntervalHistogram object that samples and reports the event loop\ndelay over time. The delays will be reported in nanoseconds.
Using a timer to detect approximate event loop delay works because the\nexecution of timers is tied specifically to the lifecycle of the libuv\nevent loop. That is, a delay in the loop will cause a delay in the execution\nof the timer, and those delays are specifically what this API is intended to\ndetect.
\nimport { monitorEventLoopDelay } from 'node:perf_hooks';\n\nconst h = monitorEventLoopDelay({ resolution: 20 });\nh.enable();\n// Do something.\nh.disable();\nconsole.log(h.min);\nconsole.log(h.max);\nconsole.log(h.mean);\nconsole.log(h.stddev);\nconsole.log(h.percentiles);\nconsole.log(h.percentile(50));\nconsole.log(h.percentile(99));\n\nconst { monitorEventLoopDelay } = require('node:perf_hooks');\nconst h = monitorEventLoopDelay({ resolution: 20 });\nh.enable();\n// Do something.\nh.disable();\nconsole.log(h.min);\nconsole.log(h.max);\nconsole.log(h.mean);\nconsole.log(h.stddev);\nconsole.log(h.percentiles);\nconsole.log(h.percentile(50));\nconsole.log(h.percentile(99));\n"
},
{
"textRaw": "`perf_hooks.timerify(fn[, options])`",
"name": "timerify",
"type": "method",
"meta": {
"added": [
"v25.2.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function}",
"name": "fn",
"type": "Function"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`histogram` {RecordableHistogram} A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds.",
"name": "histogram",
"type": "RecordableHistogram",
"desc": "A histogram object created using `perf_hooks.createHistogram()` that will record runtime durations in nanoseconds."
}
],
"optional": true
}
]
}
],
"desc": "This property is an extension by Node.js. It is not available in Web browsers.
\nWraps a function within a new function that measures the running time of the\nwrapped function. A PerformanceObserver must be subscribed to the 'function'\nevent type in order for the timing details to be accessed.
import { timerify, performance, PerformanceObserver } from 'node:perf_hooks';\n\nfunction someFunction() {\n console.log('hello world');\n}\n\nconst wrapped = timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n console.log(list.getEntries()[0].duration);\n\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n\nconst {\n timerify,\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nfunction someFunction() {\n console.log('hello world');\n}\n\nconst wrapped = timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n console.log(list.getEntries()[0].duration);\n\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n\nIf the wrapped function returns a promise, a finally handler will be attached\nto the promise and the duration will be reported once the finally handler is\ninvoked.
" } ], "modules": [ { "textRaw": "Examples", "name": "examples", "type": "module", "modules": [ { "textRaw": "Measuring the duration of async operations", "name": "measuring_the_duration_of_async_operations", "type": "module", "desc": "The following example uses the Async Hooks and Performance APIs to measure\nthe actual duration of a Timeout operation (including the amount of time it took\nto execute the callback).
\nimport { createHook } from 'node:async_hooks';\nimport { performance, PerformanceObserver } from 'node:perf_hooks';\n\nconst set = new Set();\nconst hook = createHook({\n init(id, type) {\n if (type === 'Timeout') {\n performance.mark(`Timeout-${id}-Init`);\n set.add(id);\n }\n },\n destroy(id) {\n if (set.has(id)) {\n set.delete(id);\n performance.mark(`Timeout-${id}-Destroy`);\n performance.measure(`Timeout-${id}`,\n `Timeout-${id}-Init`,\n `Timeout-${id}-Destroy`);\n }\n },\n});\nhook.enable();\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries()[0]);\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'], buffered: true });\n\nsetTimeout(() => {}, 1000);\n\n'use strict';\nconst async_hooks = require('node:async_hooks');\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\n\nconst set = new Set();\nconst hook = async_hooks.createHook({\n init(id, type) {\n if (type === 'Timeout') {\n performance.mark(`Timeout-${id}-Init`);\n set.add(id);\n }\n },\n destroy(id) {\n if (set.has(id)) {\n set.delete(id);\n performance.mark(`Timeout-${id}-Destroy`);\n performance.measure(`Timeout-${id}`,\n `Timeout-${id}-Init`,\n `Timeout-${id}-Destroy`);\n }\n },\n});\nhook.enable();\n\nconst obs = new PerformanceObserver((list, observer) => {\n console.log(list.getEntries()[0]);\n performance.clearMarks();\n performance.clearMeasures();\n observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'] });\n\nsetTimeout(() => {}, 1000);\n",
"displayName": "Measuring the duration of async operations"
},
{
"textRaw": "Measuring how long it takes to load dependencies",
"name": "measuring_how_long_it_takes_to_load_dependencies",
"type": "module",
"desc": "The following example measures the duration of require() operations to load\ndependencies:
import { performance, PerformanceObserver } from 'node:perf_hooks';\n\n// Activate the observer\nconst obs = new PerformanceObserver((list) => {\n const entries = list.getEntries();\n entries.forEach((entry) => {\n console.log(`import('${entry[0]}')`, entry.duration);\n });\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'], buffered: true });\n\nconst timedImport = performance.timerify(async (module) => {\n return await import(module);\n});\n\nawait timedImport('some-module');\n\n'use strict';\nconst {\n performance,\n PerformanceObserver,\n} = require('node:perf_hooks');\nconst mod = require('node:module');\n\n// Monkey patch the require function\nmod.Module.prototype.require =\n performance.timerify(mod.Module.prototype.require);\nrequire = performance.timerify(require);\n\n// Activate the observer\nconst obs = new PerformanceObserver((list) => {\n const entries = list.getEntries();\n entries.forEach((entry) => {\n console.log(`require('${entry[0]}')`, entry.duration);\n });\n performance.clearMarks();\n performance.clearMeasures();\n obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\nrequire('some-module');\n",
"displayName": "Measuring how long it takes to load dependencies"
},
{
"textRaw": "Measuring how long one HTTP round-trip takes",
"name": "measuring_how_long_one_http_round-trip_takes",
"type": "module",
"desc": "The following example is used to trace the time spent by HTTP client\n(OutgoingMessage) and HTTP request (IncomingMessage). For HTTP client,\nit means the time interval between starting the request and receiving the\nresponse, and for HTTP request, it means the time interval between receiving\nthe request and sending the response:
import { PerformanceObserver } from 'node:perf_hooks';\nimport { createServer, get } from 'node:http';\n\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\n\nobs.observe({ entryTypes: ['http'] });\n\nconst PORT = 8080;\n\ncreateServer((req, res) => {\n res.end('ok');\n}).listen(PORT, () => {\n get(`http://127.0.0.1:${PORT}`);\n});\n\n'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst http = require('node:http');\n\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\n\nobs.observe({ entryTypes: ['http'] });\n\nconst PORT = 8080;\n\nhttp.createServer((req, res) => {\n res.end('ok');\n}).listen(PORT, () => {\n http.get(`http://127.0.0.1:${PORT}`);\n});\n",
"displayName": "Measuring how long one HTTP round-trip takes"
},
{
"textRaw": "Measuring how long the `net.connect` (only for TCP) takes when the connection is successful",
"name": "measuring_how_long_the_`net.connect`_(only_for_tcp)_takes_when_the_connection_is_successful",
"type": "module",
"desc": "import { PerformanceObserver } from 'node:perf_hooks';\nimport { connect, createServer } from 'node:net';\n\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['net'] });\nconst PORT = 8080;\ncreateServer((socket) => {\n socket.destroy();\n}).listen(PORT, () => {\n connect(PORT);\n});\n\n'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst net = require('node:net');\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['net'] });\nconst PORT = 8080;\nnet.createServer((socket) => {\n socket.destroy();\n}).listen(PORT, () => {\n net.connect(PORT);\n});\n",
"displayName": "Measuring how long the `net.connect` (only for TCP) takes when the connection is successful"
},
{
"textRaw": "Measuring how long the DNS takes when the request is successful",
"name": "measuring_how_long_the_dns_takes_when_the_request_is_successful",
"type": "module",
"desc": "import { PerformanceObserver } from 'node:perf_hooks';\nimport { lookup, promises } from 'node:dns';\n\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['dns'] });\nlookup('localhost', () => {});\npromises.resolve('localhost');\n\n'use strict';\nconst { PerformanceObserver } = require('node:perf_hooks');\nconst dns = require('node:dns');\nconst obs = new PerformanceObserver((items) => {\n items.getEntries().forEach((item) => {\n console.log(item);\n });\n});\nobs.observe({ entryTypes: ['dns'] });\ndns.lookup('localhost', () => {});\ndns.promises.resolve('localhost');\n",
"displayName": "Measuring how long the DNS takes when the request is successful"
}
],
"displayName": "Examples"
}
],
"displayName": "Performance measurement APIs",
"source": "doc/api/perf_hooks.md"
},
{
"textRaw": "Permissions",
"name": "permissions",
"introduced_in": "v20.0.0",
"type": "module",
"desc": "Permissions can be used to control what system resources the\nNode.js process has access to or what actions the process can take\nwith those resources.
\nThe permission model implements a \"seat belt\" approach, which prevents trusted\ncode from unintentionally changing files or using resources that access has\nnot explicitly been granted to. It does not provide security guarantees in the\npresence of malicious code. Malicious code can bypass the permission model and\nexecute arbitrary code without the restrictions imposed by the permission\nmodel.
\nIf you find a potential security vulnerability, please refer to our\nSecurity Policy.
", "modules": [ { "textRaw": "Process-based permissions", "name": "process-based_permissions", "type": "module", "modules": [ { "textRaw": "Permission Model", "name": "permission_model", "type": "module", "meta": { "added": [ "v20.0.0" ], "changes": [ { "version": [ "v23.5.0", "v22.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/56201", "description": "This feature is no longer experimental." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "The Node.js Permission Model is a mechanism for restricting access to specific\nresources during execution.\nThe API exists behind a flag --permission which when enabled,\nwill restrict access to all available permissions.
The available permissions are documented by the --permission\nflag.
When starting Node.js with --permission,\nthe ability to access the file system through the fs module, access the network,\nspawn processes, use node:worker_threads, use native addons, use WASI, and\nenable the runtime inspector will be restricted (the listener for SIGUSR1 won't\nbe created).
$ node --permission index.js\n\nError: Access to this API has been restricted\n at node:internal/main/run_main_module:23:47 {\n code: 'ERR_ACCESS_DENIED',\n permission: 'FileSystemRead',\n resource: '/home/user/index.js'\n}\n\nAllowing access to spawning a process and creating worker threads can be done\nusing the --allow-child-process and --allow-worker respectively.
To allow network access, use --allow-net and for allowing native addons\nwhen using permission model, use the --allow-addons\nflag. For WASI, use the --allow-wasi flag.
When enabling the Permission Model through the --permission\nflag a new property permission is added to the process object.\nThis property contains one function:
API call to check permissions at runtime (permission.has())
process.permission.has('fs.write'); // true\nprocess.permission.has('fs.write', '/home/rafaelgss/protected-folder'); // true\n\nprocess.permission.has('fs.read'); // true\nprocess.permission.has('fs.read', '/home/rafaelgss/protected-folder'); // false\n"
}
],
"displayName": "Runtime API"
},
{
"textRaw": "File System Permissions",
"name": "file_system_permissions",
"type": "module",
"desc": "The Permission Model, by default, restricts access to the file system through the node:fs module.\nIt does not guarantee that users will not be able to access the file system through other means,\nsuch as through the node:sqlite module.
To allow access to the file system, use the --allow-fs-read and\n--allow-fs-write flags:
$ node --permission --allow-fs-read=* --allow-fs-write=* index.js\nHello world!\n\nBy default the entrypoints of your application are included\nin the allowed file system read list. For example:
\n$ node --permission index.js\n\nindex.js will be included in the allowed file system read list$ node -r /path/to/custom-require.js --permission index.js.\n\n/path/to/custom-require.js will be included in the allowed file system read\nlist.index.js will be included in the allowed file system read list.The valid arguments for both flags are:
\n* - To allow all FileSystemRead or FileSystemWrite operations,\nrespectively.Example:
\n--allow-fs-read=* - It will allow all FileSystemRead operations.--allow-fs-write=* - It will allow all FileSystemWrite operations.--allow-fs-write=/tmp/ - It will allow FileSystemWrite access to the /tmp/\nfolder.--allow-fs-read=/tmp/ --allow-fs-read=/home/.gitignore - It allows FileSystemRead access\nto the /tmp/ folder and the /home/.gitignore path.Wildcards are supported too:
\n--allow-fs-read=/home/test* will allow read access to everything\nthat matches the wildcard. e.g: /home/test/file1 or /home/test2After passing a wildcard character (*) all subsequent characters will\nbe ignored. For example: /home/*.js will work similar to /home/*.
When the permission model is initialized, it will automatically add a wildcard\n(*) if the specified directory exists. For example, if /home/test/files\nexists, it will be treated as /home/test/files/*. However, if the directory\ndoes not exist, the wildcard will not be added, and access will be limited to\n/home/test/files. If you want to allow access to a folder that does not exist\nyet, make sure to explicitly include the wildcard:\n/my-path/folder-do-not-exist/*.
In addition to passing permission flags on the command line, they can also be\ndeclared in a Node.js configuration file when using the experimental\n[--experimental-config-file][] flag. Permission options must be placed inside\nthe permission top-level object.
Example node.config.json:
{\n \"permission\": {\n \"allow-fs-read\": [\"./foo\"],\n \"allow-fs-write\": [\"./bar\"],\n \"allow-child-process\": true,\n \"allow-worker\": true,\n \"allow-net\": true,\n \"allow-addons\": false\n }\n}\n\nWhen the permission namespace is present in the configuration file, Node.js\nautomatically enables the --permission flag. Run with:
$ node --experimental-default-config-file app.js\n",
"displayName": "Configuration file support"
},
{
"textRaw": "Using the Permission Model with `npx`",
"name": "using_the_permission_model_with_`npx`",
"type": "module",
"desc": "If you're using npx to execute a Node.js script, you can enable the\nPermission Model by passing the --node-options flag. For example:
npx --node-options=\"--permission\" package-name\n\nThis sets the NODE_OPTIONS environment variable for all Node.js processes\nspawned by npx, without affecting the npx process itself.
FileSystemRead Error with npx
The above command will likely throw a FileSystemRead invalid access error\nbecause Node.js requires file system read access to locate and execute the\npackage. To avoid this:
Using a Globally Installed Package\nGrant read access to the global node_modules directory by running:
npx --node-options=\"--permission --allow-fs-read=$(npm prefix -g)\" package-name\n\nUsing the npx Cache\nIf you are installing the package temporarily or relying on the npx cache,\ngrant read access to the npm cache directory:
npx --node-options=\"--permission --allow-fs-read=$(npm config get cache)\" package-name\n\nAny arguments you would normally pass to node (e.g., --allow-* flags) can\nalso be passed through the --node-options flag. This flexibility makes it\neasy to configure permissions as needed when using npx.
There are constraints you need to know before using this system:
\n--env-file or --openssl-config are designed\nto read files before environment initialization. As a result, such flags are\nnot subject to the rules of the Permission Model. The same applies for V8\nflags that can be set via runtime through v8.setFlagsFromString.node:fs module bypasses the\nPermission Model.The version of the punycode module bundled in Node.js is being deprecated.\nIn a future major version of Node.js this module will be removed. Users\ncurrently depending on the punycode module should switch to using the\nuserland-provided Punycode.js module instead. For punycode-based URL\nencoding, see url.domainToASCII or, more generally, the\nWHATWG URL API.
The punycode module is a bundled version of the Punycode.js module. It\ncan be accessed using:
const punycode = require('node:punycode');\n\nPunycode is a character encoding scheme defined by RFC 3492 that is\nprimarily intended for use in Internationalized Domain Names. Because host\nnames in URLs are limited to ASCII characters only, Domain Names that contain\nnon-ASCII characters must be converted into ASCII using the Punycode scheme.\nFor instance, the Japanese character that translates into the English word,\n'example' is '例'. The Internationalized Domain Name, '例.com' (equivalent\nto 'example.com') is represented by Punycode as the ASCII string\n'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\nmade available to developers as a convenience. Fixes or other modifications to\nthe module must be directed to the Punycode.js project.
The punycode.decode() method converts a Punycode string of ASCII-only\ncharacters to the equivalent string of Unicode codepoints.
punycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n"
},
{
"textRaw": "`punycode.encode(string)`",
"name": "encode",
"type": "method",
"meta": {
"added": [
"v0.5.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`string` {string}",
"name": "string",
"type": "string"
}
]
}
],
"desc": "The punycode.encode() method converts a string of Unicode codepoints to a\nPunycode string of ASCII-only characters.
punycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n"
},
{
"textRaw": "`punycode.toASCII(domain)`",
"name": "toASCII",
"type": "method",
"meta": {
"added": [
"v0.6.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`domain` {string}",
"name": "domain",
"type": "string"
}
]
}
],
"desc": "The punycode.toASCII() method converts a Unicode string representing an\nInternationalized Domain Name to Punycode. Only the non-ASCII parts of the\ndomain name will be converted. Calling punycode.toASCII() on a string that\nalready only contains ASCII characters will have no effect.
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'\npunycode.toASCII('example.com'); // 'example.com'\n"
},
{
"textRaw": "`punycode.toUnicode(domain)`",
"name": "toUnicode",
"type": "method",
"meta": {
"added": [
"v0.6.1"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`domain` {string}",
"name": "domain",
"type": "string"
}
]
}
],
"desc": "The punycode.toUnicode() method converts a string representing a domain name\ncontaining Punycode encoded characters into Unicode. Only the Punycode\nencoded parts of the domain name are be converted.
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'\npunycode.toUnicode('example.com'); // 'example.com'\n"
}
],
"properties": [
{
"textRaw": "`punycode.ucs2`",
"name": "ucs2",
"type": "property",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"methods": [
{
"textRaw": "`punycode.ucs2.decode(string)`",
"name": "decode",
"type": "method",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`string` {string}",
"name": "string",
"type": "string"
}
]
}
],
"desc": "The punycode.ucs2.decode() method returns an array containing the numeric\ncodepoint values of each Unicode symbol in the string.
punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]\n"
},
{
"textRaw": "`punycode.ucs2.encode(codePoints)`",
"name": "encode",
"type": "method",
"meta": {
"added": [
"v0.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`codePoints` {integer[]}",
"name": "codePoints",
"type": "integer[]"
}
]
}
],
"desc": "The punycode.ucs2.encode() method returns a string based on an array of\nnumeric code point values.
punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'\n"
}
]
},
{
"textRaw": "Type: {string}",
"name": "version",
"type": "string",
"meta": {
"added": [
"v0.6.1"
],
"changes": []
},
"desc": "Returns a string identifying the current Punycode.js version number.
" } ], "displayName": "Punycode", "source": "doc/api/punycode.md" }, { "textRaw": "Query string", "name": "query_string", "introduced_in": "v0.1.25", "type": "module", "stability": 2, "stabilityText": "Stable", "desc": "The node:querystring module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:
const querystring = require('node:querystring');\n\nquerystring is more performant than <URLSearchParams> but is not a\nstandardized API. Use <URLSearchParams> when performance is not critical or\nwhen compatibility with browser code is desirable.
The querystring.decode() function is an alias for querystring.parse().
The querystring.encode() function is an alias for querystring.stringify().
The querystring.escape() method performs URL percent-encoding on the given\nstr in a manner that is optimized for the specific requirements of URL\nquery strings.
The querystring.escape() method is used by querystring.stringify() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement percent-encoding implementation if\nnecessary by assigning querystring.escape to an alternative function.
The querystring.parse() method parses a URL query string (str) into a\ncollection of key and value pairs.
For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:
{\n \"foo\": \"bar\",\n \"abc\": [\"xyz\", \"123\"]\n}\n\nThe object returned by the querystring.parse() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
By default, percent-encoded characters within the query string will be assumed\nto use UTF-8 encoding. If an alternative character encoding is used, then an\nalternative decodeURIComponent option will need to be specified:
// Assuming gbkDecodeURIComponent function already exists...\n\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n { decodeURIComponent: gbkDecodeURIComponent });\n"
},
{
"textRaw": "`querystring.stringify(obj[, sep[, eq[, options]]])`",
"name": "stringify",
"type": "method",
"meta": {
"added": [
"v0.1.25"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`obj` {Object} The object to serialize into a URL query string",
"name": "obj",
"type": "Object",
"desc": "The object to serialize into a URL query string"
},
{
"textRaw": "`sep` {string} The substring used to delimit key and value pairs in the query string. **Default:** `'&'`.",
"name": "sep",
"type": "string",
"default": "`'&'`",
"desc": "The substring used to delimit key and value pairs in the query string.",
"optional": true
},
{
"textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. **Default:** `'='`.",
"name": "eq",
"type": "string",
"default": "`'='`",
"desc": ". The substring used to delimit keys and values in the query string.",
"optional": true
},
{
"textRaw": "`options`",
"name": "options",
"options": [
{
"textRaw": "`encodeURIComponent` {Function} The function to use when converting URL-unsafe characters to percent-encoding in the query string. **Default:** `querystring.escape()`.",
"name": "encodeURIComponent",
"type": "Function",
"default": "`querystring.escape()`",
"desc": "The function to use when converting URL-unsafe characters to percent-encoding in the query string."
}
],
"optional": true
}
]
}
],
"desc": "The querystring.stringify() method produces a URL query string from a\ngiven obj by iterating through the object's \"own properties\".
It serializes the following types of values passed in obj:\n<string> | <number> | <bigint> | <boolean> | <string[]> | <number[]> | <bigint[]> | <boolean[]>\nThe numeric values must be finite. Any other input values will be coerced to\nempty strings.
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });\n// Returns 'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');\n// Returns 'foo:bar;baz:qux'\n\nBy default, characters requiring percent-encoding within the query string will\nbe encoded as UTF-8. If an alternative encoding is required, then an alternative\nencodeURIComponent option will need to be specified:
// Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n { encodeURIComponent: gbkEncodeURIComponent });\n"
},
{
"textRaw": "`querystring.unescape(str)`",
"name": "unescape",
"type": "method",
"meta": {
"added": [
"v0.1.25"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`str` {string}",
"name": "str",
"type": "string"
}
]
}
],
"desc": "The querystring.unescape() method performs decoding of URL percent-encoded\ncharacters on the given str.
The querystring.unescape() method is used by querystring.parse() and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement decoding implementation if\nnecessary by assigning querystring.unescape to an alternative function.
By default, the querystring.unescape() method will attempt to use the\nJavaScript built-in decodeURIComponent() method to decode. If that fails,\na safer equivalent that does not throw on malformed URLs will be used.
The node:readline module provides an interface for reading data from a\nReadable stream (such as process.stdin) one line at a time.
To use the promise-based APIs:
\nimport * as readline from 'node:readline/promises';\n\nconst readline = require('node:readline/promises');\n\nTo use the callback and sync APIs:
\nimport * as readline from 'node:readline';\n\nconst readline = require('node:readline');\n\nThe following simple example illustrates the basic use of the node:readline\nmodule.
import * as readline from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\n\nconst rl = readline.createInterface({ input, output });\n\nconst answer = await rl.question('What do you think of Node.js? ');\n\nconsole.log(`Thank you for your valuable feedback: ${answer}`);\n\nrl.close();\n\nconst readline = require('node:readline');\nconst { stdin: input, stdout: output } = require('node:process');\n\nconst rl = readline.createInterface({ input, output });\n\nrl.question('What do you think of Node.js? ', (answer) => {\n // TODO: Log the answer in a database\n console.log(`Thank you for your valuable feedback: ${answer}`);\n\n rl.close();\n});\n\nOnce this code is invoked, the Node.js application will not terminate until the\nreadline.Interface is closed because the interface waits for data to be\nreceived on the input stream.
<EventEmitter>Instances of the InterfaceConstructor class are constructed using the\nreadlinePromises.createInterface() or readline.createInterface() method.\nEvery instance is associated with a single input Readable stream and a\nsingle output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.
The 'close' event is emitted when one of the following occur:
rl.close() method is called and the InterfaceConstructor instance has\nrelinquished control over the input and output streams;input stream receives its 'end' event;input stream receives Ctrl+D to signal\nend-of-transmission (EOT);input stream receives Ctrl+C to signal SIGINT\nand there is no 'SIGINT' event listener registered on the\nInterfaceConstructor instance.The listener function is called without passing any arguments.
\nThe InterfaceConstructor instance is finished once the 'close' event is\nemitted.
The 'error' event is emitted when an error occurs on the input stream\nassociated with the node:readline Interface.
The listener function is called with an Error object passed as the single argument.
The 'line' event is emitted whenever the input stream receives an\nend-of-line input (\\n, \\r, or \\r\\n). This usually occurs when the user\npresses Enter or Return.
The 'line' event is also emitted if new data has been read from a stream and\nthat stream ends without a final end-of-line marker.
The listener function is called with a string containing the single line of\nreceived input.
\nrl.on('line', (input) => {\n console.log(`Received: ${input}`);\n});\n"
},
{
"textRaw": "Event: `'history'`",
"name": "history",
"type": "event",
"meta": {
"added": [
"v15.8.0",
"v14.18.0"
],
"changes": []
},
"params": [],
"desc": "The 'history' event is emitted whenever the history array has changed.
The listener function is called with an array containing the history array.\nIt will reflect all changes, added lines and removed lines due to\nhistorySize and removeHistoryDuplicates.
The primary purpose is to allow a listener to persist the history.\nIt is also possible for the listener to change the history object. This\ncould be useful to prevent certain lines to be added to the history, like\na password.
\nrl.on('history', (history) => {\n console.log(`Received: ${history}`);\n});\n"
},
{
"textRaw": "Event: `'pause'`",
"name": "pause",
"type": "event",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"params": [],
"desc": "The 'pause' event is emitted when one of the following occur:
input stream is paused.input stream is not paused and receives the 'SIGCONT' event. (See\nevents 'SIGTSTP' and 'SIGCONT'.)The listener function is called without passing any arguments.
\nrl.on('pause', () => {\n console.log('Readline paused.');\n});\n"
},
{
"textRaw": "Event: `'resume'`",
"name": "resume",
"type": "event",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"params": [],
"desc": "The 'resume' event is emitted whenever the input stream is resumed.
The listener function is called without passing any arguments.
\nrl.on('resume', () => {\n console.log('Readline resumed.');\n});\n"
},
{
"textRaw": "Event: `'SIGCONT'`",
"name": "SIGCONT",
"type": "event",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"params": [],
"desc": "The 'SIGCONT' event is emitted when a Node.js process previously moved into\nthe background using Ctrl+Z (i.e. SIGTSTP) is then\nbrought back to the foreground using fg(1p).
If the input stream was paused before the SIGTSTP request, this event will\nnot be emitted.
The listener function is invoked without passing any arguments.
\nrl.on('SIGCONT', () => {\n // `prompt` will automatically resume the stream\n rl.prompt();\n});\n\nThe 'SIGCONT' event is not supported on Windows.
The 'SIGINT' event is emitted whenever the input stream receives\na Ctrl+C input, known typically as SIGINT. If there are no\n'SIGINT' event listeners registered when the input stream receives a\nSIGINT, the 'pause' event will be emitted.
The listener function is invoked without passing any arguments.
\nrl.on('SIGINT', () => {\n rl.question('Are you sure you want to exit? ', (answer) => {\n if (answer.match(/^y(es)?$/i)) rl.pause();\n });\n});\n"
},
{
"textRaw": "Event: `'SIGTSTP'`",
"name": "SIGTSTP",
"type": "event",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"params": [],
"desc": "The 'SIGTSTP' event is emitted when the input stream receives\na Ctrl+Z input, typically known as SIGTSTP. If there are\nno 'SIGTSTP' event listeners registered when the input stream receives a\nSIGTSTP, the Node.js process will be sent to the background.
When the program is resumed using fg(1p), the 'pause' and 'SIGCONT' events\nwill be emitted. These can be used to resume the input stream.
The 'pause' and 'SIGCONT' events will not be emitted if the input was\npaused before the process was sent to the background.
The listener function is invoked without passing any arguments.
\nrl.on('SIGTSTP', () => {\n // This will override SIGTSTP and prevent the program from going to the\n // background.\n console.log('Caught SIGTSTP.');\n});\n\nThe 'SIGTSTP' event is not supported on Windows.
The rl.close() method closes the InterfaceConstructor instance and\nrelinquishes control over the input and output streams. When called,\nthe 'close' event will be emitted.
Calling rl.close() does not immediately stop other events (including 'line')\nfrom being emitted by the InterfaceConstructor instance.
Alias for rl.close().
The rl.pause() method pauses the input stream, allowing it to be resumed\nlater if necessary.
Calling rl.pause() does not immediately pause other events (including\n'line') from being emitted by the InterfaceConstructor instance.
The rl.prompt() method writes the InterfaceConstructor instances configured\nprompt to a new line in output in order to provide a user with a new\nlocation at which to provide input.
When called, rl.prompt() will resume the input stream if it has been\npaused.
If the InterfaceConstructor was created with output set to null or\nundefined the prompt is not written.
The rl.resume() method resumes the input stream if it has been paused.
The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.
The rl.getPrompt() method returns the current prompt used by rl.prompt().
The rl.write() method will write either data or a key sequence identified\nby key to the output. The key argument is supported only if output is\na TTY text terminal. See TTY keybindings for a list of key\ncombinations.
If key is specified, data is ignored.
When called, rl.write() will resume the input stream if it has been\npaused.
If the InterfaceConstructor was created with output set to null or\nundefined the data and key are not written.
rl.write('Delete this!');\n// Simulate Ctrl+U to delete the line written previously\nrl.write(null, { ctrl: true, name: 'u' });\n\nThe rl.write() method will write the data to the readline Interface's\ninput as if it were provided by the user.
Create an AsyncIterator object that iterates through each line in the input\nstream as a string. This method allows asynchronous iteration of\nInterfaceConstructor objects through for await...of loops.
Errors in the input stream are not forwarded.
\nIf the loop is terminated with break, throw, or return,\nrl.close() will be called. In other words, iterating over a\nInterfaceConstructor will always consume the input stream fully.
Performance is not on par with the traditional 'line' event API. Use 'line'\ninstead for performance-sensitive applications.
async function processLineByLine() {\n const rl = readline.createInterface({\n // ...\n });\n\n for await (const line of rl) {\n // Each line in the readline input will be successively available here as\n // `line`.\n }\n}\n\nreadline.createInterface() will start to consume the input stream once\ninvoked. Having asynchronous operations between interface creation and\nasynchronous iteration may result in missed lines.
Returns the real position of the cursor in relation to the input\nprompt + string. Long input (wrapping) strings, as well as multiple\nline prompts are included in the calculations.
" } ], "properties": [ { "textRaw": "Type: {string}", "name": "line", "type": "string", "meta": { "added": [ "v0.1.98" ], "changes": [ { "version": [ "v15.8.0", "v14.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/33676", "description": "Value will always be a string, never undefined." } ] }, "desc": "The current input data being processed by node.
\nThis can be used when collecting input from a TTY stream to retrieve the\ncurrent value that has been processed thus far, prior to the line event\nbeing emitted. Once the line event has been emitted, this property will\nbe an empty string.
Be aware that modifying the value during the instance runtime may have\nunintended consequences if rl.cursor is not also controlled.
If not using a TTY stream for input, use the 'line' event.
One possible use case would be as follows:
\nconst values = ['lorem ipsum', 'dolor sit amet'];\nconst rl = readline.createInterface(process.stdin);\nconst showResults = debounce(() => {\n console.log(\n '\\n',\n values.filter((val) => val.startsWith(rl.line)).join(' '),\n );\n}, 300);\nprocess.stdin.on('keypress', (c, k) => {\n showResults();\n});\n"
},
{
"textRaw": "Type: {number|undefined}",
"name": "cursor",
"type": "number|undefined",
"meta": {
"added": [
"v0.1.98"
],
"changes": []
},
"desc": "The cursor position relative to rl.line.
This will track where the current cursor lands in the input string, when\nreading input from a TTY stream. The position of cursor determines the\nportion of the input string that will be modified as input is processed,\nas well as the column where the terminal caret will be rendered.
" } ] } ], "modules": [ { "textRaw": "Promises API", "name": "promises_api", "type": "module", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "classes": [ { "textRaw": "Class: `readlinePromises.Interface`", "name": "readlinePromises.Interface", "type": "class", "meta": { "added": [ "v17.0.0" ], "changes": [] }, "desc": "<readline.InterfaceConstructor>Instances of the readlinePromises.Interface class are constructed using the\nreadlinePromises.createInterface() method. Every instance is associated with a\nsingle input Readable stream and a single output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.
The rl.question() method displays the query by writing it to the output,\nwaits for user input to be provided on input, then invokes the callback\nfunction passing the provided input as the first argument.
When called, rl.question() will resume the input stream if it has been\npaused.
If the readlinePromises.Interface was created with output set to null or\nundefined the query is not written.
If the question is called after rl.close(), it returns a rejected promise.
Example usage:
\nconst answer = await rl.question('What is your favorite food? ');\nconsole.log(`Oh, so your favorite food is ${answer}`);\n\nUsing an AbortSignal to cancel a question.
const signal = AbortSignal.timeout(10_000);\n\nsignal.addEventListener('abort', () => {\n console.log('The food question timed out');\n}, { once: true });\n\nconst answer = await rl.question('What is your favorite food? ', { signal });\nconsole.log(`Oh, so your favorite food is ${answer}`);\n"
}
]
},
{
"textRaw": "Class: `readlinePromises.Readline`",
"name": "readlinePromises.Readline",
"type": "class",
"meta": {
"added": [
"v17.0.0"
],
"changes": []
},
"signatures": [
{
"textRaw": "`new readlinePromises.Readline(stream[, options])`",
"name": "readlinePromises.Readline",
"type": "ctor",
"meta": {
"added": [
"v17.0.0"
],
"changes": []
},
"params": [
{
"textRaw": "`stream` {stream.Writable} A TTY stream.",
"name": "stream",
"type": "stream.Writable",
"desc": "A TTY stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`autoCommit` {boolean} If `true`, no need to call `rl.commit()`.",
"name": "autoCommit",
"type": "boolean",
"desc": "If `true`, no need to call `rl.commit()`."
}
],
"optional": true
}
]
}
],
"methods": [
{
"textRaw": "`rl.clearLine(dir)`",
"name": "clearLine",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`dir` {integer}",
"name": "dir",
"type": "integer",
"options": [
{
"textRaw": "`-1`: to the left from cursor",
"name": "-1",
"desc": "to the left from cursor"
},
{
"textRaw": "`1`: to the right from cursor",
"name": "1",
"desc": "to the right from cursor"
},
{
"textRaw": "`0`: the entire line",
"name": "0",
"desc": "the entire line"
}
]
}
],
"return": {
"textRaw": "Returns: this",
"name": "return",
"desc": "this"
}
}
],
"desc": "The rl.clearLine() method adds to the internal list of pending action an\naction that clears current line of the associated stream in a specified\ndirection identified by dir.\nCall rl.commit() to see the effect of this method, unless autoCommit: true\nwas passed to the constructor.
The rl.clearScreenDown() method adds to the internal list of pending action an\naction that clears the associated stream from the current position of the\ncursor down.\nCall rl.commit() to see the effect of this method, unless autoCommit: true\nwas passed to the constructor.
The rl.commit() method sends all the pending actions to the associated\nstream and clears the internal list of pending actions.
The rl.cursorTo() method adds to the internal list of pending action an action\nthat moves cursor to the specified position in the associated stream.\nCall rl.commit() to see the effect of this method, unless autoCommit: true\nwas passed to the constructor.
The rl.moveCursor() method adds to the internal list of pending action an\naction that moves the cursor relative to its current position in the\nassociated stream.\nCall rl.commit() to see the effect of this method, unless autoCommit: true\nwas passed to the constructor.
The rl.rollback methods clears the internal list of pending actions without\nsending it to the associated stream.
The readlinePromises.createInterface() method creates a new readlinePromises.Interface\ninstance.
import { createInterface } from 'node:readline/promises';\nimport { stdin, stdout } from 'node:process';\nconst rl = createInterface({\n input: stdin,\n output: stdout,\n});\n\nconst { createInterface } = require('node:readline/promises');\nconst rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nOnce the readlinePromises.Interface instance is created, the most common case\nis to listen for the 'line' event:
rl.on('line', (line) => {\n console.log(`Received: ${line}`);\n});\n\nIf terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property and emits\na 'resize' event on the output if or when the columns ever change\n(process.stdout does this automatically when it is a TTY).
The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:
Array with matching entries for the completion.For instance: [[substr1, substr2, ...], originalsubstring].
function completer(line) {\n const completions = '.help .error .exit .quit .q'.split(' ');\n const hits = completions.filter((c) => c.startsWith(line));\n // Show all completions if none found\n return [hits.length ? hits : completions, line];\n}\n\nThe completer function can also return a <Promise>, or be asynchronous:
async function completer(linePartial) {\n await someAsyncWork();\n return [['123'], linePartial];\n}\n",
"displayName": "Use of the `completer` function"
}
]
}
],
"displayName": "Promises API"
},
{
"textRaw": "Callback API",
"name": "callback_api",
"type": "module",
"meta": {
"added": [
"v0.1.104"
],
"changes": []
},
"classes": [
{
"textRaw": "Class: `readline.Interface`",
"name": "readline.Interface",
"type": "class",
"meta": {
"added": [
"v0.1.104"
],
"changes": [
{
"version": "v17.0.0",
"pr-url": "https://github.com/nodejs/node/pull/37947",
"description": "The class `readline.Interface` now inherits from `Interface`."
}
]
},
"desc": "<readline.InterfaceConstructor>Instances of the readline.Interface class are constructed using the\nreadline.createInterface() method. Every instance is associated with a\nsingle input Readable stream and a single output Writable stream.\nThe output stream is used to print prompts for user input that arrives on,\nand is read from, the input stream.
The rl.question() method displays the query by writing it to the output,\nwaits for user input to be provided on input, then invokes the callback\nfunction passing the provided input as the first argument.
When called, rl.question() will resume the input stream if it has been\npaused.
If the readline.Interface was created with output set to null or\nundefined the query is not written.
The callback function passed to rl.question() does not follow the typical\npattern of accepting an Error object or null as the first argument.\nThe callback is called with the provided answer as the only argument.
An error will be thrown if calling rl.question() after rl.close().
Example usage:
\nrl.question('What is your favorite food? ', (answer) => {\n console.log(`Oh, so your favorite food is ${answer}`);\n});\n\nUsing an AbortController to cancel a question.
const ac = new AbortController();\nconst signal = ac.signal;\n\nrl.question('What is your favorite food? ', { signal }, (answer) => {\n console.log(`Oh, so your favorite food is ${answer}`);\n});\n\nsignal.addEventListener('abort', () => {\n console.log('The food question timed out');\n}, { once: true });\n\nsetTimeout(() => ac.abort(), 10000);\n"
}
]
}
],
"methods": [
{
"textRaw": "`readline.clearLine(stream, dir[, callback])`",
"name": "clearLine",
"type": "method",
"meta": {
"added": [
"v0.7.7"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v12.7.0",
"pr-url": "https://github.com/nodejs/node/pull/28674",
"description": "The stream's write() callback and return value are exposed."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {stream.Writable}",
"name": "stream",
"type": "stream.Writable"
},
{
"textRaw": "`dir` {number}",
"name": "dir",
"type": "number",
"options": [
{
"textRaw": "`-1`: to the left from cursor",
"name": "-1",
"desc": "to the left from cursor"
},
{
"textRaw": "`1`: to the right from cursor",
"name": "1",
"desc": "to the right from cursor"
},
{
"textRaw": "`0`: the entire line",
"name": "0",
"desc": "the entire line"
}
]
},
{
"textRaw": "`callback` {Function} Invoked once the operation completes.",
"name": "callback",
"type": "Function",
"desc": "Invoked once the operation completes.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.",
"name": "return",
"type": "boolean",
"desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`."
}
}
],
"desc": "The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.
The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.
The readline.createInterface() method creates a new readline.Interface\ninstance.
import { createInterface } from 'node:readline';\nimport { stdin, stdout } from 'node:process';\nconst rl = createInterface({\n input: stdin,\n output: stdout,\n});\n\nconst { createInterface } = require('node:readline');\nconst rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n});\n\nOnce the readline.Interface instance is created, the most common case is to\nlisten for the 'line' event:
rl.on('line', (line) => {\n console.log(`Received: ${line}`);\n});\n\nIf terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property and emits\na 'resize' event on the output if or when the columns ever change\n(process.stdout does this automatically when it is a TTY).
When creating a readline.Interface using stdin as input, the program\nwill not terminate until it receives an EOF character. To exit without\nwaiting for user input, call process.stdin.unref().
The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:
Array with matching entries for the completion.For instance: [[substr1, substr2, ...], originalsubstring].
function completer(line) {\n const completions = '.help .error .exit .quit .q'.split(' ');\n const hits = completions.filter((c) => c.startsWith(line));\n // Show all completions if none found\n return [hits.length ? hits : completions, line];\n}\n\nThe completer function can be called asynchronously if it accepts two\narguments:
function completer(linePartial, callback) {\n callback(null, [['123'], linePartial]);\n}\n",
"displayName": "Use of the `completer` function"
}
]
},
{
"textRaw": "`readline.cursorTo(stream, x[, y][, callback])`",
"name": "cursorTo",
"type": "method",
"meta": {
"added": [
"v0.7.7"
],
"changes": [
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v12.7.0",
"pr-url": "https://github.com/nodejs/node/pull/28674",
"description": "The stream's write() callback and return value are exposed."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {stream.Writable}",
"name": "stream",
"type": "stream.Writable"
},
{
"textRaw": "`x` {number}",
"name": "x",
"type": "number"
},
{
"textRaw": "`y` {number}",
"name": "y",
"type": "number",
"optional": true
},
{
"textRaw": "`callback` {Function} Invoked once the operation completes.",
"name": "callback",
"type": "Function",
"desc": "Invoked once the operation completes.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {boolean} `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.",
"name": "return",
"type": "boolean",
"desc": "`false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`."
}
}
],
"desc": "The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.
The readline.moveCursor() method moves the cursor relative to its current\nposition in a given TTY stream.
The following example illustrates the use of readline.Interface class to\nimplement a small command-line interface:
import { createInterface } from 'node:readline';\nimport { exit, stdin, stdout } from 'node:process';\nconst rl = createInterface({\n input: stdin,\n output: stdout,\n prompt: 'OHAI> ',\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n switch (line.trim()) {\n case 'hello':\n console.log('world!');\n break;\n default:\n console.log(`Say what? I might have heard '${line.trim()}'`);\n break;\n }\n rl.prompt();\n}).on('close', () => {\n console.log('Have a great day!');\n exit(0);\n});\n\nconst { createInterface } = require('node:readline');\nconst rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n prompt: 'OHAI> ',\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n switch (line.trim()) {\n case 'hello':\n console.log('world!');\n break;\n default:\n console.log(`Say what? I might have heard '${line.trim()}'`);\n break;\n }\n rl.prompt();\n}).on('close', () => {\n console.log('Have a great day!');\n process.exit(0);\n});\n",
"displayName": "Example: Tiny CLI"
},
{
"textRaw": "Example: Read file stream line-by-Line",
"name": "example:_read_file_stream_line-by-line",
"type": "module",
"desc": "A common use case for readline is to consume an input file one line at a\ntime. The easiest way to do so is leveraging the fs.ReadStream API as\nwell as a for await...of loop:
import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\n\nasync function processLineByLine() {\n const fileStream = createReadStream('input.txt');\n\n const rl = createInterface({\n input: fileStream,\n crlfDelay: Infinity,\n });\n // Note: we use the crlfDelay option to recognize all instances of CR LF\n // ('\\r\\n') in input.txt as a single line break.\n\n for await (const line of rl) {\n // Each line in input.txt will be successively available here as `line`.\n console.log(`Line from file: ${line}`);\n }\n}\n\nprocessLineByLine();\n\nconst { createReadStream } = require('node:fs');\nconst { createInterface } = require('node:readline');\n\nasync function processLineByLine() {\n const fileStream = createReadStream('input.txt');\n\n const rl = createInterface({\n input: fileStream,\n crlfDelay: Infinity,\n });\n // Note: we use the crlfDelay option to recognize all instances of CR LF\n // ('\\r\\n') in input.txt as a single line break.\n\n for await (const line of rl) {\n // Each line in input.txt will be successively available here as `line`.\n console.log(`Line from file: ${line}`);\n }\n}\n\nprocessLineByLine();\n\nAlternatively, one could use the 'line' event:
import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\n\nconst rl = createInterface({\n input: createReadStream('sample.txt'),\n crlfDelay: Infinity,\n});\n\nrl.on('line', (line) => {\n console.log(`Line from file: ${line}`);\n});\n\nconst { createReadStream } = require('node:fs');\nconst { createInterface } = require('node:readline');\n\nconst rl = createInterface({\n input: createReadStream('sample.txt'),\n crlfDelay: Infinity,\n});\n\nrl.on('line', (line) => {\n console.log(`Line from file: ${line}`);\n});\n\nCurrently, for await...of loop can be a bit slower. If async / await\nflow and speed are both essential, a mixed approach can be applied:
import { once } from 'node:events';\nimport { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\n\n(async function processLineByLine() {\n try {\n const rl = createInterface({\n input: createReadStream('big-file.txt'),\n crlfDelay: Infinity,\n });\n\n rl.on('line', (line) => {\n // Process the line.\n });\n\n await once(rl, 'close');\n\n console.log('File processed.');\n } catch (err) {\n console.error(err);\n }\n})();\n\nconst { once } = require('node:events');\nconst { createReadStream } = require('node:fs');\nconst { createInterface } = require('node:readline');\n\n(async function processLineByLine() {\n try {\n const rl = createInterface({\n input: createReadStream('big-file.txt'),\n crlfDelay: Infinity,\n });\n\n rl.on('line', (line) => {\n // Process the line.\n });\n\n await once(rl, 'close');\n\n console.log('File processed.');\n } catch (err) {\n console.error(err);\n }\n})();\n",
"displayName": "Example: Read file stream line-by-Line"
},
{
"textRaw": "TTY keybindings",
"name": "tty_keybindings",
"type": "module",
"desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Keybindings | Description | Notes |
|---|---|---|
| Ctrl+Shift+Backspace | Delete line left | Doesn't work on Linux, Mac and Windows |
| Ctrl+Shift+Delete | Delete line right | Doesn't work on Mac |
| Ctrl+C | Emit SIGINT or close the readline instance | |
| Ctrl+H | Delete left | |
| Ctrl+D | Delete right or close the readline instance in case the current line is empty / EOF | Doesn't work on Windows |
| Ctrl+U | Delete from the current position to the line start | |
| Ctrl+K | Delete from the current position to the end of line | |
| Ctrl+Y | Yank (Recall) the previously deleted text | Only works with text deleted by Ctrl+U or Ctrl+K |
| Meta+Y | Cycle among previously deleted texts | Only available when the last keystroke is Ctrl+Y or Meta+Y |
| Ctrl+A | Go to start of line | |
| Ctrl+E | Go to end of line | |
| Ctrl+B | Back one character | |
| Ctrl+F | Forward one character | |
| Ctrl+L | Clear screen | |
| Ctrl+N | Next history item | |
| Ctrl+P | Previous history item | |
| Ctrl+- | Undo previous change | Any keystroke that emits key code 0x1F will do this action.\n In many terminals, for example xterm,\n this is bound to Ctrl+-. |
| Ctrl+6 | Redo previous change | Many terminals don't have a default redo keystroke.\n We choose key code 0x1E to perform redo.\n In xterm, it is bound to Ctrl+6\n by default. |
| Ctrl+Z | Moves running process into background. Type\n fg and press Enter\n to return. | Doesn't work on Windows |
| Ctrl+W or Ctrl\n +Backspace | Delete backward to a word boundary | Ctrl+Backspace Doesn't\n work on Linux, Mac and Windows |
| Ctrl+Delete | Delete forward to a word boundary | Doesn't work on Mac |
| Ctrl+Left arrow or\n Meta+B | Word left | Ctrl+Left arrow Doesn't work\n on Mac |
| Ctrl+Right arrow or\n Meta+F | Word right | Ctrl+Right arrow Doesn't work\n on Mac |
| Meta+D or Meta\n +Delete | Delete word right | Meta+Delete Doesn't work\n on windows |
| Meta+Backspace | Delete word left | Doesn't work on Mac |
The readline.emitKeypressEvents() method causes the given Readable\nstream to begin emitting 'keypress' events corresponding to received input.
Optionally, interface specifies a readline.Interface instance for which\nautocompletion 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\ninput is a terminal. Closing the readline instance does not stop\nthe input from emitting 'keypress' events.
readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n process.stdin.setRawMode(true);\n"
}
],
"displayName": "Readline",
"source": "doc/api/readline.md"
},
{
"textRaw": "REPL",
"name": "repl",
"introduced_in": "v0.10.0",
"type": "module",
"stability": 2,
"stabilityText": "Stable",
"desc": "The node:repl module provides a Read-Eval-Print-Loop (REPL) implementation\nthat is available both as a standalone program or includible in other\napplications. It can be accessed using:
import repl from 'node:repl';\n\nconst repl = require('node:repl');\n",
"modules": [
{
"textRaw": "Design and features",
"name": "design_and_features",
"type": "module",
"desc": "The node:repl module exports the repl.REPLServer class. While running,\ninstances of repl.REPLServer will accept individual lines of user input,\nevaluate those according to a user-defined evaluation function, then output the\nresult. Input and output may be from stdin and stdout, respectively, or may\nbe connected to any Node.js stream.
Instances of repl.REPLServer support automatic completion of inputs,\ncompletion preview, simplistic Emacs-style line editing, multi-line inputs,\nZSH-like reverse-i-search, ZSH-like substring-based history search,\nANSI-styled output, saving and restoring current REPL session state, error\nrecovery, and customizable evaluation functions. Terminals that do not support\nANSI styles and Emacs-style line editing automatically fall back to a limited\nfeature set.
The following special commands are supported by all REPL instances:
\n.break: When in the process of inputting a multi-line expression, enter\nthe .break command (or press Ctrl+C) to abort\nfurther input or processing of that expression..clear: Resets the REPL context to an empty object and clears any\nmulti-line expression being input..exit: Close the I/O stream, causing the REPL to exit..help: Show this list of special commands..save: Save the current REPL session to a file:\n> .save ./file/to/save.js.load: Load a file into the current REPL session.\n> .load ./file/to/load.js.editor: Enter editor mode (Ctrl+D to\nfinish, Ctrl+C to cancel).> .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n\nThe following key combinations in the REPL have these special effects:
\n.break command.\nWhen pressed twice on a blank line, has the same effect as the .exit\ncommand..exit command.For key bindings related to the reverse-i-search, see reverse-i-search.\nFor all other key bindings, see TTY keybindings.
By default, all instances of repl.REPLServer use an evaluation function\nthat evaluates JavaScript expressions and provides access to Node.js built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the repl.REPLServer instance is created.
The default evaluator supports direct evaluation of JavaScript expressions:
\n> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n\nUnless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const, let, or var keywords\nare declared at the global scope.
The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the context object associated with each REPLServer:
import repl from 'node:repl';\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n\nconst repl = require('node:repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n\nProperties in the context object appear as local within the REPL:
$ node repl_test.js\n> m\n'message'\n\nContext properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty():
import repl from 'node:repl';\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n configurable: false,\n enumerable: true,\n value: msg,\n});\n\nconst repl = require('node:repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n configurable: false,\n enumerable: true,\n value: msg,\n});\n",
"displayName": "Global and local scope"
},
{
"textRaw": "Accessing core Node.js modules",
"name": "accessing_core_node.js_modules",
"type": "module",
"desc": "The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input fs will be evaluated on-demand as\nglobal.fs = require('node:fs').
> fs.createReadStream('./some/file');\n",
"displayName": "Accessing core Node.js modules"
},
{
"textRaw": "Global uncaught exceptions",
"name": "global_uncaught_exceptions",
"type": "module",
"meta": {
"changes": [
{
"version": "v12.3.0",
"pr-url": "https://github.com/nodejs/node/pull/27151",
"description": "The `'uncaughtException'` event is from now on triggered if the repl is used as standalone program."
}
]
},
"desc": "The REPL uses the domain module to catch all uncaught exceptions for that\nREPL session.
This use of the domain module in the REPL has these side effects:
Uncaught exceptions only emit the 'uncaughtException' event in the\nstandalone REPL. Adding a listener for this event in a REPL within\nanother Node.js program results in ERR_INVALID_REPL_INPUT.
const r = repl.start();\n\nr.write('process.on(\"uncaughtException\", () => console.log(\"Foobar\"));\\n');\n// Output stream includes:\n// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`\n// cannot be used in the REPL\n\nr.close();\n\nTrying to use process.setUncaughtExceptionCaptureCallback() throws\nan ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE error.
The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _ (underscore).\nExplicitly setting _ to a value will disable this behavior.
> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n\nSimilarly, _error will refer to the last seen error, if there was any.\nExplicitly setting _error to a value will disable this behavior.
> throw new Error('foo');\nUncaught Error: foo\n> _error.message\n'foo'\n",
"displayName": "Assignment of the `_` (underscore) variable"
},
{
"textRaw": "`await` keyword",
"name": "`await`_keyword",
"type": "module",
"desc": "Support for the await keyword is enabled at the top level.
> await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nUncaught Error: REPL await\n at REPL2:1:54\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n\nOne known limitation of using the await keyword in the REPL is that\nit will invalidate the lexical scoping of the const keywords.
For example:
\n> const m = await Promise.resolve(123)\nundefined\n> m\n123\n> m = await Promise.resolve(234)\n234\n// redeclaring the constant does error\n> const m = await Promise.resolve(345)\nUncaught SyntaxError: Identifier 'm' has already been declared\n\n--no-experimental-repl-await shall disable top-level await in REPL.
The REPL supports bi-directional reverse-i-search similar to ZSH. It is\ntriggered with Ctrl+R to search backward\nand Ctrl+S to search forwards.
\nDuplicated history entries will be skipped.
\nEntries are accepted as soon as any key is pressed that doesn't correspond\nwith the reverse search. Cancelling is possible by pressing Esc\nor Ctrl+C.
\nChanging the direction immediately searches for the next entry in the expected\ndirection from the current position on.
", "displayName": "Reverse-i-search" }, { "textRaw": "Custom evaluation functions", "name": "custom_evaluation_functions", "type": "module", "desc": "When a new repl.REPLServer is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.
An evaluation function accepts the following four arguments:
\ncode <string> The code to be executed (e.g. 1 + 1).context <Object> The context in which the code is executed. This can either be the JavaScript global\ncontext or a context specific to the REPL instance, depending on the useGlobal option.replResourceName <string> An identifier for the REPL resource associated with the current code\nevaluation. This can be useful for debugging purposes.callback <Function> A function to invoke once the code evaluation is complete. The callback takes two parameters:\nnull/undefined if no error occurred.The following illustrates an example of a REPL that squares a given number, an error is instead printed\nif the provided input is not actually a number:
\nimport repl from 'node:repl';\n\nfunction byThePowerOfTwo(number) {\n return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n if (isNaN(code)) {\n callback(new Error(`${code.trim()} is not a number`));\n } else {\n callback(null, byThePowerOfTwo(code));\n }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });\n\nconst repl = require('node:repl');\n\nfunction byThePowerOfTwo(number) {\n return number * number;\n}\n\nfunction myEval(code, context, replResourceName, callback) {\n if (isNaN(code)) {\n callback(new Error(`${code.trim()} is not a number`));\n } else {\n callback(null, byThePowerOfTwo(code));\n }\n}\n\nrepl.start({ prompt: 'Enter a number: ', eval: myEval });\n",
"modules": [
{
"textRaw": "Recoverable errors",
"name": "recoverable_errors",
"type": "module",
"desc": "At the REPL prompt, pressing Enter sends the current line of input to\nthe eval function. In order to support multi-line input, the eval function\ncan return an instance of repl.Recoverable to the provided callback function:
function myEval(cmd, context, filename, callback) {\n let result;\n try {\n result = vm.runInThisContext(cmd);\n } catch (e) {\n if (isRecoverableError(e)) {\n return callback(new repl.Recoverable(e));\n }\n }\n callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n if (error.name === 'SyntaxError') {\n return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n }\n return false;\n}\n",
"displayName": "Recoverable errors"
}
],
"displayName": "Custom evaluation functions"
},
{
"textRaw": "Customizing REPL output",
"name": "customizing_repl_output",
"type": "module",
"desc": "By default, repl.REPLServer instances format output using the\nutil.inspect() method before writing the output to the provided Writable\nstream (process.stdout by default). The showProxy inspection option is set\nto true by default and the colors option is set to true depending on the\nREPL's useColors option.
The useColors boolean option can be specified at construction to instruct the\ndefault writer to use ANSI style codes to colorize the output from the\nutil.inspect() method.
If the REPL is run as standalone program, it is also possible to change the\nREPL's inspection defaults from inside the REPL by using the\ninspect.replDefaults property which mirrors the defaultOptions from\nutil.inspect().
> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n 1\n]\n>\n\nTo fully customize the output of a repl.REPLServer instance pass in a new\nfunction for the writer option on construction. The following example, for\ninstance, simply converts any input text to upper case:
import repl from 'node:repl';\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, cmd);\n}\n\nfunction myWriter(output) {\n return output.toUpperCase();\n}\n\nconst repl = require('node:repl');\n\nconst r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, cmd);\n}\n\nfunction myWriter(output) {\n return output.toUpperCase();\n}\n",
"displayName": "Customizing REPL output"
}
],
"displayName": "Design and features"
},
{
"textRaw": "The Node.js REPL",
"name": "the_node.js_repl",
"type": "module",
"desc": "Node.js itself uses the node:repl module to provide its own interactive\ninterface for executing JavaScript. This can be used by executing the Node.js\nbinary without passing any arguments (or by passing the -i argument):
$ node\n> const a = [1, 2, 3];\nundefined\n> a\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n... console.log(v);\n... });\n1\n2\n3\n",
"modules": [
{
"textRaw": "Environment variable options",
"name": "environment_variable_options",
"type": "module",
"desc": "Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:
\nNODE_REPL_HISTORY: When a valid path is given, persistent REPL history\nwill be saved to the specified file rather than .node_repl_history in the\nuser's home directory. Setting this value to '' (an empty string) will\ndisable persistent REPL history. Whitespace will be trimmed from the value.\nOn Windows platforms environment variables with empty values are invalid so\nset this variable to one or more spaces to disable persistent REPL history.NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be\npersisted if history is available. Must be a positive number.\nDefault: 1000.NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default:\n'sloppy', which will allow non-strict mode code to be run.By default, the Node.js REPL will persist history between node REPL sessions\nby saving inputs to a .node_repl_history file located in the user's home\ndirectory. This can be disabled by setting the environment variable\nNODE_REPL_HISTORY=''.
For advanced line-editors, start Node.js with the environment variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings, which will allow use with rlwrap.
For example, the following can be added to a .bashrc file:
alias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n",
"displayName": "Using the Node.js REPL with advanced line-editors"
},
{
"textRaw": "Starting multiple REPL instances in the same process",
"name": "starting_multiple_repl_instances_in_the_same_process",
"type": "module",
"desc": "It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single global object (by setting\nthe useGlobal option to true) but have separate I/O interfaces.
The following example, for instance, provides separate REPLs on stdin, a Unix\nsocket, and a TCP socket, all sharing the same global object:
import net from 'node:net';\nimport repl from 'node:repl';\nimport process from 'node:process';\nimport fs from 'node:fs';\n\nlet connections = 0;\n\nrepl.start({\n prompt: 'Node.js via stdin> ',\n useGlobal: true,\n input: process.stdin,\n output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via Unix socket> ',\n useGlobal: true,\n input: socket,\n output: socket,\n }).on('exit', () => {\n socket.end();\n });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via TCP socket> ',\n useGlobal: true,\n input: socket,\n output: socket,\n }).on('exit', () => {\n socket.end();\n });\n}).listen(5001);\n\nconst net = require('node:net');\nconst repl = require('node:repl');\nconst fs = require('node:fs');\n\nlet connections = 0;\n\nrepl.start({\n prompt: 'Node.js via stdin> ',\n useGlobal: true,\n input: process.stdin,\n output: process.stdout,\n});\n\nconst unixSocketPath = '/tmp/node-repl-sock';\n\n// If the socket file already exists let's remove it\nfs.rmSync(unixSocketPath, { force: true });\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via Unix socket> ',\n useGlobal: true,\n input: socket,\n output: socket,\n }).on('exit', () => {\n socket.end();\n });\n}).listen(unixSocketPath);\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via TCP socket> ',\n useGlobal: true,\n input: socket,\n output: socket,\n }).on('exit', () => {\n socket.end();\n });\n}).listen(5001);\n\nRunning this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. telnet,\nfor instance, is useful for connecting to TCP sockets, while socat can be used\nto connect to both Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.
", "displayName": "Starting multiple REPL instances in the same process" }, { "textRaw": "Examples", "name": "examples", "type": "module", "modules": [ { "textRaw": "Full-featured \"terminal\" REPL over `net.Server` and `net.Socket`", "name": "full-featured_\"terminal\"_repl_over_`net.server`_and_`net.socket`", "type": "module", "desc": "This is an example on how to run a \"full-featured\" (terminal) REPL using\nnet.Server and net.Socket
The following script starts an HTTP server on port 1337 that allows\nclients to establish socket connections to its REPL instance.
// repl-server.js\nimport repl from 'node:repl';\nimport net from 'node:net';\n\nnet\n .createServer((socket) => {\n const r = repl.start({\n prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n input: socket,\n output: socket,\n terminal: true,\n useGlobal: false,\n });\n r.on('exit', () => {\n socket.end();\n });\n r.context.socket = socket;\n })\n .listen(1337);\n\n// repl-server.js\nconst repl = require('node:repl');\nconst net = require('node:net');\n\nnet\n .createServer((socket) => {\n const r = repl.start({\n prompt: `socket ${socket.remoteAddress}:${socket.remotePort}> `,\n input: socket,\n output: socket,\n terminal: true,\n useGlobal: false,\n });\n r.on('exit', () => {\n socket.end();\n });\n r.context.socket = socket;\n })\n .listen(1337);\n\nWhile the following implements a client that can create a socket connection\nwith the above defined server over port 1337.
// repl-client.js\nimport net from 'node:net';\nimport process from 'node:process';\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n process.stdin.resume();\n process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n process.stdin.setRawMode(false);\n process.stdin.pause();\n sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n sock.destroy();\n console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n if (b.length === 1 && b[0] === 4) {\n process.stdin.emit('end');\n }\n});\n\n// repl-client.js\nconst net = require('node:net');\n\nconst sock = net.connect(1337);\n\nprocess.stdin.pipe(sock);\nsock.pipe(process.stdout);\n\nsock.on('connect', () => {\n process.stdin.resume();\n process.stdin.setRawMode(true);\n});\n\nsock.on('close', () => {\n process.stdin.setRawMode(false);\n process.stdin.pause();\n sock.removeListener('close', done);\n});\n\nprocess.stdin.on('end', () => {\n sock.destroy();\n console.log();\n});\n\nprocess.stdin.on('data', (b) => {\n if (b.length === 1 && b[0] === 4) {\n process.stdin.emit('end');\n }\n});\n\nTo run the example open two different terminals on your machine, start the server\nwith node repl-server.js in one terminal and node repl-client.js on the other.
Original code from https://gist.github.com/TooTallNate/2209310.
", "displayName": "Full-featured \"terminal\" REPL over `net.Server` and `net.Socket`" }, { "textRaw": "REPL over `curl`", "name": "repl_over_`curl`", "type": "module", "desc": "This is an example on how to run a REPL instance over curl()
The following script starts an HTTP server on port 8000 that can accept\na connection established via curl().
import http from 'node:http';\nimport repl from 'node:repl';\n\nconst server = http.createServer((req, res) => {\n res.setHeader('content-type', 'multipart/octet-stream');\n\n repl.start({\n prompt: 'curl repl> ',\n input: req,\n output: res,\n terminal: false,\n useColors: true,\n useGlobal: false,\n });\n});\n\nserver.listen(8000);\n\nconst http = require('node:http');\nconst repl = require('node:repl');\n\nconst server = http.createServer((req, res) => {\n res.setHeader('content-type', 'multipart/octet-stream');\n\n repl.start({\n prompt: 'curl repl> ',\n input: req,\n output: res,\n terminal: false,\n useColors: true,\n useGlobal: false,\n });\n});\n\nserver.listen(8000);\n\nWhen the above script is running you can then use curl() to connect to\nthe server and connect to its REPL instance by running curl --no-progress-meter -sSNT. localhost:8000.
Warning This example is intended purely for educational purposes to demonstrate how\nNode.js REPLs can be started using different I/O streams.\nIt should not be used in production environments or any context where security\nis a concern without additional protective measures.\nIf you need to implement REPLs in a real-world application, consider alternative\napproaches that mitigate these risks, such as using secure input mechanisms and\navoiding open network interfaces.
\nOriginal code from https://gist.github.com/TooTallNate/2053342.
", "displayName": "REPL over `curl`" } ], "displayName": "Examples" } ], "displayName": "The Node.js REPL" } ], "classes": [ { "textRaw": "Class: `REPLServer`", "name": "REPLServer", "type": "class", "meta": { "added": [ "v0.1.91" ], "changes": [] }, "desc": "options <Object> | <string> See repl.start()<readline.Interface>Instances of repl.REPLServer are created using the repl.start() method\nor directly using the JavaScript new keyword.
import repl from 'node:repl';\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n\nconst repl = require('node:repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n",
"events": [
{
"textRaw": "Event: `'exit'`",
"name": "exit",
"type": "event",
"meta": {
"added": [
"v0.7.7"
],
"changes": []
},
"params": [],
"desc": "The 'exit' event is emitted when the REPL is exited either by receiving the\n.exit command as input, the user pressing Ctrl+C twice\nto signal SIGINT,\nor by pressing Ctrl+D to signal 'end' on the input\nstream. The listener\ncallback is invoked without any arguments.
replServer.on('exit', () => {\n console.log('Received \"exit\" event from repl!');\n process.exit();\n});\n"
},
{
"textRaw": "Event: `'reset'`",
"name": "reset",
"type": "event",
"meta": {
"added": [
"v0.11.0"
],
"changes": []
},
"params": [],
"desc": "The 'reset' event is emitted when the REPL's context is reset. This occurs\nwhenever the .clear command is received as input unless the REPL is using\nthe default evaluator and the repl.REPLServer instance was created with the\nuseGlobal option set to true. The listener callback will be called with a\nreference to the context object as the only argument.
This can be used primarily to re-initialize REPL context to some pre-defined\nstate:
\nimport repl from 'node:repl';\n\nfunction initializeContext(context) {\n context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n\nconst repl = require('node:repl');\n\nfunction initializeContext(context) {\n context.m = 'test';\n}\n\nconst r = repl.start({ prompt: '> ' });\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n\nWhen this code is executed, the global 'm' variable can be modified but then\nreset to its initial value using the .clear command:
$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n"
}
],
"methods": [
{
"textRaw": "`replServer.defineCommand(keyword, cmd)`",
"name": "defineCommand",
"type": "method",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`keyword` {string} The command keyword (_without_ a leading `.` character).",
"name": "keyword",
"type": "string",
"desc": "The command keyword (_without_ a leading `.` character)."
},
{
"textRaw": "`cmd` {Object|Function} The function to invoke when the command is processed.",
"name": "cmd",
"type": "Object|Function",
"desc": "The function to invoke when the command is processed."
}
]
}
],
"desc": "The replServer.defineCommand() method is used to add new .-prefixed commands\nto the REPL instance. Such commands are invoked by typing a . followed by the\nkeyword. The cmd is either a Function or an Object with the following\nproperties:
help <string> Help text to be displayed when .help is entered (Optional).action <Function> The function to execute, optionally accepting a single\nstring argument.The following example shows two new commands added to the REPL instance:
\nimport repl from 'node:repl';\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n help: 'Say hello',\n action(name) {\n this.clearBufferedCommand();\n console.log(`Hello, ${name}!`);\n this.displayPrompt();\n },\n});\nreplServer.defineCommand('saybye', function saybye() {\n console.log('Goodbye!');\n this.close();\n});\n\nconst repl = require('node:repl');\n\nconst replServer = repl.start({ prompt: '> ' });\nreplServer.defineCommand('sayhello', {\n help: 'Say hello',\n action(name) {\n this.clearBufferedCommand();\n console.log(`Hello, ${name}!`);\n this.displayPrompt();\n },\n});\nreplServer.defineCommand('saybye', function saybye() {\n console.log('Goodbye!');\n this.close();\n});\n\nThe new commands can then be used from within the REPL instance:
\n> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n"
},
{
"textRaw": "`replServer.displayPrompt([preserveCursor])`",
"name": "displayPrompt",
"type": "method",
"meta": {
"added": [
"v0.1.91"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`preserveCursor` {boolean}",
"name": "preserveCursor",
"type": "boolean",
"optional": true
}
]
}
],
"desc": "The replServer.displayPrompt() method readies the REPL instance for input\nfrom the user, printing the configured prompt to a new line in the output\nand resuming the input to accept new input.
When multi-line input is being entered, a pipe '|' is printed rather than the\n'prompt'.
When preserveCursor is true, the cursor placement will not be reset to 0.
The replServer.displayPrompt method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand() method.
The replServer.clearBufferedCommand() method clears any command that has been\nbuffered but not yet executed. This method is primarily intended to be\ncalled from within the action function for commands registered using the\nreplServer.defineCommand() method.
Initializes a history log file for the REPL instance. When executing the\nNode.js binary and using the command-line REPL, a history file is initialized\nby default. However, this is not the case when creating a REPL\nprogrammatically. Use this method to initialize a history log file when working\nwith REPL instances programmatically.
" } ] } ], "properties": [ { "textRaw": "Type: {string[]}", "name": "builtinModules", "type": "string[]", "meta": { "added": [ "v14.5.0" ], "changes": [], "deprecated": [ "v24.0.0", "v22.16.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `module.builtinModules` instead.", "desc": "A list of the names of some Node.js modules, e.g., 'http'.
An automated migration is available (source):
\nnpx codemod@latest @nodejs/repl-builtin-modules\n"
}
],
"methods": [
{
"textRaw": "`repl.start([options])`",
"name": "start",
"type": "method",
"meta": {
"added": [
"v0.1.91"
],
"changes": [
{
"version": "v24.1.0",
"pr-url": "https://github.com/nodejs/node/pull/58003",
"description": "Added the possibility to add/edit/remove multilines while adding a multiline command."
},
{
"version": "v24.0.0",
"pr-url": "https://github.com/nodejs/node/pull/57400",
"description": "The multi-line indicator is now \"|\" instead of \"...\". Added support for multi-line history. It is now possible to \"fix\" multi-line commands with syntax errors by visiting the history and editing the command. When visiting the multiline history from an old node version, the multiline structure is not preserved."
},
{
"version": [
"v13.4.0",
"v12.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/30811",
"description": "The `preview` option is now available."
},
{
"version": "v12.0.0",
"pr-url": "https://github.com/nodejs/node/pull/26518",
"description": "The `terminal` option now follows the default description in all cases and `useColors` checks `hasColors()` if available."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/19187",
"description": "The `REPL_MAGIC_MODE` `replMode` was removed."
},
{
"version": "v6.3.0",
"pr-url": "https://github.com/nodejs/node/pull/6635",
"description": "The `breakEvalOnSigint` option is supported now."
},
{
"version": "v5.8.0",
"pr-url": "https://github.com/nodejs/node/pull/5388",
"description": "The `options` parameter is optional now."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object|string}",
"name": "options",
"type": "Object|string",
"options": [
{
"textRaw": "`prompt` {string} The input prompt to display. **Default:** `'> '` (with a trailing space).",
"name": "prompt",
"type": "string",
"default": "`'> '` (with a trailing space)",
"desc": "The input prompt to display."
},
{
"textRaw": "`input` {stream.Readable} The `Readable` stream from which REPL input will be read. **Default:** `process.stdin`.",
"name": "input",
"type": "stream.Readable",
"default": "`process.stdin`",
"desc": "The `Readable` stream from which REPL input will be read."
},
{
"textRaw": "`output` {stream.Writable} The `Writable` stream to which REPL output will be written. **Default:** `process.stdout`.",
"name": "output",
"type": "stream.Writable",
"default": "`process.stdout`",
"desc": "The `Writable` stream to which REPL output will be written."
},
{
"textRaw": "`terminal` {boolean} If `true`, specifies that the `output` should be treated as a TTY terminal. **Default:** checking the value of the `isTTY` property on the `output` stream upon instantiation.",
"name": "terminal",
"type": "boolean",
"default": "checking the value of the `isTTY` property on the `output` stream upon instantiation",
"desc": "If `true`, specifies that the `output` should be treated as a TTY terminal."
},
{
"textRaw": "`eval` {Function} The function to be used when evaluating each given line of input. **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines. See the custom evaluation functions section for more details.",
"name": "eval",
"type": "Function",
"default": "an async wrapper for the JavaScript `eval()` function. An `eval` function can error with `repl.Recoverable` to indicate the input was incomplete and prompt for additional lines. See the custom evaluation functions section for more details",
"desc": "The function to be used when evaluating each given line of input."
},
{
"textRaw": "`useColors` {boolean} If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect. **Default:** checking color support on the `output` stream if the REPL instance's `terminal` value is `true`.",
"name": "useColors",
"type": "boolean",
"default": "checking color support on the `output` stream if the REPL instance's `terminal` value is `true`",
"desc": "If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output. If a custom `writer` function is provided then this has no effect."
},
{
"textRaw": "`useGlobal` {boolean} If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`. **Default:** `false`.",
"name": "useGlobal",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to `true`."
},
{
"textRaw": "`ignoreUndefined` {boolean} If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. **Default:** `false`.",
"name": "ignoreUndefined",
"type": "boolean",
"default": "`false`",
"desc": "If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`."
},
{
"textRaw": "`writer` {Function} The function to invoke to format the output of each command before writing to `output`. **Default:** `util.inspect()`.",
"name": "writer",
"type": "Function",
"default": "`util.inspect()`",
"desc": "The function to invoke to format the output of each command before writing to `output`."
},
{
"textRaw": "`completer` {Function} An optional function used for custom Tab auto completion. See `readline.InterfaceCompleter` for an example.",
"name": "completer",
"type": "Function",
"desc": "An optional function used for custom Tab auto completion. See `readline.InterfaceCompleter` for an example."
},
{
"textRaw": "`replMode` {symbol} A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:",
"name": "replMode",
"type": "symbol",
"desc": "A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:",
"options": [
{
"textRaw": "`repl.REPL_MODE_SLOPPY` to evaluate expressions in sloppy mode.",
"name": "repl.REPL_MODE_SLOPPY",
"desc": "to evaluate expressions in sloppy mode."
},
{
"textRaw": "`repl.REPL_MODE_STRICT` to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`.",
"name": "repl.REPL_MODE_STRICT",
"desc": "to evaluate expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`."
}
]
},
{
"textRaw": "`breakEvalOnSigint` {boolean} Stop evaluating the current piece of code when `SIGINT` is received, such as when Ctrl+C is pressed. This cannot be used together with a custom `eval` function. **Default:** `false`.",
"name": "breakEvalOnSigint",
"type": "boolean",
"default": "`false`",
"desc": "Stop evaluating the current piece of code when `SIGINT` is received, such as when Ctrl+C is pressed. This cannot be used together with a custom `eval` function."
},
{
"textRaw": "`preview` {boolean} Defines if the repl prints autocomplete and output previews or not. **Default:** `true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect.",
"name": "preview",
"type": "boolean",
"default": "`true` with the default eval function and `false` in case a custom eval function is used. If `terminal` is falsy, then there are no previews and the value of `preview` has no effect",
"desc": "Defines if the repl prints autocomplete and output previews or not."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {repl.REPLServer}",
"name": "return",
"type": "repl.REPLServer"
}
}
],
"desc": "The repl.start() method creates and starts a repl.REPLServer instance.
If options is a string, then it specifies the input prompt:
import repl from 'node:repl';\n\n// a Unix style prompt\nrepl.start('$ ');\n\nconst repl = require('node:repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n"
}
],
"displayName": "REPL",
"source": "doc/api/repl.md"
},
{
"textRaw": "Single executable applications",
"name": "single_executable_applications",
"introduced_in": "v19.7.0",
"type": "module",
"meta": {
"added": [
"v19.7.0",
"v18.16.0"
],
"changes": [
{
"version": "v25.5.0",
"pr-url": "https://github.com/nodejs/node/pull/61167",
"description": "Added built-in single executable application generation via the CLI flag `--build-sea`."
},
{
"version": "v20.6.0",
"pr-url": "https://github.com/nodejs/node/pull/46824",
"description": "Added support for \"useSnapshot\"."
},
{
"version": "v20.6.0",
"pr-url": "https://github.com/nodejs/node/pull/48191",
"description": "Added support for \"useCodeCache\"."
}
]
},
"stability": 1.1,
"stabilityText": "Active development",
"desc": "This feature allows the distribution of a Node.js application conveniently to a\nsystem that does not have Node.js installed.
\nNode.js supports the creation of single executable applications by allowing\nthe injection of a blob prepared by Node.js, which can contain a bundled script,\ninto the node binary. During start up, the program checks if anything has been\ninjected. If the blob is found, it executes the script in the blob. Otherwise\nNode.js operates as it normally does.
The single executable application feature supports running a\nsingle embedded script using the CommonJS or the ECMAScript Modules module system.
\nUsers can create a single executable application from their bundled script\nwith the node binary itself and any tool which can inject resources into the\nbinary.
Create a JavaScript file:
\necho 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js\n\nCreate a configuration file building a blob that can be injected into the\nsingle executable application (see\nGenerating single executable preparation blobs for details):
\necho '{ \"main\": \"hello.js\", \"output\": \"sea\" }' > sea-config.json\n\necho '{ \"main\": \"hello.js\", \"output\": \"sea.exe\" }' > sea-config.json\n\nThe .exe extension is necessary.
Generate the target executable:
\nnode --build-sea sea-config.json\n\nSign the binary (macOS and Windows only):
\ncodesign --sign - hello\n\nA certificate needs to be present for this to work. However, the unsigned\nbinary would still be runnable.
\nsigntool sign /fd SHA256 hello.exe\n\nRun the binary:
\n$ ./hello world\nHello, world!\n\n$ .\\hello.exe world\nHello, world!\n\nTo generate a single executable application directly, the --build-sea flag can be\nused. It takes a path to a configuration file in JSON format. If the path passed to it\nisn't absolute, Node.js will use the path relative to the current working directory.
The configuration currently reads the following top-level fields:
\n{\n \"main\": \"/path/to/bundled/script.js\",\n \"mainFormat\": \"commonjs\", // Default: \"commonjs\", options: \"commonjs\", \"module\"\n \"executable\": \"/path/to/node/binary\", // Optional, if not specified, uses the current Node.js binary\n \"output\": \"/path/to/write/the/generated/executable\",\n \"disableExperimentalSEAWarning\": true, // Default: false\n \"useSnapshot\": false, // Default: false\n \"useCodeCache\": true, // Default: false\n \"execArgv\": [\"--no-warnings\", \"--max-old-space-size=4096\"], // Optional\n \"execArgvExtension\": \"env\", // Default: \"env\", options: \"none\", \"env\", \"cli\"\n \"assets\": { // Optional\n \"a.dat\": \"/path/to/a.dat\",\n \"b.txt\": \"/path/to/b.txt\"\n }\n}\n\nIf the paths are not absolute, Node.js will use the path relative to the\ncurrent working directory. The version of the Node.js binary used to produce\nthe blob must be the same as the one to which the blob will be injected.
\nNote: When generating cross-platform SEAs (e.g., generating a SEA\nfor linux-x64 on darwin-arm64), useCodeCache and useSnapshot\nmust be set to false to avoid generating incompatible executables.\nSince code cache and snapshots can only be loaded on the same platform\nwhere they are compiled, the generated executable might crash on startup when\ntrying to load code cache or snapshots built on a different platform.
Users can include assets by adding a key-path dictionary to the configuration\nas the assets field. At build time, Node.js would read the assets from the\nspecified paths and bundle them into the preparation blob. In the generated\nexecutable, users can retrieve the assets using the sea.getAsset() and\nsea.getAssetAsBlob() APIs.
{\n \"main\": \"/path/to/bundled/script.js\",\n \"output\": \"/path/to/write/the/generated/executable\",\n \"assets\": {\n \"a.jpg\": \"/path/to/a.jpg\",\n \"b.txt\": \"/path/to/b.txt\"\n }\n}\n\nThe single-executable application can access the assets as follows:
\nconst { getAsset, getAssetAsBlob, getRawAsset, getAssetKeys } = require('node:sea');\n// Get all asset keys.\nconst keys = getAssetKeys();\nconsole.log(keys); // ['a.jpg', 'b.txt']\n// Returns a copy of the data in an ArrayBuffer.\nconst image = getAsset('a.jpg');\n// Returns a string decoded from the asset as UTF8.\nconst text = getAsset('b.txt', 'utf8');\n// Returns a Blob containing the asset.\nconst blob = getAssetAsBlob('a.jpg');\n// Returns an ArrayBuffer containing the raw asset without copying.\nconst raw = getRawAsset('a.jpg');\n\nSee documentation of the sea.getAsset(), sea.getAssetAsBlob(),\nsea.getRawAsset() and sea.getAssetKeys() APIs for more information.
The useSnapshot field can be used to enable startup snapshot support. In this\ncase, the main script would not be executed when the final executable is launched.\nInstead, it would be run when the single executable application preparation\nblob is generated on the building machine. The generated preparation blob would\nthen include a snapshot capturing the states initialized by the main script.\nThe final executable, with the preparation blob injected, would deserialize\nthe snapshot at run time.
When useSnapshot is true, the main script must invoke the\nv8.startupSnapshot.setDeserializeMainFunction() API to configure code\nthat needs to be run when the final executable is launched by the users.
The typical pattern for an application to use snapshot in a single executable\napplication is:
\nv8.startupSnapshot.setDeserializeMainFunction(). This function will be\ncompiled and serialized into the snapshot, but not invoked at build time.The general constraints of the startup snapshot scripts also apply to the main\nscript when it's used to build snapshot for the single executable application,\nand the main script can use the v8.startupSnapshot API to adapt to\nthese constraints. See\ndocumentation about startup snapshot support in Node.js.
When useCodeCache is set to true in the configuration, during the generation\nof the single executable preparation blob, Node.js will compile the main\nscript to generate the V8 code cache. The generated code cache would be part of\nthe preparation blob and get injected into the final executable. When the single\nexecutable application is launched, instead of compiling the main script from\nscratch, Node.js would use the code cache to speed up the compilation, then\nexecute the script, which would improve the startup performance.
Note: import() does not work when useCodeCache is true.
The execArgv field can be used to specify Node.js-specific\narguments that will be automatically applied when the single\nexecutable application starts. This allows application developers\nto configure Node.js runtime options without requiring end users\nto be aware of these flags.
For example, the following configuration:
\n{\n \"main\": \"/path/to/bundled/script.js\",\n \"output\": \"/path/to/write/the/generated/executable\",\n \"execArgv\": [\"--no-warnings\", \"--max-old-space-size=2048\"]\n}\n\nwill instruct the SEA to be launched with the --no-warnings and\n--max-old-space-size=2048 flags. In the scripts embedded in the executable, these flags\ncan be accessed using the process.execArgv property:
// If the executable is launched with `sea user-arg1 user-arg2`\nconsole.log(process.execArgv);\n// Prints: ['--no-warnings', '--max-old-space-size=2048']\nconsole.log(process.argv);\n// Prints ['/path/to/sea', 'path/to/sea', 'user-arg1', 'user-arg2']\n\nThe user-provided arguments are in the process.argv array starting from index 2,\nsimilar to what would happen if the application is started with:
node --no-warnings --max-old-space-size=2048 /path/to/bundled/script.js user-arg1 user-arg2\n",
"displayName": "Execution arguments"
},
{
"textRaw": "Execution argument extension",
"name": "execution_argument_extension",
"type": "module",
"desc": "The execArgvExtension field controls how additional execution arguments can be\nprovided beyond those specified in the execArgv field. It accepts one of three string values:
\"none\": No extension is allowed. Only the arguments specified in execArgv will be used,\nand the NODE_OPTIONS environment variable will be ignored.\"env\": (Default) The NODE_OPTIONS environment variable can extend the execution arguments.\nThis is the default behavior to maintain backward compatibility.\"cli\": The executable can be launched with --node-options=\"--flag1 --flag2\", and those flags\nwill be parsed as execution arguments for Node.js instead of being passed to the user script.\nThis allows using arguments that are not supported by the NODE_OPTIONS environment variable.For example, with \"execArgvExtension\": \"cli\":
{\n \"main\": \"/path/to/bundled/script.js\",\n \"output\": \"/path/to/write/the/generated/executable\",\n \"execArgv\": [\"--no-warnings\"],\n \"execArgvExtension\": \"cli\"\n}\n\nThe executable can be launched as:
\n./my-sea --node-options=\"--trace-exit\" user-arg1 user-arg2\n\nThis would be equivalent to running:
\nnode --no-warnings --trace-exit /path/to/bundled/script.js user-arg1 user-arg2\n",
"displayName": "Execution argument extension"
}
],
"displayName": "Generating single executable applications with `--build-sea`"
},
{
"textRaw": "Single-executable application API",
"name": "single-executable_application_api",
"type": "module",
"desc": "The node:sea builtin allows interaction with the single-executable application\nfrom the JavaScript main script embedded into the executable.
This method can be used to retrieve the assets configured to be bundled into the\nsingle-executable application at build time.\nAn error is thrown when no matching asset can be found.
" }, { "textRaw": "`sea.getAssetAsBlob(key[, options])`", "name": "getAssetAsBlob", "type": "method", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`key` {string} the key for the asset in the dictionary specified by the `assets` field in the single-executable application configuration.", "name": "key", "type": "string", "desc": "the key for the asset in the dictionary specified by the `assets` field in the single-executable application configuration." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`type` {string} An optional mime type for the blob.", "name": "type", "type": "string", "desc": "An optional mime type for the blob." } ], "optional": true } ], "return": { "textRaw": "Returns: {Blob}", "name": "return", "type": "Blob" } } ], "desc": "Similar to sea.getAsset(), but returns the result in a <Blob>.\nAn error is thrown when no matching asset can be found.
This method can be used to retrieve the assets configured to be bundled into the\nsingle-executable application at build time.\nAn error is thrown when no matching asset can be found.
\nUnlike sea.getAsset() or sea.getAssetAsBlob(), this method does not\nreturn 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\ninjected section is not marked as writable or not aligned properly,\nwrites to the returned array buffer is likely to result in a crash.
" }, { "textRaw": "`sea.getAssetKeys()`", "name": "getAssetKeys", "type": "method", "meta": { "added": [ "v24.8.0", "v22.20.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns {string[]} An array containing all the keys of the assets embedded in the executable. If no assets are embedded, returns an empty array.", "name": "return", "type": "string[]", "desc": "An array containing all the keys of the assets embedded in the executable. If no assets are embedded, returns an empty array." } } ], "desc": "This method can be used to retrieve an array of all the keys of assets\nembedded into the single-executable application.\nAn error is thrown when not running inside a single-executable application.
" } ], "displayName": "Single-executable application API" }, { "textRaw": "In the injected main script", "name": "in_the_injected_main_script", "type": "module", "modules": [ { "textRaw": "Module format of the injected main script", "name": "module_format_of_the_injected_main_script", "type": "module", "desc": "To specify how Node.js should interpret the injected main script, use the\nmainFormat field in the single-executable application configuration.\nThe accepted values are:
\"commonjs\": The injected main script is treated as a CommonJS module.\"module\": The injected main script is treated as an ECMAScript module.If the mainFormat field is not specified, it defaults to \"commonjs\".
Currently, \"mainFormat\": \"module\" cannot be used together with \"useSnapshot\"\nor \"useCodeCache\".
In the injected main script, module loading does not read from the file system.\nBy default, both require() and import statements would only be able to load\nthe built-in modules. Attempting to load a module that can only be found in the\nfile system will throw an error.
Users can bundle their application into a standalone JavaScript file to inject\ninto the executable. This also ensures a more deterministic dependency graph.
\nTo load modules from the file system in the injected main script, users can\ncreate a require function that can load from the file system using\nmodule.createRequire(). For example, in a CommonJS entry point:
const { createRequire } = require('node:module');\nrequire = createRequire(__filename);\n",
"displayName": "Module loading in the injected main script"
},
{
"textRaw": "`require()` in the injected main script",
"name": "`require()`_in_the_injected_main_script",
"type": "module",
"desc": "require() in the injected main script is not the same as the require()\navailable to modules that are not injected.\nCurrently, it does not have any of the properties that non-injected\nrequire() has except require.main.
The values of __filename and module.filename in the injected main script\nare equal to process.execPath.
The value of __dirname in the injected main script is equal to the directory\nname of process.execPath.
When using \"mainFormat\": \"module\", import.meta is available in the\ninjected main script with the following properties:
import.meta.url: A file: URL corresponding to process.execPath.import.meta.filename: Equal to process.execPath.import.meta.dirname: The directory name of process.execPath.import.meta.main: true.import.meta.resolve is currently not supported.
When using \"mainFormat\": \"module\", import() can be used to dynamically\nload built-in modules. Attempting to use import() to load modules from\nthe file system will throw an error.
Native addons can be bundled as assets into the single-executable application\nby specifying them in the assets field of the configuration file used to\ngenerate the single-executable application preparation blob.\nThe addon can then be loaded in the injected main script by writing the asset\nto a temporary file and loading it with process.dlopen().
{\n \"main\": \"/path/to/bundled/script.js\",\n \"output\": \"/path/to/write/the/generated/executable\",\n \"assets\": {\n \"myaddon.node\": \"/path/to/myaddon/build/Release/myaddon.node\"\n }\n}\n\n// script.js\nconst fs = require('node:fs');\nconst os = require('node:os');\nconst path = require('node:path');\nconst { getRawAsset } = require('node:sea');\nconst addonPath = path.join(os.tmpdir(), 'myaddon.node');\nfs.writeFileSync(addonPath, new Uint8Array(getRawAsset('myaddon.node')));\nconst myaddon = { exports: {} };\nprocess.dlopen(myaddon, addonPath);\nconsole.log(myaddon.exports);\nfs.rmSync(addonPath);\n\nKnown caveat: if the single-executable application is produced by postject running on a Linux arm64 docker container,\nthe produced ELF binary does not have the correct hash table to load the addons and\nwill crash on process.dlopen(). Build the single-executable application on other platforms, or at least on\na non-container Linux arm64 environment to work around this issue.
The process documented here is subject to change.
", "modules": [ { "textRaw": "1. Generating single executable preparation blobs", "name": "1._generating_single_executable_preparation_blobs", "type": "module", "desc": "To build a single executable application, Node.js would first generate a blob\nthat contains all the necessary information to run the bundled script.\nWhen using --build-sea, this step is done internally along with the injection.
Before --build-sea was introduced, an older workflow was introduced to write the\npreparation blob to disk for injection by external tools. This can still\nbe used for verification purposes.
To dump the preparation blob to disk for verification, use --experimental-sea-config.\nThis writes a file that can be injected into a Node.js binary using tools like postject.
The configuration is similar to that of --build-sea, except that the\noutput field specifies the path to write the generated blob file instead of\nthe final executable.
{\n \"main\": \"/path/to/bundled/script.js\",\n // Instead of the final executable, this is the path to write the blob.\n \"output\": \"/path/to/write/the/generated/blob.blob\"\n}\n",
"displayName": "Dumping the preparation blob to disk"
}
],
"displayName": "1. Generating single executable preparation blobs"
},
{
"textRaw": "2. Injecting the preparation blob into the `node` binary",
"name": "2._injecting_the_preparation_blob_into_the_`node`_binary",
"type": "module",
"desc": "To complete the creation of a single executable application, the generated blob\nneeds to be injected into a copy of the node binary, as documented below.
When using --build-sea, this step is done internally along with the blob generation.
node binary is a PE file, the blob should be injected as a resource\nnamed NODE_SEA_BLOB.node binary is a Mach-O file, the blob should be injected as a section\nnamed NODE_SEA_BLOB in the NODE_SEA segment.node binary is an ELF file, the blob should be injected as a note\nnamed NODE_SEA_BLOB.Then, the SEA building process searches the binary for the\nNODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0 fuse string and flip the\nlast character to 1 to indicate that a resource has been injected.
Before --build-sea was introduced, an older workflow was introduced to allow\nexternal tools to inject the generated blob into a copy of the node binary.
For example, with postject:
\nCreate a copy of the node executable and name it according to your needs:
cp $(command -v node) hello\n\nnode -e \"require('fs').copyFileSync(process.execPath, 'hello.exe')\"\n\nThe .exe extension is necessary.
Remove the signature of the binary (macOS and Windows only):
\ncodesign --remove-signature hello\n\nsigntool can be used from the installed Windows SDK. If this step is\nskipped, ignore any signature-related warning from postject.
\nsigntool remove /s hello.exe\n\nInject the blob into the copied binary by running postject with\nthe following options:
hello / hello.exe - The name of the copy of the node executable\ncreated in step 4.NODE_SEA_BLOB - The name of the resource / note / section in the binary\nwhere 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\nfuse 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\nsegment in the binary where the contents of the blob will be\nstored.To summarize, here is the required command for each platform:
\nOn Linux:
\nnpx postject hello NODE_SEA_BLOB sea-prep.blob \\\n --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2\n\nOn Windows - PowerShell:
\nnpx postject hello.exe NODE_SEA_BLOB sea-prep.blob `\n --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2\n\nOn Windows - Command Prompt:
\nnpx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^\n --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2\n\nOn macOS:
\nnpx postject hello NODE_SEA_BLOB sea-prep.blob \\\n --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \\\n --macho-segment-name NODE_SEA\n\nSingle-executable support is tested regularly on CI only on the following\nplatforms:
\nThis is due to a lack of better tools to generate single-executables that can be\nused to test this feature on other platforms.
\nSuggestions for other resource injection tools/workflows are welcomed. Please\nstart a discussion at https://github.com/nodejs/single-executable/discussions\nto help us document them.
", "displayName": "Platform support" } ], "displayName": "Notes" } ], "displayName": "Single executable applications", "source": "doc/api/single-executable-applications.md" }, { "textRaw": "SQLite", "name": "sqlite", "introduced_in": "v22.5.0", "type": "module", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/61262", "description": "SQLite is now a release candidate." }, { "version": [ "v23.4.0", "v22.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/55890", "description": "SQLite is no longer behind `--experimental-sqlite` but still experimental." } ] }, "stability": 1.2, "stabilityText": "Release candidate.", "desc": "The node:sqlite module facilitates working with SQLite databases.\nTo access it:
import sqlite from 'node:sqlite';\n\nconst sqlite = require('node:sqlite');\n\nThis module is only available under the node: scheme.
The following example shows the basic usage of the node:sqlite module to open\nan in-memory database, write data to the database, and then read the data back.
import { DatabaseSync } from 'node:sqlite';\nconst database = new DatabaseSync(':memory:');\n\n// Execute SQL statements from strings.\ndatabase.exec(`\n CREATE TABLE data(\n key INTEGER PRIMARY KEY,\n value TEXT\n ) STRICT\n`);\n// Create a prepared statement to insert data into the database.\nconst insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\n// Execute the prepared statement with bound values.\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n// Create a prepared statement to read data from the database.\nconst query = database.prepare('SELECT * FROM data ORDER BY key');\n// Execute the prepared statement and log the result set.\nconsole.log(query.all());\n// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]\n\n'use strict';\nconst { DatabaseSync } = require('node:sqlite');\nconst database = new DatabaseSync(':memory:');\n\n// Execute SQL statements from strings.\ndatabase.exec(`\n CREATE TABLE data(\n key INTEGER PRIMARY KEY,\n value TEXT\n ) STRICT\n`);\n// Create a prepared statement to insert data into the database.\nconst insert = database.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\n// Execute the prepared statement with bound values.\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n// Create a prepared statement to read data from the database.\nconst query = database.prepare('SELECT * FROM data ORDER BY key');\n// Execute the prepared statement and log the result set.\nconsole.log(query.all());\n// Prints: [ { key: 1, value: 'hello' }, { key: 2, value: 'world' } ]\n",
"classes": [
{
"textRaw": "Class: `DatabaseSync`",
"name": "DatabaseSync",
"type": "class",
"meta": {
"added": [
"v22.5.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57752",
"description": "Add `timeout` option."
},
{
"version": [
"v23.10.0",
"v22.15.0"
],
"pr-url": "https://github.com/nodejs/node/pull/56991",
"description": "The `path` argument now supports Buffer and URL objects."
}
]
},
"desc": "This class represents a single connection to a SQLite database. All APIs\nexposed by this class execute synchronously.
", "signatures": [ { "textRaw": "`new DatabaseSync(path[, options])`", "name": "DatabaseSync", "type": "ctor", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": "v25.5.0", "pr-url": "https://github.com/nodejs/node/pull/61266", "description": "Enable `defensive` by default." }, { "version": [ "v25.1.0" ], "pr-url": "https://github.com/nodejs/node/pull/60217", "description": "Add `defensive` option." }, { "version": [ "v24.4.0", "v22.18.0" ], "pr-url": "https://github.com/nodejs/node/pull/58697", "description": "Add new SQLite database options." } ] }, "params": [ { "textRaw": "`path` {string|Buffer|URL} The path of the database. A SQLite database can be stored in a file or completely in memory. To use a file-backed database, the path should be a file path. To use an in-memory database, the path should be the special name `':memory:'`.", "name": "path", "type": "string|Buffer|URL", "desc": "The path of the database. A SQLite database can be stored in a file or completely in memory. To use a file-backed database, the path should be a file path. To use an in-memory database, the path should be the special name `':memory:'`." }, { "textRaw": "`options` {Object} Configuration options for the database connection. The following options are supported:", "name": "options", "type": "Object", "desc": "Configuration options for the database connection. The following options are supported:", "options": [ { "textRaw": "`open` {boolean} If `true`, the database is opened by the constructor. When this value is `false`, the database must be opened via the `open()` method. **Default:** `true`.", "name": "open", "type": "boolean", "default": "`true`", "desc": "If `true`, the database is opened by the constructor. When this value is `false`, the database must be opened via the `open()` method." }, { "textRaw": "`readOnly` {boolean} If `true`, the database is opened in read-only mode. If the database does not exist, opening it will fail. **Default:** `false`.", "name": "readOnly", "type": "boolean", "default": "`false`", "desc": "If `true`, the database is opened in read-only mode. If the database does not exist, opening it will fail." }, { "textRaw": "`enableForeignKeyConstraints` {boolean} If `true`, foreign key constraints are enabled. This is recommended but can be disabled for compatibility with legacy database schemas. The enforcement of foreign key constraints can be enabled and disabled after opening the database using `PRAGMA foreign_keys`. **Default:** `true`.", "name": "enableForeignKeyConstraints", "type": "boolean", "default": "`true`", "desc": "If `true`, foreign key constraints are enabled. This is recommended but can be disabled for compatibility with legacy database schemas. The enforcement of foreign key constraints can be enabled and disabled after opening the database using `PRAGMA foreign_keys`." }, { "textRaw": "`enableDoubleQuotedStringLiterals` {boolean} If `true`, SQLite will accept double-quoted string literals. This is not recommended but can be enabled for compatibility with legacy database schemas. **Default:** `false`.", "name": "enableDoubleQuotedStringLiterals", "type": "boolean", "default": "`false`", "desc": "If `true`, SQLite will accept double-quoted string literals. This is not recommended but can be enabled for compatibility with legacy database schemas." }, { "textRaw": "`allowExtension` {boolean} If `true`, the `loadExtension` SQL function and the `loadExtension()` method are enabled. You can call `enableLoadExtension(false)` later to disable this feature. **Default:** `false`.", "name": "allowExtension", "type": "boolean", "default": "`false`", "desc": "If `true`, the `loadExtension` SQL function and the `loadExtension()` method are enabled. You can call `enableLoadExtension(false)` later to disable this feature." }, { "textRaw": "`timeout` {number} The busy timeout in milliseconds. This is the maximum amount of time that SQLite will wait for a database lock to be released before returning an error. **Default:** `0`.", "name": "timeout", "type": "number", "default": "`0`", "desc": "The busy timeout in milliseconds. This is the maximum amount of time that SQLite will wait for a database lock to be released before returning an error." }, { "textRaw": "`readBigInts` {boolean} If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, integer fields are read as JavaScript numbers. **Default:** `false`.", "name": "readBigInts", "type": "boolean", "default": "`false`", "desc": "If `true`, integer fields are read as JavaScript `BigInt` values. If `false`, integer fields are read as JavaScript numbers." }, { "textRaw": "`returnArrays` {boolean} If `true`, query results are returned as arrays instead of objects. **Default:** `false`.", "name": "returnArrays", "type": "boolean", "default": "`false`", "desc": "If `true`, query results are returned as arrays instead of objects." }, { "textRaw": "`allowBareNamedParameters` {boolean} If `true`, allows binding named parameters without the prefix character (e.g., `foo` instead of `:foo`). **Default:** `true`.", "name": "allowBareNamedParameters", "type": "boolean", "default": "`true`", "desc": "If `true`, allows binding named parameters without the prefix character (e.g., `foo` instead of `:foo`)." }, { "textRaw": "`allowUnknownNamedParameters` {boolean} If `true`, unknown named parameters are ignored when binding. If `false`, an exception is thrown for unknown named parameters. **Default:** `false`.", "name": "allowUnknownNamedParameters", "type": "boolean", "default": "`false`", "desc": "If `true`, unknown named parameters are ignored when binding. If `false`, an exception is thrown for unknown named parameters." }, { "textRaw": "`defensive` {boolean} If `true`, enables the defensive flag. When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. The defensive flag can also be set using `enableDefensive()`. **Default:** `true`.", "name": "defensive", "type": "boolean", "default": "`true`", "desc": "If `true`, enables the defensive flag. When the defensive flag is enabled, language features that allow ordinary SQL to deliberately corrupt the database file are disabled. The defensive flag can also be set using `enableDefensive()`." }, { "textRaw": "`limits` {Object} Configuration for various SQLite limits. These limits can be used to prevent excessive resource consumption when handling potentially malicious input. See Run-Time Limits and Limit Constants in the SQLite documentation for details. Default values are determined by SQLite's compile-time defaults and may vary depending on how SQLite was built. The following properties are supported:", "name": "limits", "type": "Object", "desc": "Configuration for various SQLite limits. These limits can be used to prevent excessive resource consumption when handling potentially malicious input. See Run-Time Limits and Limit Constants in the SQLite documentation for details. Default values are determined by SQLite's compile-time defaults and may vary depending on how SQLite was built. The following properties are supported:", "options": [ { "textRaw": "`length` {number} Maximum length of a string or BLOB.", "name": "length", "type": "number", "desc": "Maximum length of a string or BLOB." }, { "textRaw": "`sqlLength` {number} Maximum length of an SQL statement.", "name": "sqlLength", "type": "number", "desc": "Maximum length of an SQL statement." }, { "textRaw": "`column` {number} Maximum number of columns.", "name": "column", "type": "number", "desc": "Maximum number of columns." }, { "textRaw": "`exprDepth` {number} Maximum depth of an expression tree.", "name": "exprDepth", "type": "number", "desc": "Maximum depth of an expression tree." }, { "textRaw": "`compoundSelect` {number} Maximum number of terms in a compound SELECT.", "name": "compoundSelect", "type": "number", "desc": "Maximum number of terms in a compound SELECT." }, { "textRaw": "`vdbeOp` {number} Maximum number of VDBE instructions.", "name": "vdbeOp", "type": "number", "desc": "Maximum number of VDBE instructions." }, { "textRaw": "`functionArg` {number} Maximum number of function arguments.", "name": "functionArg", "type": "number", "desc": "Maximum number of function arguments." }, { "textRaw": "`attach` {number} Maximum number of attached databases.", "name": "attach", "type": "number", "desc": "Maximum number of attached databases." }, { "textRaw": "`likePatternLength` {number} Maximum length of a LIKE pattern.", "name": "likePatternLength", "type": "number", "desc": "Maximum length of a LIKE pattern." }, { "textRaw": "`variableNumber` {number} Maximum number of SQL variables.", "name": "variableNumber", "type": "number", "desc": "Maximum number of SQL variables." }, { "textRaw": "`triggerDepth` {number} Maximum trigger recursion depth.", "name": "triggerDepth", "type": "number", "desc": "Maximum trigger recursion depth." } ] } ], "optional": true } ], "desc": "Constructs a new DatabaseSync instance.
Registers a new aggregate function with the SQLite database. This method is a wrapper around\nsqlite3_create_window_function().
When used as a window function, the result function will be called multiple times.
const { DatabaseSync } = require('node:sqlite');\n\nconst db = new DatabaseSync(':memory:');\ndb.exec(`\n CREATE TABLE t3(x, y);\n INSERT INTO t3 VALUES ('a', 4),\n ('b', 5),\n ('c', 3),\n ('d', 8),\n ('e', 1);\n`);\n\ndb.aggregate('sumint', {\n start: 0,\n step: (acc, value) => acc + value,\n});\n\ndb.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }\n\nimport { DatabaseSync } from 'node:sqlite';\n\nconst db = new DatabaseSync(':memory:');\ndb.exec(`\n CREATE TABLE t3(x, y);\n INSERT INTO t3 VALUES ('a', 4),\n ('b', 5),\n ('c', 3),\n ('d', 8),\n ('e', 1);\n`);\n\ndb.aggregate('sumint', {\n start: 0,\n step: (acc, value) => acc + value,\n});\n\ndb.prepare('SELECT sumint(y) as total FROM t3').get(); // { total: 21 }\n"
},
{
"textRaw": "`database.close()`",
"name": "close",
"type": "method",
"meta": {
"added": [
"v22.5.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes the database connection. An exception is thrown if the database is not\nopen. This method is a wrapper around sqlite3_close_v2().
Loads a shared library into the database connection. This method is a wrapper\naround sqlite3_load_extension(). It is required to enable the\nallowExtension option when constructing the DatabaseSync instance.
Enables or disables the loadExtension SQL function, and the loadExtension()\nmethod. When allowExtension is false when constructing, you cannot enable\nloading extensions for security reasons.
Enables or disables the defensive flag. When the defensive flag is active,\nlanguage features that allow ordinary SQL to deliberately corrupt the database file are disabled.\nSee SQLITE_DBCONFIG_DEFENSIVE in the SQLite documentation for details.
This method is a wrapper around sqlite3_db_filename()
This method allows one or more SQL statements to be executed without returning\nany results. This method is useful when executing SQL statements read from a\nfile. This method is a wrapper around sqlite3_exec().
This method is used to create SQLite user-defined functions. This method is a\nwrapper around sqlite3_create_function_v2().
Sets an authorizer callback that SQLite will invoke whenever it attempts to\naccess data or modify the database schema through prepared statements.\nThis can be used to implement security policies, audit access, or restrict certain operations.\nThis method is a wrapper around sqlite3_set_authorizer().
When invoked, the callback receives five arguments:
\nactionCode <number> The type of operation being performed (e.g., SQLITE_INSERT, SQLITE_UPDATE, SQLITE_SELECT).arg1 <string> | <null> The first argument (context-dependent, often a table name).arg2 <string> | <null> The second argument (context-dependent, often a column name).dbName <string> | <null> The name of the database.triggerOrView <string> | <null> The name of the trigger or view causing the access.The callback must return one of the following constants:
\nSQLITE_OK - Allow the operation.SQLITE_DENY - Deny the operation (causes an error).SQLITE_IGNORE - Ignore the operation (silently skip).const { DatabaseSync, constants } = require('node:sqlite');\nconst db = new DatabaseSync(':memory:');\n\n// Set up an authorizer that denies all table creation\ndb.setAuthorizer((actionCode) => {\n if (actionCode === constants.SQLITE_CREATE_TABLE) {\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n});\n\n// This will work\ndb.prepare('SELECT 1').get();\n\n// This will throw an error due to authorization denial\ntry {\n db.exec('CREATE TABLE blocked (id INTEGER)');\n} catch (err) {\n console.log('Operation blocked:', err.message);\n}\n\nimport { DatabaseSync, constants } from 'node:sqlite';\nconst db = new DatabaseSync(':memory:');\n\n// Set up an authorizer that denies all table creation\ndb.setAuthorizer((actionCode) => {\n if (actionCode === constants.SQLITE_CREATE_TABLE) {\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n});\n\n// This will work\ndb.prepare('SELECT 1').get();\n\n// This will throw an error due to authorization denial\ntry {\n db.exec('CREATE TABLE blocked (id INTEGER)');\n} catch (err) {\n console.log('Operation blocked:', err.message);\n}\n"
},
{
"textRaw": "`database.open()`",
"name": "open",
"type": "method",
"meta": {
"added": [
"v22.5.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Opens the database specified in the path argument of the DatabaseSync\nconstructor. This method should only be used when the database is not opened via\nthe constructor. An exception is thrown if the database is already open.
Compiles a SQL statement into a prepared statement. This method is a wrapper\naround sqlite3_prepare_v2().
Creates a new SQLTagStore, which is a Least Recently Used (LRU) cache\nfor storing prepared statements. This allows for the efficient reuse of\nprepared statements by tagging them with a unique identifier.
When a tagged SQL literal is executed, the SQLTagStore checks if a prepared\nstatement for the corresponding SQL query string already exists in the cache.\nIf it does, the cached statement is used. If not, a new prepared statement is\ncreated, executed, and then stored in the cache for future use. This mechanism\nhelps to avoid the overhead of repeatedly parsing and preparing the same SQL\nstatements.
Tagged statements bind the placeholder values from the template literal as\nparameters to the underlying prepared statement. For example:
\nsqlTagStore.get`SELECT ${value}`;\n\nis equivalent to:
\ndb.prepare('SELECT ?').get(value);\n\nHowever, in the first example, the tag store will cache the underlying prepared\nstatement for future use.
\n\n\nNote: The
\n${value}syntax in tagged statements binds a parameter to\nthe prepared statement. This differs from its behavior in untagged template\nliterals, where it performs string interpolation.\n// This a safe example of binding a parameter to a tagged statement.\nsqlTagStore.run`INSERT INTO t1 (id) VALUES (${id})`;\n\n// This is an *unsafe* example of an untagged template string.\n// `id` is interpolated into the query text as a string.\n// This can lead to SQL injection and data corruption.\ndb.run(`INSERT INTO t1 (id) VALUES (${id})`);\n
The tag store will match a statement from the cache if the query strings\n(including the positions of any bound placeholders) are identical.
\n// The following statements will match in the cache:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${12345} AND active = 1`;\n\n// The following statements will not match, as the query strings\n// and bound placeholders differ:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`SELECT * FROM t1 WHERE id = 12345 AND active = 1`;\n\n// The following statements will not match, as matches are case-sensitive:\nsqlTagStore.get`SELECT * FROM t1 WHERE id = ${id} AND active = 1`;\nsqlTagStore.get`select * from t1 where id = ${id} and active = 1`;\n\nThe only way of binding parameters in tagged statements is with the ${value}\nsyntax. Do not add parameter binding placeholders (? etc.) to the SQL query\nstring itself.
import { DatabaseSync } from 'node:sqlite';\n\nconst db = new DatabaseSync(':memory:');\nconst sql = db.createTagStore();\n\ndb.exec('CREATE TABLE users (id INT, name TEXT)');\n\n// Using the 'run' method to insert data.\n// The tagged literal is used to identify the prepared statement.\nsql.run`INSERT INTO users VALUES (1, 'Alice')`;\nsql.run`INSERT INTO users VALUES (2, 'Bob')`;\n\n// Using the 'get' method to retrieve a single row.\nconst name = 'Alice';\nconst user = sql.get`SELECT * FROM users WHERE name = ${name}`;\nconsole.log(user); // { id: 1, name: 'Alice' }\n\n// Using the 'all' method to retrieve all rows.\nconst allUsers = sql.all`SELECT * FROM users ORDER BY id`;\nconsole.log(allUsers);\n// [\n// { id: 1, name: 'Alice' },\n// { id: 2, name: 'Bob' }\n// ]\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst db = new DatabaseSync(':memory:');\nconst sql = db.createTagStore();\n\ndb.exec('CREATE TABLE users (id INT, name TEXT)');\n\n// Using the 'run' method to insert data.\n// The tagged literal is used to identify the prepared statement.\nsql.run`INSERT INTO users VALUES (1, 'Alice')`;\nsql.run`INSERT INTO users VALUES (2, 'Bob')`;\n\n// Using the 'get' method to retrieve a single row.\nconst name = 'Alice';\nconst user = sql.get`SELECT * FROM users WHERE name = ${name}`;\nconsole.log(user); // { id: 1, name: 'Alice' }\n\n// Using the 'all' method to retrieve all rows.\nconst allUsers = sql.all`SELECT * FROM users ORDER BY id`;\nconsole.log(allUsers);\n// [\n// { id: 1, name: 'Alice' },\n// { id: 2, name: 'Bob' }\n// ]\n"
},
{
"textRaw": "`database.createSession([options])`",
"name": "createSession",
"type": "method",
"meta": {
"added": [
"v23.3.0",
"v22.12.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} The configuration options for the session.",
"name": "options",
"type": "Object",
"desc": "The configuration options for the session.",
"options": [
{
"textRaw": "`table` {string} A specific table to track changes for. By default, changes to all tables are tracked.",
"name": "table",
"type": "string",
"desc": "A specific table to track changes for. By default, changes to all tables are tracked."
},
{
"textRaw": "`db` {string} Name of the database to track. This is useful when multiple databases have been added using `ATTACH DATABASE`. **Default**: `'main'`.",
"name": "db",
"type": "string",
"desc": "Name of the database to track. This is useful when multiple databases have been added using `ATTACH DATABASE`. **Default**: `'main'`."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Session} A session handle.",
"name": "return",
"type": "Session",
"desc": "A session handle."
}
}
],
"desc": "Creates and attaches a session to the database. This method is a wrapper around sqlite3session_create() and sqlite3session_attach().
An exception is thrown if the database is not\nopen. This method is a wrapper around sqlite3changeset_apply().
import { DatabaseSync } from 'node:sqlite';\n\nconst sourceDb = new DatabaseSync(':memory:');\nconst targetDb = new DatabaseSync(':memory:');\n\nsourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\ntargetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\n\nconst session = sourceDb.createSession();\n\nconst insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n\nconst changeset = session.changeset();\ntargetDb.applyChangeset(changeset);\n// Now that the changeset has been applied, targetDb contains the same data as sourceDb.\n\nconst { DatabaseSync } = require('node:sqlite');\n\nconst sourceDb = new DatabaseSync(':memory:');\nconst targetDb = new DatabaseSync(':memory:');\n\nsourceDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\ntargetDb.exec('CREATE TABLE data(key INTEGER PRIMARY KEY, value TEXT)');\n\nconst session = sourceDb.createSession();\n\nconst insert = sourceDb.prepare('INSERT INTO data (key, value) VALUES (?, ?)');\ninsert.run(1, 'hello');\ninsert.run(2, 'world');\n\nconst changeset = session.changeset();\ntargetDb.applyChangeset(changeset);\n// Now that the changeset has been applied, targetDb contains the same data as sourceDb.\n"
},
{
"textRaw": "`database[Symbol.dispose]()`",
"name": "[Symbol.dispose]",
"type": "method",
"meta": {
"added": [
"v23.11.0",
"v22.15.0"
],
"changes": [
{
"version": "v24.2.0",
"pr-url": "https://github.com/nodejs/node/pull/58467",
"description": "No longer experimental."
}
]
},
"signatures": [
{
"params": []
}
],
"desc": "Closes the database connection. If the database connection is already closed\nthen this is a no-op.
" } ], "properties": [ { "textRaw": "Type: {boolean} Whether the database is currently open or not.", "name": "isOpen", "type": "boolean", "meta": { "added": [ "v23.11.0", "v22.15.0" ], "changes": [] }, "desc": "Whether the database is currently open or not." }, { "textRaw": "Type: {boolean} Whether the database is currently within a transaction. This method is a wrapper around `sqlite3_get_autocommit()`.", "name": "isTransaction", "type": "boolean", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "desc": "Whether the database is currently within a transaction. This method is a wrapper around `sqlite3_get_autocommit()`." }, { "textRaw": "Type: {Object}", "name": "limits", "type": "Object", "meta": { "added": [ "v25.8.0" ], "changes": [] }, "desc": "An object for getting and setting SQLite database limits at runtime.\nEach property corresponds to an SQLite limit and can be read or written.
\nconst db = new DatabaseSync(':memory:');\n\n// Read current limit\nconsole.log(db.limits.length);\n\n// Set a new limit\ndb.limits.sqlLength = 100000;\n\n// Reset a limit to its compile-time maximum\ndb.limits.sqlLength = Infinity;\n\nAvailable properties: length, sqlLength, column, exprDepth,\ncompoundSelect, vdbeOp, functionArg, attach, likePatternLength,\nvariableNumber, triggerDepth.
Setting a property to Infinity resets the limit to its compile-time maximum value.
Retrieves a changeset containing all changes since the changeset was created. Can be called multiple times.\nAn exception is thrown if the database or the session is not open. This method is a wrapper around sqlite3session_changeset().
Similar to the method above, but generates a more compact patchset. See Changesets and Patchsets\nin the documentation of SQLite. An exception is thrown if the database or the session is not open. This method is a\nwrapper around sqlite3session_patchset().
Closes the session. An exception is thrown if the database or the session is not open. This method is a\nwrapper around sqlite3session_delete().
Closes the session. If the session is already closed, does nothing.
" } ] }, { "textRaw": "Class: `StatementSync`", "name": "StatementSync", "type": "class", "meta": { "added": [ "v22.5.0" ], "changes": [] }, "desc": "This class represents a single prepared statement. This class cannot be\ninstantiated via its constructor. Instead, instances are created via the\ndatabase.prepare() method. All APIs exposed by this class execute\nsynchronously.
A prepared statement is an efficient binary representation of the SQL used to\ncreate it. Prepared statements are parameterizable, and can be invoked multiple\ntimes with different bound values. Parameters also offer protection against\nSQL injection attacks. For these reasons, prepared statements are preferred\nover hand-crafted SQL strings when handling user input.
", "methods": [ { "textRaw": "`statement.all([namedParameters][, ...anonymousParameters])`", "name": "all", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56385", "description": "Add support for `DataView` and typed array objects for `anonymousParameters`." } ] }, "signatures": [ { "params": [ { "textRaw": "`namedParameters` {Object} An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "name": "namedParameters", "type": "Object", "desc": "An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "optional": true }, { "textRaw": "`...anonymousParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Zero or more values to bind to anonymous parameters.", "name": "...anonymousParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Zero or more values to bind to anonymous parameters.", "optional": true } ], "return": { "textRaw": "Returns: {Array} An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row.", "name": "return", "type": "Array", "desc": "An array of objects. Each object corresponds to a row returned by executing the prepared statement. The keys and values of each object correspond to the column names and values of the row." } } ], "desc": "This method executes a prepared statement and returns all results as an array of\nobjects. If the prepared statement does not return any results, this method\nreturns an empty array. The prepared statement parameters are bound using\nthe values in namedParameters and anonymousParameters.
This method is used to retrieve information about the columns returned by the\nprepared statement.
" }, { "textRaw": "`statement.get([namedParameters][, ...anonymousParameters])`", "name": "get", "type": "method", "meta": { "added": [ "v22.5.0" ], "changes": [ { "version": [ "v23.7.0", "v22.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/56385", "description": "Add support for `DataView` and typed array objects for `anonymousParameters`." } ] }, "signatures": [ { "params": [ { "textRaw": "`namedParameters` {Object} An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "name": "namedParameters", "type": "Object", "desc": "An optional object used to bind named parameters. The keys of this object are used to configure the mapping.", "optional": true }, { "textRaw": "`...anonymousParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Zero or more values to bind to anonymous parameters.", "name": "...anonymousParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Zero or more values to bind to anonymous parameters.", "optional": true } ], "return": { "textRaw": "Returns: {Object|undefined} An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no rows were returned from the database then this method returns `undefined`.", "name": "return", "type": "Object|undefined", "desc": "An object corresponding to the first row returned by executing the prepared statement. The keys and values of the object correspond to the column names and values of the row. If no rows were returned from the database then this method returns `undefined`." } } ], "desc": "This method executes a prepared statement and returns the first result as an\nobject. If the prepared statement does not return any results, this method\nreturns undefined. The prepared statement parameters are bound using the\nvalues in namedParameters and anonymousParameters.
This method executes a prepared statement and returns an iterator of\nobjects. If the prepared statement does not return any results, this method\nreturns an empty iterator. The prepared statement parameters are bound using\nthe values in namedParameters and anonymousParameters.
This method executes a prepared statement and returns an object summarizing the\nresulting changes. The prepared statement parameters are bound using the\nvalues in namedParameters and anonymousParameters.
The names of SQLite parameters begin with a prefix character. By default,\nnode:sqlite requires that this prefix character is present when binding\nparameters. However, with the exception of dollar sign character, these\nprefix characters also require extra quoting when used in object keys.
To improve ergonomics, this method can be used to also allow bare named\nparameters, which do not require the prefix character in JavaScript code. There\nare several caveats to be aware of when enabling bare named parameters:
\n$k and @k, in the same prepared\nstatement will result in an exception as it cannot be determined how to bind\na bare name.By default, if an unknown name is encountered while binding parameters, an\nexception is thrown. This method allows unknown named parameters to be ignored.
" }, { "textRaw": "`statement.setReturnArrays(enabled)`", "name": "setReturnArrays", "type": "method", "meta": { "added": [ "v24.0.0", "v22.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enabled` {boolean} Enables or disables the return of query results as arrays.", "name": "enabled", "type": "boolean", "desc": "Enables or disables the return of query results as arrays." } ] } ], "desc": "When enabled, query results returned by the all(), get(), and iterate() methods will be returned as arrays instead\nof objects.
When reading from the database, SQLite INTEGERs are mapped to JavaScript\nnumbers by default. However, SQLite INTEGERs can store values larger than\nJavaScript numbers are capable of representing. In such cases, this method can\nbe used to read INTEGER data using JavaScript BigInts. This method has no\nimpact on database write operations where numbers and BigInts are both\nsupported at all times.
The source SQL text of the prepared statement with parameter\nplaceholders replaced by the values that were used during the most recent\nexecution of this prepared statement. This property is a wrapper around\nsqlite3_expanded_sql().
The source SQL text of the prepared statement. This property is a\nwrapper around sqlite3_sql().
This class represents a single LRU (Least Recently Used) cache for storing\nprepared statements.
\nInstances of this class are created via the database.createTagStore()\nmethod, not by using a constructor. The store caches prepared statements based\non the provided SQL query string. When the same query is seen again, the store\nretrieves the cached statement and safely applies the new values through\nparameter binding, thereby preventing attacks like SQL injection.
The cache has a maxSize that defaults to 1000 statements, but a custom size can\nbe provided (e.g., database.createTagStore(100)). All APIs exposed by this\nclass execute synchronously.
Executes the given SQL query and returns all resulting rows as an array of\nobjects.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.get(stringElements[, ...boundParameters])`", "name": "get", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Object|undefined} An object representing the first row returned by the query, or `undefined` if no rows are returned.", "name": "return", "type": "Object|undefined", "desc": "An object representing the first row returned by the query, or `undefined` if no rows are returned." } } ], "desc": "Executes the given SQL query and returns the first resulting row as an object.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.iterate(stringElements[, ...boundParameters])`", "name": "iterate", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Iterator} An iterator that yields objects representing the rows returned by the query.", "name": "return", "type": "Iterator", "desc": "An iterator that yields objects representing the rows returned by the query." } } ], "desc": "Executes the given SQL query and returns an iterator over the resulting rows.
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.run(stringElements[, ...boundParameters])`", "name": "run", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stringElements` {string[]} Template literal elements containing the SQL query.", "name": "stringElements", "type": "string[]", "desc": "Template literal elements containing the SQL query." }, { "textRaw": "`...boundParameters` {null|number|bigint|string|Buffer|TypedArray|DataView} Parameter values to be bound to placeholders in the template string.", "name": "...boundParameters", "type": "null|number|bigint|string|Buffer|TypedArray|DataView", "desc": "Parameter values to be bound to placeholders in the template string.", "optional": true } ], "return": { "textRaw": "Returns: {Object} An object containing information about the execution, including `changes` and `lastInsertRowid`.", "name": "return", "type": "Object", "desc": "An object containing information about the execution, including `changes` and `lastInsertRowid`." } } ], "desc": "Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).
\nThis function is intended to be used as a template literal tag, not to be\ncalled directly.
" }, { "textRaw": "`sqlTagStore.clear()`", "name": "clear", "type": "method", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "Resets the LRU cache, clearing all stored prepared statements.
" } ], "properties": [ { "textRaw": "Type: {integer}", "name": "size", "type": "integer", "meta": { "added": [ "v24.9.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/60246", "description": "Changed from a method to a getter." } ] }, "desc": "A read-only property that returns the number of prepared statements currently in the cache.
" }, { "textRaw": "Type: {integer}", "name": "capacity", "type": "integer", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "desc": "A read-only property that returns the maximum number of prepared statements the cache can hold.
" }, { "textRaw": "Type: {DatabaseSync}", "name": "db", "type": "DatabaseSync", "meta": { "added": [ "v24.9.0" ], "changes": [] }, "desc": "A read-only property that returns the DatabaseSync object associated with this SQLTagStore.
When Node.js writes to or reads from SQLite, it is necessary to convert between\nJavaScript data types and SQLite's data types. Because JavaScript supports\nmore data types than SQLite, only a subset of JavaScript types are supported.\nAttempting to write an unsupported data type to SQLite will result in an\nexception.
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n| Storage class | JavaScript to SQLite | SQLite to JavaScript |
|---|---|---|
NULL | <null> | <null> |
INTEGER | <number> or <bigint> | <number> or <bigint> (configurable) |
REAL | <number> | <number> |
TEXT | <string> | <string> |
BLOB | <TypedArray> or <DataView> | <Uint8Array> |
APIs that read values from SQLite have a configuration option that determines\nwhether INTEGER values are converted to number or bigint in JavaScript,\nsuch as the readBigInts option for statements and the useBigIntArguments\noption for user-defined functions. If Node.js reads an INTEGER value from\nSQLite that is outside the JavaScript safe integer range, and the option to\nread BigInts is not enabled, then an ERR_OUT_OF_RANGE error will be thrown.
This method makes a database backup. This method abstracts the sqlite3_backup_init(), sqlite3_backup_step()\nand sqlite3_backup_finish() functions.
The backed-up database can be used normally during the backup process. Mutations coming from the same connection - same\n<DatabaseSync> - object will be reflected in the backup right away. However, mutations from other connections will cause\nthe backup process to restart.
const { backup, DatabaseSync } = require('node:sqlite');\n\n(async () => {\n const sourceDb = new DatabaseSync('source.db');\n const totalPagesTransferred = await backup(sourceDb, 'backup.db', {\n rate: 1, // Copy one page at a time.\n progress: ({ totalPages, remainingPages }) => {\n console.log('Backup in progress', { totalPages, remainingPages });\n },\n });\n\n console.log('Backup completed', totalPagesTransferred);\n})();\n\nimport { backup, DatabaseSync } from 'node:sqlite';\n\nconst sourceDb = new DatabaseSync('source.db');\nconst totalPagesTransferred = await backup(sourceDb, 'backup.db', {\n rate: 1, // Copy one page at a time.\n progress: ({ totalPages, remainingPages }) => {\n console.log('Backup in progress', { totalPages, remainingPages });\n },\n});\n\nconsole.log('Backup completed', totalPagesTransferred);\n"
}
],
"properties": [
{
"textRaw": "Type: {Object}",
"name": "constants",
"type": "Object",
"meta": {
"added": [
"v23.5.0",
"v22.13.0"
],
"changes": []
},
"desc": "An object containing commonly used constants for SQLite operations.
", "modules": [ { "textRaw": "SQLite constants", "name": "sqlite_constants", "type": "module", "desc": "The following constants are exported by the sqlite.constants object.
One of the following constants is available as an argument to the onConflict\nconflict resolution handler passed to database.applyChangeset(). See also\nConstants Passed To The Conflict Handler in the SQLite documentation.
| Constant | Description |
|---|---|
SQLITE_CHANGESET_DATA | The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is present in the database, but one or more other (non primary-key) fields modified by the update do not contain the expected \"before\" values. |
SQLITE_CHANGESET_NOTFOUND | The conflict handler is invoked with this constant when processing a DELETE or UPDATE change if a row with the required PRIMARY KEY fields is not present in the database. |
SQLITE_CHANGESET_CONFLICT | This constant is passed to the conflict handler while processing an INSERT change if the operation would result in duplicate primary key values. |
SQLITE_CHANGESET_CONSTRAINT | If foreign key handling is enabled, and applying a changeset leaves the database in a state containing foreign key violations, the conflict handler is invoked with this constant exactly once before the changeset is committed. If the conflict handler returns SQLITE_CHANGESET_OMIT, the changes, including those that caused the foreign key constraint violation, are committed. Or, if it returns SQLITE_CHANGESET_ABORT, the changeset is rolled back. |
SQLITE_CHANGESET_FOREIGN_KEY | If any other constraint violation occurs while applying a change (i.e. a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is invoked with this constant. |
One of the following constants must be returned from the onConflict conflict\nresolution handler passed to database.applyChangeset(). See also\nConstants Returned From The Conflict Handler in the SQLite documentation.
| Constant | Description |
|---|---|
SQLITE_CHANGESET_OMIT | Conflicting changes are omitted. |
SQLITE_CHANGESET_REPLACE | Conflicting changes replace existing values. Note that this value can only be returned when the type of conflict is either SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. |
SQLITE_CHANGESET_ABORT | Abort when a change encounters a conflict and roll back database. |
The following constants are used with the database.setAuthorizer() method.
One of the following constants must be returned from the authorizer callback\nfunction passed to database.setAuthorizer().
| Constant | Description |
|---|---|
SQLITE_OK | Allow the operation to proceed normally. |
SQLITE_DENY | Deny the operation and cause an error to be returned. |
SQLITE_IGNORE | Ignore the operation and continue as if it had never been requested. |
The following constants are passed as the first argument to the authorizer\ncallback function to indicate what type of operation is being authorized.
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n| Constant | Description |
|---|---|
SQLITE_CREATE_INDEX | Create an index |
SQLITE_CREATE_TABLE | Create a table |
SQLITE_CREATE_TEMP_INDEX | Create a temporary index |
SQLITE_CREATE_TEMP_TABLE | Create a temporary table |
SQLITE_CREATE_TEMP_TRIGGER | Create a temporary trigger |
SQLITE_CREATE_TEMP_VIEW | Create a temporary view |
SQLITE_CREATE_TRIGGER | Create a trigger |
SQLITE_CREATE_VIEW | Create a view |
SQLITE_DELETE | Delete from a table |
SQLITE_DROP_INDEX | Drop an index |
SQLITE_DROP_TABLE | Drop a table |
SQLITE_DROP_TEMP_INDEX | Drop a temporary index |
SQLITE_DROP_TEMP_TABLE | Drop a temporary table |
SQLITE_DROP_TEMP_TRIGGER | Drop a temporary trigger |
SQLITE_DROP_TEMP_VIEW | Drop a temporary view |
SQLITE_DROP_TRIGGER | Drop a trigger |
SQLITE_DROP_VIEW | Drop a view |
SQLITE_INSERT | Insert into a table |
SQLITE_PRAGMA | Execute a PRAGMA statement |
SQLITE_READ | Read from a table |
SQLITE_SELECT | Execute a SELECT statement |
SQLITE_TRANSACTION | Begin, commit, or rollback a transaction |
SQLITE_UPDATE | Update a table |
SQLITE_ATTACH | Attach a database |
SQLITE_DETACH | Detach a database |
SQLITE_ALTER_TABLE | Alter a table |
SQLITE_REINDEX | Reindex |
SQLITE_ANALYZE | Analyze the database |
SQLITE_CREATE_VTABLE | Create a virtual table |
SQLITE_DROP_VTABLE | Drop a virtual table |
SQLITE_FUNCTION | Use a function |
SQLITE_SAVEPOINT | Create, release, or rollback a savepoint |
SQLITE_COPY | Copy data (legacy) |
SQLITE_RECURSIVE | Recursive query |
A stream is an abstract interface for working with streaming data in Node.js.\nThe node:stream module provides an API for implementing the stream interface.
There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.
Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.
To access the node:stream module:
const stream = require('node:stream');\n\nThe node:stream module is useful for creating new types of stream instances.\nIt is usually not necessary to use the node:stream module to consume streams.
This document contains two primary sections and a third section for notes. The\nfirst section explains how to use existing streams within an application. The\nsecond section explains how to create new types of streams.
", "displayName": "Organization of this document" }, { "textRaw": "Types of streams", "name": "types_of_streams", "type": "module", "desc": "There are four fundamental stream types within Node.js:
\nWritable: streams to which data can be written (for example,\nfs.createWriteStream()).Readable: streams from which data can be read (for example,\nfs.createReadStream()).Duplex: streams that are both Readable and Writable (for example,\nnet.Socket).Transform: Duplex streams that can modify or transform the data as it\nis written and read (for example, zlib.createDeflate()).Additionally, this module includes the utility functions\nstream.duplexPair(),\nstream.pipeline(),\nstream.finished()\nstream.Readable.from(), and\nstream.addAbortSignal().
The stream/promises API provides an alternative set of asynchronous utility\nfunctions for streams that return Promise objects rather than using\ncallbacks. The API is accessible via require('node:stream/promises')\nor require('node:stream').promises.
All streams created by Node.js APIs operate exclusively on strings, <Buffer>,\n<TypedArray> and <DataView> objects:
Strings and Buffers are the most common types used with streams.TypedArray and DataView lets you handle binary data with types like\nInt32Array or Uint8Array. When you write a TypedArray or DataView to a\nstream, Node.js processes\nthe raw bytes.It is possible, however, for stream\nimplementations to work with other types of JavaScript values (with the\nexception of null, which serves a special purpose within streams).\nSuch streams are considered to operate in \"object mode\".
Stream instances are switched into object mode using the objectMode option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nawait pipeline(\n createReadStream('archive.tar'),\n createGzip(),\n createWriteStream('archive.tar.gz'),\n);\nconsole.log('Pipeline succeeded.');\n\nTo use an AbortSignal, pass it inside an options object, as the last argument.\nWhen the signal is aborted, destroy will be called on the underlying pipeline,\nwith an AbortError.
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n const ac = new AbortController();\n const signal = ac.signal;\n\n setImmediate(() => ac.abort());\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n { signal },\n );\n}\n\nrun().catch(console.error); // AbortError\n\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nconst ac = new AbortController();\nconst { signal } = ac;\nsetImmediate(() => ac.abort());\ntry {\n await pipeline(\n createReadStream('archive.tar'),\n createGzip(),\n createWriteStream('archive.tar.gz'),\n { signal },\n );\n} catch (err) {\n console.error(err); // AbortError\n}\n\nThe pipeline API also supports async generators:
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source, { signal }) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield await processChunk(chunk, { signal });\n }\n },\n fs.createWriteStream('uppercase.txt'),\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\n\nawait pipeline(\n createReadStream('lowercase.txt'),\n async function* (source, { signal }) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield await processChunk(chunk, { signal });\n }\n },\n createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');\n\nRemember to handle the signal argument passed into the async generator.\nEspecially in the case where the async generator is the source for the\npipeline (i.e. first argument) or the pipeline will never complete.
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n await pipeline(\n async function* ({ signal }) {\n await someLongRunningfn({ signal });\n yield 'asd';\n },\n fs.createWriteStream('uppercase.txt'),\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n\nimport { pipeline } from 'node:stream/promises';\nimport fs from 'node:fs';\nawait pipeline(\n async function* ({ signal }) {\n await someLongRunningfn({ signal });\n yield 'asd';\n },\n fs.createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');\n\nThe pipeline API provides callback version:
const { finished } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n await finished(rs);\n console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n\nimport { finished } from 'node:stream/promises';\nimport { createReadStream } from 'node:fs';\n\nconst rs = createReadStream('archive.tar');\n\nasync function run() {\n await finished(rs);\n console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n\nThe finished API also provides a callback version.
stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after the returned promise is\nresolved or rejected. The reason for this is so that unexpected 'error'\nevents (due to incorrect stream implementations) do not cause unexpected\ncrashes. If this is unwanted behavior then options.cleanup should be set to\ntrue:
await finished(rs, { cleanup: true });\n"
}
],
"miscs": [
{
"textRaw": "Buffering",
"name": "Buffering",
"type": "misc",
"desc": "Both Writable and Readable streams will store data in an internal\nbuffer.
The amount of data potentially buffered depends on the highWaterMark option\npassed into the stream's constructor. For normal streams, the highWaterMark\noption specifies a total number of bytes. For streams operating\nin object mode, the highWaterMark specifies a total number of objects. For\nstreams operating on (but not decoding) strings, the highWaterMark specifies\na total number of UTF-16 code units.
Data is buffered in Readable streams when the implementation calls\nstream.push(chunk). If the consumer of the Stream does not\ncall stream.read(), the data will sit in the internal\nqueue until it is consumed.
Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read() method that is\nused to fill the read buffer).
Data is buffered in Writable streams when the\nwritable.write(chunk) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark, calls to writable.write() will return true. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark, false\nwill be returned.
A key goal of the stream API, particularly the stream.pipe() method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.
The highWaterMark option is a threshold, not a limit: it dictates the amount\nof data that a stream buffers before it stops asking for more data. It does not\nenforce a strict memory limitation in general. Specific stream implementations\nmay choose to enforce stricter limits but doing so is optional.
Because Duplex and Transform streams are both Readable and\nWritable, each maintains two separate internal buffers used for reading and\nwriting, allowing each side to operate independently of the other while\nmaintaining an appropriate and efficient flow of data. For example,\nnet.Socket instances are Duplex streams whose Readable side allows\nconsumption of data received from the socket and whose Writable side allows\nwriting data to the socket. Because data may be written to the socket at a\nfaster or slower rate than data is received, each side should\noperate (and buffer) independently of the other.
The mechanics of the internal buffering are an internal implementation detail\nand may be changed at any time. However, for certain advanced implementations,\nthe internal buffers can be retrieved using writable.writableBuffer or\nreadable.readableBuffer. Use of these undocumented properties is discouraged.
Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:
\nconst http = require('node:http');\n\nconst server = http.createServer((req, res) => {\n // `req` is an http.IncomingMessage, which is a readable stream.\n // `res` is an http.ServerResponse, which is a writable stream.\n\n let body = '';\n // Get the data as utf8 strings.\n // If an encoding is not set, Buffer objects will be received.\n req.setEncoding('utf8');\n\n // Readable streams emit 'data' events once a listener is added.\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n // The 'end' event indicates that the entire body has been received.\n req.on('end', () => {\n try {\n const data = JSON.parse(body);\n // Write back something interesting to the user:\n res.write(typeof data);\n res.end();\n } catch (er) {\n // uh oh! bad json!\n res.statusCode = 400;\n return res.end(`error: ${er.message}`);\n }\n });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token 'o', \"not json\" is not valid JSON\n\nWritable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.
Readable streams use the EventEmitter API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.
Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.
Duplex and Transform streams are both Writable and\nReadable.
Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('node:stream').
Developers wishing to implement new types of streams should refer to the\nsection API for stream implementers.
", "miscs": [ { "textRaw": "Writable streams", "name": "writable_streams", "type": "misc", "desc": "Writable streams are an abstraction for a destination to which data is\nwritten.
\nExamples of Writable streams include:
process.stdout, process.stderrSome of these examples are actually Duplex streams that implement the\nWritable interface.
All Writable streams implement the interface defined by the\nstream.Writable class.
While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:
const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n",
"classes": [
{
"textRaw": "Class: `stream.Writable`",
"name": "stream.Writable",
"type": "class",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"events": [
{
"textRaw": "Event: `'close'`",
"name": "close",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18438",
"description": "Add `emitClose` option to specify if `'close'` is emitted on destroy."
}
]
},
"params": [],
"desc": "The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.
A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.
If a call to stream.write(chunk) returns false, the\n'drain' event will be emitted when it is appropriate to resume writing data\nto the stream.
// Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n let i = 1000000;\n write();\n function write() {\n let ok = true;\n do {\n i--;\n if (i === 0) {\n // Last time!\n writer.write(data, encoding, callback);\n } else {\n // See if we should continue, or wait.\n // Don't pass the callback, because we're not done yet.\n ok = writer.write(data, encoding);\n }\n } while (i > 0 && ok);\n if (i > 0) {\n // Had to stop early!\n // Write some more once it drains.\n writer.once('drain', write);\n }\n }\n}\n"
},
{
"textRaw": "Event: `'error'`",
"name": "error",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"params": [
{
"textRaw": "Type: {Error}",
"name": "type",
"type": "Error"
}
],
"desc": "The 'error' event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error argument when called.
The stream is closed when the 'error' event is emitted unless the\nautoDestroy option was set to false when creating the\nstream.
After 'error', no further events other than 'close' should be emitted\n(including 'error' events).
The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.
const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');\n"
},
{
"textRaw": "Event: `'pipe'`",
"name": "pipe",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"params": [
{
"textRaw": "`src` {stream.Readable} source stream that is piping to this writable",
"name": "src",
"type": "stream.Readable",
"desc": "source stream that is piping to this writable"
}
],
"desc": "The 'pipe' event is emitted when the stream.pipe() method is called on\na readable stream, adding this writable to its set of destinations.
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n console.log('Something is piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\n"
},
{
"textRaw": "Event: `'unpipe'`",
"name": "unpipe",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"params": [
{
"textRaw": "`src` {stream.Readable} The source stream that unpiped this writable",
"name": "src",
"type": "stream.Readable",
"desc": "The source stream that unpiped this writable"
}
],
"desc": "The 'unpipe' event is emitted when the stream.unpipe() method is called\non a Readable stream, removing this Writable from its set of\ndestinations.
This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n console.log('Something has stopped piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n"
}
],
"methods": [
{
"textRaw": "`writable.cork()`",
"name": "cork",
"type": "method",
"meta": {
"added": [
"v0.11.2"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "The writable.cork() method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork() or\nstream.end() methods are called.
The primary intent of writable.cork() is to accommodate a situation in which\nseveral small chunks are written to the stream in rapid succession. Instead of\nimmediately forwarding them to the underlying destination, writable.cork()\nbuffers all the chunks until writable.uncork() is called, which will pass them\nall to writable._writev(), if present. This prevents a head-of-line blocking\nsituation where data is being buffered while waiting for the first small chunk\nto be processed. However, use of writable.cork() without implementing\nwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the writable\nstream has ended and subsequent calls to write() or end() will result in\nan ERR_STREAM_DESTROYED error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\nwrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.\nUse end() instead of destroy if data should flush before close, or wait for\nthe 'drain' event before destroying the stream.
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconst fooErr = new Error('foo error');\nmyStream.destroy(fooErr);\nmyStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error\n\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});\n\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED\n\nOnce destroy() has been called any further calls will be a no-op and no\nfurther errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method,\nbut instead implement writable._destroy().
Calling the writable.end() method signals that no more data will be written\nto the Writable. The optional chunk and encoding arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream.
Calling the stream.write() method after calling\nstream.end() will raise an error.
// Write 'hello, ' and then end with 'world!'.\nconst fs = require('node:fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n"
},
{
"textRaw": "`writable.setDefaultEncoding(encoding)`",
"name": "setDefaultEncoding",
"type": "method",
"meta": {
"added": [
"v0.11.15"
],
"changes": [
{
"version": "v6.1.0",
"pr-url": "https://github.com/nodejs/node/pull/5040",
"description": "This method now returns a reference to `writable`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`encoding` {string} The new default encoding",
"name": "encoding",
"type": "string",
"desc": "The new default encoding"
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.
The writable.uncork() method flushes all data buffered since\nstream.cork() was called.
When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, defer calls to writable.uncork() using\nprocess.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.
stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n\nIf the writable.cork() method is called multiple times on a stream, the\nsame number of calls to writable.uncork() must be called to flush the buffered\ndata.
stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n stream.uncork();\n // The data will not be flushed until uncork() is called a second time.\n stream.uncork();\n});\n\nSee also: writable.cork().
Calls writable.destroy() with an AbortError and returns\na promise that fulfills when the stream is finished.
The writable.write() method writes some data to the stream, and calls the\nsupplied callback once the data has been fully handled. If an error\noccurs, the callback will be called with the error as its\nfirst argument. The callback is called asynchronously and before 'error' is\nemitted.
The return value is true if the internal buffer is less than the\nhighWaterMark configured when the stream was created after admitting chunk.\nIf false is returned, further attempts to write data to the stream should\nstop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain' event will be emitted.\nOnce write() returns false, do not write more chunks\nuntil the 'drain' event is emitted. While calling write() on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform streams are paused\nby default until they are piped or a 'data' or 'readable' event handler\nis added.
If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe(). However, if calling write() is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n'drain' event:
function write(data, cb) {\n if (!stream.write(data)) {\n stream.once('drain', cb);\n } else {\n process.nextTick(cb);\n }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n console.log('Write completed, do more writes now.');\n});\n\nA Writable stream in object mode will always ignore the encoding argument.
Is true after 'close' has been emitted.
Is true after writable.destroy() has been called.
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true\n"
},
{
"textRaw": "Type: {boolean}",
"name": "writable",
"type": "boolean",
"meta": {
"added": [
"v11.4.0"
],
"changes": []
},
"desc": "Is true if it is safe to call writable.write(), which means\nthe stream has not been destroyed, errored, or ended.
Returns whether the stream was destroyed or errored before emitting 'finish'.
Is true after writable.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.
Number of times writable.uncork() needs to be\ncalled in order to fully uncork the stream.
Returns error if the stream has been destroyed with an error.
" }, { "textRaw": "Type: {boolean}", "name": "writableFinished", "type": "boolean", "meta": { "added": [ "v12.6.0" ], "changes": [] }, "desc": "Is set to true immediately before the 'finish' event is emitted.
Return the value of highWaterMark passed when creating this Writable.
This property contains the number of bytes (or objects) in the queue\nready to be written. The value provides introspection data regarding\nthe status of the highWaterMark.
Is true if the stream's buffer has been full and stream will emit 'drain'.
Getter for the property objectMode of a given Writable stream.
Readable streams are an abstraction for a source from which data is\nconsumed.
\nExamples of Readable streams include:
process.stdinAll Readable streams implement the interface defined by the\nstream.Readable class.
Readable streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from object mode.\nA Readable stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.
In flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\nEventEmitter interface.
In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.
All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:
'data' event handler.stream.resume() method.stream.pipe() method to send the data to a Writable.The Readable can switch back to paused mode using one of the following:
stream.pause() method.stream.unpipe() method.The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.
For backward compatibility reasons, removing 'data' event handlers will\nnot automatically pause the stream. Also, if there are piped destinations,\nthen calling stream.pause() will not guarantee that the\nstream will remain paused once those destinations drain and ask for more data.
If a Readable is switched into flowing mode and there are no consumers\navailable to handle the data, that data will be lost. This can occur, for\ninstance, when the readable.resume() method is called without a listener\nattached to the 'data' event, or when a 'data' event handler is removed\nfrom the stream.
Adding a 'readable' event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\nreadable.read(). If the 'readable' event handler is\nremoved, then the stream will start flowing again if there is a\n'data' event handler.
The \"two modes\" of operation for a Readable stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the Readable stream implementation.
Specifically, at any given point in time, every Readable is in one of three\npossible states:
readable.readableFlowing === nullreadable.readableFlowing === falsereadable.readableFlowing === trueWhen readable.readableFlowing is null, no mechanism for consuming the\nstream's data is provided. Therefore, the stream will not generate data.\nWhile in this state, attaching a listener for the 'data' event, calling the\nreadable.pipe() method, or calling the readable.resume() method will switch\nreadable.readableFlowing to true, causing the Readable to begin actively\nemitting events as data is generated.
Calling readable.pause(), readable.unpipe(), or receiving backpressure\nwill cause the readable.readableFlowing to be set as false,\ntemporarily halting the flowing of events but not halting the generation of\ndata. While in this state, attaching a listener for the 'data' event\nwill not switch readable.readableFlowing to true.
const { PassThrough, Writable } = require('node:stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false.\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\n// readableFlowing is still false.\npass.write('ok'); // Will not emit 'data'.\npass.resume(); // Must be called to make stream emit 'data'.\n// readableFlowing is now true.\n\nWhile readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.
The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof on('data'), on('readable'), pipe(), or async iterators could\nlead to unintuitive behavior.
The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.
A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.
The 'data' event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe(), readable.resume(), or by\nattaching a listener callback to the 'data' event. The 'data' event will\nalso be emitted whenever the readable.read() method is called and a chunk of\ndata is available to be returned.
Attaching a 'data' event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.
The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding() method; otherwise the data will be passed as a\nBuffer.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\n"
},
{
"textRaw": "Event: `'end'`",
"name": "end",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"params": [],
"desc": "The 'end' event is emitted when there is no more data to be consumed from\nthe stream.
The 'end' event will not be emitted unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling stream.read() repeatedly until all data has been\nconsumed.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n console.log('There will be no more data.');\n});\n"
},
{
"textRaw": "Event: `'error'`",
"name": "error",
"type": "event",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"params": [
{
"textRaw": "Type: {Error}",
"name": "type",
"type": "Error"
}
],
"desc": "The 'error' event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream is unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.
The listener callback will be passed a single Error object.
The 'pause' event is emitted when stream.pause() is called\nand readableFlowing is not false.
The 'readable' event is emitted when there is data available to be read from\nthe stream, up to the configured high water mark (state.highWaterMark). Effectively,\nit indicates that the stream has new information within the buffer. If data is available\nwithin this buffer, stream.read() can be called to retrieve that data.\nAdditionally, the 'readable' event may also be emitted when the end of the stream has been\nreached.
const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n // There is some data to read now.\n let data;\n\n while ((data = this.read()) !== null) {\n console.log(data);\n }\n});\n\nIf the end of the stream has been reached, calling\nstream.read() will return null and trigger the 'end'\nevent. This is also true if there never was any data to be read. For instance,\nin the following example, foo.txt is an empty file:
const fs = require('node:fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n console.log('end');\n});\n\nThe output of running this script is:
\n$ node test.js\nreadable: null\nend\n\nIn some cases, attaching a listener for the 'readable' event will cause some\namount of data to be read into an internal buffer.
In general, the readable.pipe() and 'data' event mechanisms are easier to\nunderstand than the 'readable' event. However, handling 'readable' might\nresult in increased throughput.
If both 'readable' and 'data' are used at the same time, 'readable'\ntakes precedence in controlling the flow, i.e. 'data' will be emitted\nonly when stream.read() is called. The\nreadableFlowing property would become false.\nIf there are 'data' listeners when 'readable' is removed, the stream\nwill start flowing, i.e. 'data' events will be emitted without calling\n.resume().
The 'resume' event is emitted when stream.resume() is\ncalled and readableFlowing is not true.
Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the readable\nstream will release any internal resources and subsequent calls to push()\nwill be ignored.
Once destroy() has been called any further calls will be a no-op and no\nfurther errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement\nreadable._destroy().
The readable.isPaused() method returns the current operating state of the\nReadable. This is used primarily by the mechanism that underlies the\nreadable.pipe() method. In most typical cases, there will be no reason to\nuse this method directly.
const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n"
},
{
"textRaw": "`readable.pause()`",
"name": "pause",
"type": "method",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "The readable.pause() method will cause a stream in flowing mode to stop\nemitting 'data' events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n readable.pause();\n console.log('There will be no additional data for 1 second.');\n setTimeout(() => {\n console.log('Now data will start flowing again.');\n readable.resume();\n }, 1000);\n});\n\nThe readable.pause() method has no effect if there is a 'readable'\nevent listener.
The readable.pipe() method attaches a Writable stream to the readable,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed\nso that the destination Writable stream is not overwhelmed by a faster\nReadable stream.
The following example pipes all of the data from the readable into a file\nnamed file.txt:
const fs = require('node:fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n\nIt is possible to attach multiple Writable streams to a single Readable\nstream.
The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:
const fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n\nBy default, stream.end() is called on the destination Writable\nstream when the source Readable stream emits 'end', so that the\ndestination is no longer writable. To disable this default behavior, the end\noption can be passed as false, causing the destination stream to remain open:
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n writer.end('Goodbye\\n');\n});\n\nOne important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.
The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.
The readable.read() method reads data out of the internal buffer and\nreturns it. If no data is available to be read, null is returned. By default,\nthe data is returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.
The optional size argument specifies a specific number of bytes to read. If\nsize bytes are not available to be read, null will be returned unless\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.
If the size argument is not specified, all of the data contained in the\ninternal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams\noperating in paused mode. In flowing mode, readable.read() is called\nautomatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n let chunk;\n console.log('Stream is readable (new data received in buffer)');\n // Use a loop to make sure we read all currently available data\n while (null !== (chunk = readable.read())) {\n console.log(`Read ${chunk.length} bytes of data...`);\n }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n console.log('Reached end of stream.');\n});\n\nEach call to readable.read() returns a chunk of data or null, signifying\nthat there's no more data to read at that moment. These chunks aren't automatically\nconcatenated. Because a single read() call does not return all the data, using\na while loop may be necessary to continuously read chunks until all data is retrieved.\nWhen reading a large file, .read() might return null temporarily, indicating\nthat it has consumed all buffered content but there may be more data yet to be\nbuffered. In such cases, a new 'readable' event is emitted once there's more\ndata in the buffer, and the 'end' event signifies the end of data transmission.
Therefore to read a file's whole contents from a readable, it is necessary\nto collect chunks across multiple 'readable' events:
const chunks = [];\n\nreadable.on('readable', () => {\n let chunk;\n while (null !== (chunk = readable.read())) {\n chunks.push(chunk);\n }\n});\n\nreadable.on('end', () => {\n const content = chunks.join('');\n});\n\nA Readable stream in object mode will always return a single item from\na call to readable.read(size), regardless of the value of the\nsize argument.
If the readable.read() method returns a chunk of data, a 'data' event will\nalso be emitted.
Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.
The readable.resume() method causes an explicitly paused Readable stream to\nresume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a\nstream without actually processing any of that data:
getReadableStreamSomehow()\n .resume()\n .on('end', () => {\n console.log('Reached the end, but did not read anything.');\n });\n\nThe readable.resume() method has no effect if there is a 'readable'\nevent listener.
The readable.setEncoding() method sets the character encoding for\ndata read from the Readable stream.
By default, no encoding is assigned and stream data will be returned as\nBuffer objects. Setting an encoding causes the stream data\nto be returned as strings of the specified encoding rather than as Buffer\nobjects. For instance, calling readable.setEncoding('utf8') will cause the\noutput data to be interpreted as UTF-8 data, and passed as strings. Calling\nreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal\nstring format.
The Readable stream will properly handle multi-byte characters delivered\nthrough the stream that would otherwise become improperly decoded if simply\npulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n assert.equal(typeof chunk, 'string');\n console.log('Got %d characters of string data:', chunk.length);\n});\n"
},
{
"textRaw": "`readable.unpipe([destination])`",
"name": "unpipe",
"type": "method",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe",
"name": "destination",
"type": "stream.Writable",
"desc": "Optional specific stream to unpipe",
"optional": true
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "The readable.unpipe() method detaches a Writable stream previously attached\nusing the stream.pipe() method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then\nthe method does nothing.
const fs = require('node:fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second.\nreadable.pipe(writable);\nsetTimeout(() => {\n console.log('Stop writing to file.txt.');\n readable.unpipe(writable);\n console.log('Manually close the file stream.');\n writable.end();\n}, 1000);\n"
},
{
"textRaw": "`readable.unshift(chunk[, encoding])`",
"name": "unshift",
"type": "method",
"meta": {
"added": [
"v0.9.11"
],
"changes": [
{
"version": [
"v22.0.0",
"v20.13.0"
],
"pr-url": "https://github.com/nodejs/node/pull/51866",
"description": "The `chunk` argument can now be a `TypedArray` or `DataView` instance."
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/11608",
"description": "The `chunk` argument can now be a `Uint8Array` instance."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`chunk` {Buffer|TypedArray|DataView|string|null|any} Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value.",
"name": "chunk",
"type": "Buffer|TypedArray|DataView|string|null|any",
"desc": "Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value."
},
{
"textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.",
"name": "encoding",
"type": "string",
"desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.",
"optional": true
}
]
}
],
"desc": "Passing chunk as null signals the end of the stream (EOF) and behaves the\nsame as readable.push(null), after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.
The readable.unshift() method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to \"un-consume\" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event\nhas been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to\nuse of a Transform stream instead. See the API for stream implementers\nsection for more information.
// Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('node:string_decoder');\nfunction parseHeader(stream, callback) {\n stream.on('error', callback);\n stream.on('readable', onReadable);\n const decoder = new StringDecoder('utf8');\n let header = '';\n function onReadable() {\n let chunk;\n while (null !== (chunk = stream.read())) {\n const str = decoder.write(chunk);\n if (str.includes('\\n\\n')) {\n // Found the header boundary.\n const split = str.split(/\\n\\n/);\n header += split.shift();\n const remaining = split.join('\\n\\n');\n const buf = Buffer.from(remaining, 'utf8');\n stream.removeListener('error', callback);\n // Remove the 'readable' listener before unshifting.\n stream.removeListener('readable', onReadable);\n if (buf.length)\n stream.unshift(buf);\n // Now the body of the message can be read from the stream.\n callback(null, header, stream);\n return;\n }\n // Still reading the header.\n header += str;\n }\n }\n}\n\nUnlike stream.push(chunk), stream.unshift(chunk) will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if readable.unshift() is called during a\nread (i.e. from within a stream._read() implementation on a\ncustom stream). Following the call to readable.unshift() with an immediate\nstream.push('') will reset the reading state appropriately,\nhowever it is best to simply avoid calling readable.unshift() while in the\nprocess of performing a read.
Prior to Node.js 0.10, streams did not implement the entire node:stream\nmodule API as it is currently defined. (See Compatibility for more\ninformation.)
When using an older Node.js library that emits 'data' events and has a\nstream.pause() method that is advisory only, the\nreadable.wrap() method can be used to create a Readable stream that uses\nthe old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.
const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('node:stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n myReader.read(); // etc.\n});\n"
},
{
"textRaw": "`readable[Symbol.asyncIterator]()`",
"name": "[Symbol.asyncIterator]",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": "v11.14.0",
"pr-url": "https://github.com/nodejs/node/pull/26989",
"description": "Symbol.asyncIterator support is no longer experimental."
}
]
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {AsyncIterator} to fully consume the stream.",
"name": "return",
"type": "AsyncIterator",
"desc": "to fully consume the stream."
}
}
],
"desc": "const fs = require('node:fs');\n\nasync function print(readable) {\n readable.setEncoding('utf8');\n let data = '';\n for await (const chunk of readable) {\n data += chunk;\n }\n console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);\n\nIf the loop terminates with a break, return, or a throw, the stream will\nbe destroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the highWaterMark\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64 KiB of data because no highWaterMark option is provided to\nfs.createReadStream().
Calls readable.destroy() with an AbortError and returns\na promise that fulfills when the stream is finished.
import { Readable } from 'node:stream';\n\nasync function* splitToWords(source) {\n for await (const chunk of source) {\n const words = String(chunk).split(' ');\n\n for (const word of words) {\n yield word;\n }\n }\n}\n\nconst wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);\nconst words = await wordsStream.toArray();\n\nconsole.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']\n\nreadable.compose(s) is equivalent to stream.compose(readable, s).
This method also allows for an <AbortSignal> to be provided, which will destroy\nthe composed stream when aborted.
See stream.compose(...streams) for more information.
The iterator created by this method gives users the option to cancel the\ndestruction of the stream if the for await...of loop is exited by return,\nbreak, or throw, or if the iterator should destroy the stream if the stream\nemitted an error during iteration.
const { Readable } = require('node:stream');\n\nasync function printIterator(readable) {\n for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n console.log(chunk); // 1\n break;\n }\n\n console.log(readable.destroyed); // false\n\n for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n console.log(chunk); // Will print 2 and then 3\n }\n\n console.log(readable.destroyed); // True, stream was totally consumed\n}\n\nasync function printSymbolAsyncIterator(readable) {\n for await (const chunk of readable) {\n console.log(chunk); // 1\n break;\n }\n\n console.log(readable.destroyed); // true\n}\n\nasync function showBoth() {\n await printIterator(Readable.from([1, 2, 3]));\n await printSymbolAsyncIterator(Readable.from([1, 2, 3]));\n}\n\nshowBoth();\n"
},
{
"textRaw": "`readable.map(fn[, options])`",
"name": "map",
"type": "method",
"meta": {
"added": [
"v17.4.0",
"v16.14.0"
],
"changes": [
{
"version": [
"v20.7.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49249",
"description": "added `highWaterMark` in options."
}
]
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to map over every chunk in the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to map over every chunk in the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`highWaterMark` {number} how many items to buffer while waiting for user consumption of the mapped items. **Default:** `concurrency * 2 - 1`.",
"name": "highWaterMark",
"type": "number",
"default": "`concurrency * 2 - 1`",
"desc": "how many items to buffer while waiting for user consumption of the mapped items."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Readable} a stream mapped with the function `fn`.",
"name": "return",
"type": "Readable",
"desc": "a stream mapped with the function `fn`."
}
}
],
"desc": "This method allows mapping over the stream. The fn function will be called\nfor every chunk in the stream. If the fn function returns a promise - that\npromise will be awaited before being passed to the result stream.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {\n console.log(chunk); // 2, 4, 6, 8\n}\n// With an asynchronous mapper, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map((domain) => resolver.resolve4(domain), { concurrency: 2 });\nfor await (const result of dnsResults) {\n console.log(result); // Logs the DNS result of resolver.resolve4.\n}\n"
},
{
"textRaw": "`readable.filter(fn[, options])`",
"name": "filter",
"type": "method",
"meta": {
"added": [
"v17.4.0",
"v16.14.0"
],
"changes": [
{
"version": [
"v20.7.0",
"v18.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/49249",
"description": "added `highWaterMark` in options."
}
]
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to filter chunks from the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to filter chunks from the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`highWaterMark` {number} how many items to buffer while waiting for user consumption of the filtered items. **Default:** `concurrency * 2 - 1`.",
"name": "highWaterMark",
"type": "number",
"default": "`concurrency * 2 - 1`",
"desc": "how many items to buffer while waiting for user consumption of the filtered items."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Readable} a stream filtered with the predicate `fn`.",
"name": "return",
"type": "Readable",
"desc": "a stream filtered with the predicate `fn`."
}
}
],
"desc": "This method allows filtering the stream. For each chunk in the stream the fn\nfunction will be called and if it returns a truthy value, the chunk will be\npassed to the result stream. If the fn function returns a promise - that\npromise will be awaited.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).filter(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address.ttl > 60;\n}, { concurrency: 2 });\nfor await (const result of dnsResults) {\n // Logs domains with more than 60 seconds on the resolved dns record.\n console.log(result);\n}\n"
},
{
"textRaw": "`readable.forEach(fn[, options])`",
"name": "forEach",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to call on each chunk of the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to call on each chunk of the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise for when the stream has finished.",
"name": "return",
"type": "Promise",
"desc": "a promise for when the stream has finished."
}
}
],
"desc": "This method allows iterating a stream. For each chunk in the stream the\nfn function will be called. If the fn function returns a promise - that\npromise will be awaited.
This method is different from for await...of loops in that it can optionally\nprocess chunks concurrently. In addition, a forEach iteration can only be\nstopped by having passed a signal option and aborting the related\nAbortController while for await...of can be stopped with break or\nreturn. In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it\nuses the readable event in the underlying machinery and can limit the\nnumber of concurrent fn calls.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address;\n}, { concurrency: 2 });\nawait dnsResults.forEach((result) => {\n // Logs result, similar to `for await (const result of dnsResults)`\n console.log(result);\n});\nconsole.log('done'); // Stream has finished\n"
},
{
"textRaw": "`readable.toArray([options])`",
"name": "toArray",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} allows cancelling the toArray operation if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows cancelling the toArray operation if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise containing an array with the contents of the stream.",
"name": "return",
"type": "Promise",
"desc": "a promise containing an array with the contents of the stream."
}
}
],
"desc": "This method allows easily obtaining the contents of a stream.
\nAs this method reads the entire stream into memory, it negates the benefits of\nstreams. It's intended for interoperability and convenience, not as the primary\nway to consume streams.
\nimport { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\nawait Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]\n\nconst resolver = new Resolver();\n\n// Make dns queries concurrently using .map and collect\n// the results into an array using toArray\nconst dnsResults = await Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address;\n}, { concurrency: 2 }).toArray();\n"
},
{
"textRaw": "`readable.some(fn[, options])`",
"name": "some",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to call on each chunk of the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to call on each chunk of the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise evaluating to `true` if `fn` returned a truthy value for at least one of the chunks.",
"name": "return",
"type": "Promise",
"desc": "a promise evaluating to `true` if `fn` returned a truthy value for at least one of the chunks."
}
}
],
"desc": "This method is similar to Array.prototype.some and calls fn on each chunk\nin the stream until the awaited return value is true (or any truthy value).\nOnce an fn call on a chunk awaited return value is truthy, the stream is\ndestroyed and the promise is fulfilled with true. If none of the fn\ncalls on the chunks return a truthy value, the promise is fulfilled with\nfalse.
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true\nawait Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst anyBigFile = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).some(async (fileName) => {\n const stats = await stat(fileName);\n return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(anyBigFile); // `true` if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n"
},
{
"textRaw": "`readable.find(fn[, options])`",
"name": "find",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.17.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to call on each chunk of the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to call on each chunk of the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise evaluating to the first chunk for which `fn` evaluated with a truthy value, or `undefined` if no element was found.",
"name": "return",
"type": "Promise",
"desc": "a promise evaluating to the first chunk for which `fn` evaluated with a truthy value, or `undefined` if no element was found."
}
}
],
"desc": "This method is similar to Array.prototype.find and calls fn on each chunk\nin the stream to find a chunk with a truthy value for fn. Once an fn call's\nawaited return value is truthy, the stream is destroyed and the promise is\nfulfilled with value for which fn returned a truthy value. If all of the\nfn calls on the chunks return a falsy value, the promise is fulfilled with\nundefined.
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 0); // 1\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 10); // undefined\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst foundBigFile = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).find(async (fileName) => {\n const stats = await stat(fileName);\n return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n"
},
{
"textRaw": "`readable.every(fn[, options])`",
"name": "every",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a function to call on each chunk of the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a function to call on each chunk of the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise evaluating to `true` if `fn` returned a truthy value for all of the chunks.",
"name": "return",
"type": "Promise",
"desc": "a promise evaluating to `true` if `fn` returned a truthy value for all of the chunks."
}
}
],
"desc": "This method is similar to Array.prototype.every and calls fn on each chunk\nin the stream to check if all awaited return values are truthy value for fn.\nOnce an fn call on a chunk awaited return value is falsy, the stream is\ndestroyed and the promise is fulfilled with false. If all of the fn calls\non the chunks return a truthy value, the promise is fulfilled with true.
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 0); // true\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst allBigFiles = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).every(async (fileName) => {\n const stats = await stat(fileName);\n return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\n// `true` if all files in the list are bigger than 1MiB\nconsole.log(allBigFiles);\nconsole.log('done'); // Stream has finished\n"
},
{
"textRaw": "`readable.flatMap(fn[, options])`",
"name": "flatMap",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncGeneratorFunction|AsyncFunction} a function to map over every chunk in the stream.",
"name": "fn",
"type": "Function|AsyncGeneratorFunction|AsyncFunction",
"desc": "a function to map over every chunk in the stream.",
"options": [
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`concurrency` {number} the maximum concurrent invocation of `fn` to call on the stream at once. **Default:** `1`.",
"name": "concurrency",
"type": "number",
"default": "`1`",
"desc": "the maximum concurrent invocation of `fn` to call on the stream at once."
},
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Readable} a stream flat-mapped with the function `fn`.",
"name": "return",
"type": "Readable",
"desc": "a stream flat-mapped with the function `fn`."
}
}
],
"desc": "This method returns a new stream by applying the given callback to each\nchunk of the stream and then flattening the result.
\nIt is possible to return a stream or another iterable or async iterable from\nfn and the result streams will be merged (flattened) into the returned\nstream.
import { Readable } from 'node:stream';\nimport { createReadStream } from 'node:fs';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {\n console.log(chunk); // 1, 1, 2, 2, 3, 3, 4, 4\n}\n// With an asynchronous mapper, combine the contents of 4 files\nconst concatResult = Readable.from([\n './1.mjs',\n './2.mjs',\n './3.mjs',\n './4.mjs',\n]).flatMap((fileName) => createReadStream(fileName));\nfor await (const result of concatResult) {\n // This will contain the contents (all chunks) of all 4 files\n console.log(result);\n}\n"
},
{
"textRaw": "`readable.drop(limit[, options])`",
"name": "drop",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`limit` {number} the number of chunks to drop from the readable.",
"name": "limit",
"type": "number",
"desc": "the number of chunks to drop from the readable."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Readable} a stream with `limit` chunks dropped.",
"name": "return",
"type": "Readable",
"desc": "a stream with `limit` chunks dropped."
}
}
],
"desc": "This method returns a new stream with the first limit chunks dropped.
import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]\n"
},
{
"textRaw": "`readable.take(limit[, options])`",
"name": "take",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`limit` {number} the number of chunks to take from the readable.",
"name": "limit",
"type": "number",
"desc": "the number of chunks to take from the readable."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Readable} a stream with `limit` chunks taken.",
"name": "return",
"type": "Readable",
"desc": "a stream with `limit` chunks taken."
}
}
],
"desc": "This method returns a new stream with the first limit chunks.
import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]\n"
},
{
"textRaw": "`readable.reduce(fn[, initial[, options]])`",
"name": "reduce",
"type": "method",
"meta": {
"added": [
"v17.5.0",
"v16.15.0"
],
"changes": []
},
"stability": 1,
"stabilityText": "Experimental",
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function|AsyncFunction} a reducer function to call over every chunk in the stream.",
"name": "fn",
"type": "Function|AsyncFunction",
"desc": "a reducer function to call over every chunk in the stream.",
"options": [
{
"textRaw": "`previous` {any} the value obtained from the last call to `fn` or the `initial` value if specified or the first chunk of the stream otherwise.",
"name": "previous",
"type": "any",
"desc": "the value obtained from the last call to `fn` or the `initial` value if specified or the first chunk of the stream otherwise."
},
{
"textRaw": "`data` {any} a chunk of data from the stream.",
"name": "data",
"type": "any",
"desc": "a chunk of data from the stream."
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} aborted if the stream is destroyed allowing to abort the `fn` call early.",
"name": "signal",
"type": "AbortSignal",
"desc": "aborted if the stream is destroyed allowing to abort the `fn` call early."
}
]
}
]
},
{
"textRaw": "`initial` {any} the initial value to use in the reduction.",
"name": "initial",
"type": "any",
"desc": "the initial value to use in the reduction.",
"optional": true
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`signal` {AbortSignal} allows destroying the stream if the signal is aborted.",
"name": "signal",
"type": "AbortSignal",
"desc": "allows destroying the stream if the signal is aborted."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Promise} a promise for the final value of the reduction.",
"name": "return",
"type": "Promise",
"desc": "a promise for the final value of the reduction."
}
}
],
"desc": "This method calls fn on each chunk of the stream in order, passing it the\nresult from the calculation on the previous element. It returns a promise for\nthe final value of the reduction.
If no initial value is supplied the first chunk of the stream is used as the\ninitial value. If the stream is empty, the promise is rejected with a\nTypeError with the ERR_INVALID_ARGS code property.
import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n .reduce(async (totalSize, file) => {\n const { size } = await stat(join(directoryPath, file));\n return totalSize + size;\n }, 0);\n\nconsole.log(folderSize);\n\nThe reducer function iterates the stream element-by-element which means that\nthere is no concurrency parameter or parallelism. To perform a reduce\nconcurrently, you can extract the async function to readable.map method.
import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })\n .reduce((totalSize, { size }) => totalSize + size, 0);\n\nconsole.log(folderSize);\n"
}
],
"properties": [
{
"textRaw": "Type: {boolean}",
"name": "closed",
"type": "boolean",
"meta": {
"added": [
"v18.0.0"
],
"changes": []
},
"desc": "Is true after 'close' has been emitted.
Is true after readable.destroy() has been called.
Is true if it is safe to call readable.read(), which means\nthe stream has not been destroyed or emitted 'error' or 'end'.
Returns whether the stream was destroyed or errored before emitting 'end'.
Returns whether 'data' has been emitted.
Getter for the property encoding of a given Readable stream. The encoding\nproperty can be set using the readable.setEncoding() method.
Becomes true when 'end' event is emitted.
Returns error if the stream has been destroyed with an error.
" }, { "textRaw": "Type: {boolean}", "name": "readableFlowing", "type": "boolean", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "This property reflects the current state of a Readable stream as described\nin the Three states section.
Returns the value of highWaterMark passed when creating this Readable.
This property contains the number of bytes (or objects) in the queue\nready to be read. The value provides introspection data regarding\nthe status of the highWaterMark.
Getter for the property objectMode of a given Readable stream.
Duplex streams are streams that implement both the Readable and\nWritable interfaces.
Examples of Duplex streams include:
If false then the stream will automatically end the writable side when the\nreadable side ends. Set initially by the allowHalfOpen constructor option,\nwhich defaults to true.
This can be changed manually to change the half-open behavior of an existing\nDuplex stream instance, but must be changed before the 'end' event is\nemitted.
Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.
Examples of Transform streams include:
Destroy the stream, and optionally emit an 'error' event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\nreadable._destroy().\nThe default implementation of _destroy() for Transform also emit 'close'\nunless emitClose is set in false.
Once destroy() has been called, any further calls will be a no-op and no\nfurther errors except from _destroy() may be emitted as 'error'.
The utility function duplexPair returns an Array with two items,\neach being a Duplex stream connected to the other side:
const [ sideA, sideB ] = duplexPair();\n\nWhatever is written to one stream is made readable on the other. It provides\nbehavior analogous to a network connection, where the data written by the client\nbecomes readable by the server, and vice-versa.
\nThe Duplex streams are symmetrical; one or the other may be used without any\ndifference in behavior.
" } ], "displayName": "Duplex and transform streams" } ], "methods": [ { "textRaw": "`stream.finished(stream[, options], callback)`", "name": "finished", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v19.5.0", "pr-url": "https://github.com/nodejs/node/pull/46205", "description": "Added support for `ReadableStream` and `WritableStream`." }, { "version": "v15.11.0", "pr-url": "https://github.com/nodejs/node/pull/37354", "description": "The `signal` option was added." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/32158", "description": "The `finished(stream, cb)` will wait for the `'close'` event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit `'close'`." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31545", "description": "Emitting `'close'` before `'end'` on a `Readable` stream will cause an `ERR_STREAM_PREMATURE_CLOSE` error." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31509", "description": "Callback will be invoked on streams which have already finished before the call to `finished(stream, cb)`." } ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Stream|ReadableStream|WritableStream} A readable and/or writable stream/webstream.", "name": "stream", "type": "Stream|ReadableStream|WritableStream", "desc": "A readable and/or writable stream/webstream." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default:** `true`.", "name": "error", "type": "boolean", "default": "`true`", "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished." }, { "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default:** `true`.", "name": "readable", "type": "boolean", "default": "`true`", "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable." }, { "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default:** `true`.", "name": "writable", "type": "boolean", "default": "`true`", "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable." }, { "textRaw": "`signal` {AbortSignal} allows aborting the wait for the stream finish. The underlying stream will _not_ be aborted if the signal is aborted. The callback will get called with an `AbortError`. All registered listeners added by this function will also be removed.", "name": "signal", "type": "AbortSignal", "desc": "allows aborting the wait for the stream finish. The underlying stream will _not_ be aborted if the signal is aborted. The callback will get called with an `AbortError`. All registered listeners added by this function will also be removed." } ], "optional": true }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument." } ], "return": { "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", "name": "return", "type": "Function", "desc": "A cleanup function which removes all registered listeners." } } ], "desc": "A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.
\nconst { finished } = require('node:stream');\nconst fs = require('node:fs');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n if (err) {\n console.error('Stream failed.', err);\n } else {\n console.log('Stream is done reading.');\n }\n});\n\nrs.resume(); // Drain the stream.\n\nEspecially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.
The finished API provides promise version.
stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:
const cleanup = finished(rs, (err) => {\n cleanup();\n // ...\n});\n"
},
{
"textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`",
"name": "pipeline",
"type": "method",
"signatures": [
{
"params": [
{
"name": "source"
},
{
"name": "...transforms",
"optional": true
},
{
"name": "destination"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "`stream.pipeline(streams, callback)`",
"name": "pipeline",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": [
"v19.7.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46307",
"description": "Added support for webstreams."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/32158",
"description": "The `pipeline(..., cb)` will wait for the `'close'` event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit `'close'`."
},
{
"version": "v13.10.0",
"pr-url": "https://github.com/nodejs/node/pull/31223",
"description": "Add support for async generators."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]|ReadableStream[]|WritableStream[]|TransformStream[]}",
"name": "streams",
"type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]|ReadableStream[]|WritableStream[]|TransformStream[]"
},
{
"textRaw": "`callback` {Function} Called when the pipeline is fully done.",
"name": "callback",
"type": "Function",
"desc": "Called when the pipeline is fully done.",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`val` Resolved value of `Promise` returned by `destination`.",
"name": "val",
"desc": "Resolved value of `Promise` returned by `destination`."
}
]
}
],
"return": {
"textRaw": "Returns: {Stream}",
"name": "return",
"type": "Stream"
}
}
],
"desc": "A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.
\nconst { pipeline } = require('node:stream');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n },\n);\n\nThe pipeline API provides a promise version.
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\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors. If the last\nstream is readable, dangling event listeners will be removed so that the last\nstream can be consumed later.
stream.pipeline() closes all the streams when an error is raised.\nThe IncomingRequest usage with pipeline could lead to an unexpected behavior\nonce it would destroy the socket without sending the expected response.\nSee the example below:
const fs = require('node:fs');\nconst http = require('node:http');\nconst { pipeline } = require('node:stream');\n\nconst server = http.createServer((req, res) => {\n const fileStream = fs.createReadStream('./fileNotExist.txt');\n pipeline(fileStream, res, (err) => {\n if (err) {\n console.log(err); // No such file\n // this message can't be sent once `pipeline` already destroyed the socket\n return res.end('error!!!');\n }\n });\n});\n"
},
{
"textRaw": "`stream.compose(...streams)`",
"name": "compose",
"type": "method",
"meta": {
"added": [
"v16.9.0"
],
"changes": [
{
"version": [
"v21.1.0",
"v20.10.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50187",
"description": "Added support for stream class."
},
{
"version": [
"v19.8.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46675",
"description": "Added support for webstreams."
}
]
},
"stability": 1,
"stabilityText": "`stream.compose` is experimental.",
"signatures": [
{
"params": [
{
"name": "...streams"
}
],
"return": {
"textRaw": "Returns: {stream.Duplex}",
"name": "return",
"type": "stream.Duplex"
}
}
],
"desc": "Combines two or more streams into a Duplex stream that writes to the\nfirst stream and reads from the last. Each provided stream is piped into\nthe next, using stream.pipeline. If any of the streams error then all\nare destroyed, including the outer Duplex stream.
Because stream.compose returns a new stream that in turn can (and\nshould) be piped into other streams, it enables composition. In contrast,\nwhen passing streams to stream.pipeline, typically the first stream is\na readable stream and the last a writable stream, forming a closed\ncircuit.
If passed a Function it must be a factory method taking a source\nIterable.
import { compose, Transform } from 'node:stream';\n\nconst removeSpaces = new Transform({\n transform(chunk, encoding, callback) {\n callback(null, String(chunk).replace(' ', ''));\n },\n});\n\nasync function* toUpper(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n}\n\nlet res = '';\nfor await (const buf of compose(removeSpaces, toUpper).end('hello world')) {\n res += buf;\n}\n\nconsole.log(res); // prints 'HELLOWORLD'\n\nstream.compose can be used to convert async iterables, generators and\nfunctions into streams.
AsyncIterable converts into a readable Duplex. Cannot yield\nnull.AsyncGeneratorFunction converts into a readable/writable transform Duplex.\nMust take a source AsyncIterable as first parameter. Cannot yield\nnull.AsyncFunction converts into a writable Duplex. Must return\neither null or undefined.import { compose } from 'node:stream';\nimport { finished } from 'node:stream/promises';\n\n// Convert AsyncIterable into readable Duplex.\nconst s1 = compose(async function*() {\n yield 'Hello';\n yield 'World';\n}());\n\n// Convert AsyncGenerator into transform Duplex.\nconst s2 = compose(async function*(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n});\n\nlet res = '';\n\n// Convert AsyncFunction into writable Duplex.\nconst s3 = compose(async function(source) {\n for await (const chunk of source) {\n res += chunk;\n }\n});\n\nawait finished(compose(s1, s2, s3));\n\nconsole.log(res); // prints 'HELLOWORLD'\n\nFor convenience, the readable.compose(stream) method is available on\n<Readable> and <Duplex> streams as a wrapper for this function.
Returns whether the stream has encountered an error.
" }, { "textRaw": "`stream.isReadable(stream)`", "name": "isReadable", "type": "method", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Readable|Duplex|ReadableStream}", "name": "stream", "type": "Readable|Duplex|ReadableStream" } ], "return": { "textRaw": "Returns: {boolean|null} - Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`.", "name": "return", "type": "boolean|null", "desc": "Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`." } } ], "desc": "Returns whether the stream is readable.
" }, { "textRaw": "`stream.isWritable(stream)`", "name": "isWritable", "type": "method", "signatures": [ { "params": [ { "textRaw": "`stream` {Writable|Duplex|WritableStream}", "name": "stream", "type": "Writable|Duplex|WritableStream" } ], "return": { "textRaw": "Returns: {boolean|null} - Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`.", "name": "return", "type": "boolean|null", "desc": "Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`." } } ], "desc": "Returns whether the stream is writable.
" }, { "textRaw": "`stream.Readable.from(iterable[, options])`", "name": "from", "type": "method", "meta": { "added": [ "v12.3.0", "v10.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", "name": "iterable", "type": "Iterable", "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." }, { "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", "name": "options", "type": "Object", "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", "optional": true } ], "return": { "textRaw": "Returns: {stream.Readable}", "name": "return", "type": "stream.Readable" } } ], "desc": "A utility method for creating readable streams out of iterators.
\nconst { Readable } = require('node:stream');\n\nasync function * generate() {\n yield 'hello';\n yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n\nCalling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.
If an Iterable object containing promises is passed as an argument,\nit might result in unhandled rejection.
const { Readable } = require('node:stream');\n\nReadable.from([\n new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n"
},
{
"textRaw": "`stream.Readable.fromWeb(readableStream[, options])`",
"name": "fromWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`readableStream` {ReadableStream}",
"name": "readableStream",
"type": "ReadableStream"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`encoding` {string}",
"name": "encoding",
"type": "string"
},
{
"textRaw": "`highWaterMark` {number}",
"name": "highWaterMark",
"type": "number"
},
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
},
{
"textRaw": "`signal` {AbortSignal}",
"name": "signal",
"type": "AbortSignal"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Readable}",
"name": "return",
"type": "stream.Readable"
}
}
]
},
{
"textRaw": "`stream.Readable.isDisturbed(stream)`",
"name": "isDisturbed",
"type": "method",
"meta": {
"added": [
"v16.8.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {stream.Readable|ReadableStream}",
"name": "stream",
"type": "stream.Readable|ReadableStream"
}
],
"return": {
"textRaw": "Returns: `boolean`",
"name": "return",
"desc": "`boolean`"
}
}
],
"desc": "Returns whether the stream has been read from or cancelled.
" }, { "textRaw": "`stream.Readable.toWeb(streamReadable[, options])`", "name": "toWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/58664", "description": "Add 'type' option to specify 'bytes'." }, { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." }, { "version": [ "v18.7.0" ], "pr-url": "https://github.com/nodejs/node/pull/43515", "description": "include strategy options on Readable." } ] }, "signatures": [ { "params": [ { "textRaw": "`streamReadable` {stream.Readable}", "name": "streamReadable", "type": "stream.Readable" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`strategy` {Object}", "name": "strategy", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum internal queue size (of the created `ReadableStream`) before backpressure is applied in reading from the given `stream.Readable`. If no value is provided, it will be taken from the given `stream.Readable`.", "name": "highWaterMark", "type": "number", "desc": "The maximum internal queue size (of the created `ReadableStream`) before backpressure is applied in reading from the given `stream.Readable`. If no value is provided, it will be taken from the given `stream.Readable`." }, { "textRaw": "`size` {Function} A function that size of the given chunk of data. If no value is provided, the size will be `1` for all the chunks.", "name": "size", "type": "Function", "desc": "A function that size of the given chunk of data. If no value is provided, the size will be `1` for all the chunks.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ] }, { "textRaw": "`type` {string} Specifies the type of the created `ReadableStream`. Must be `'bytes'` or undefined.", "name": "type", "type": "string", "desc": "Specifies the type of the created `ReadableStream`. Must be `'bytes'` or undefined." } ], "optional": true } ], "return": { "textRaw": "Returns: {ReadableStream}", "name": "return", "type": "ReadableStream" } } ] }, { "textRaw": "`stream.Writable.fromWeb(writableStream[, options])`", "name": "fromWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`writableStream` {WritableStream}", "name": "writableStream", "type": "WritableStream" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`decodeStrings` {boolean}", "name": "decodeStrings", "type": "boolean" }, { "textRaw": "`highWaterMark` {number}", "name": "highWaterMark", "type": "number" }, { "textRaw": "`objectMode` {boolean}", "name": "objectMode", "type": "boolean" }, { "textRaw": "`signal` {AbortSignal}", "name": "signal", "type": "AbortSignal" } ], "optional": true } ], "return": { "textRaw": "Returns: {stream.Writable}", "name": "return", "type": "stream.Writable" } } ] }, { "textRaw": "`stream.Writable.toWeb(streamWritable)`", "name": "toWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`streamWritable` {stream.Writable}", "name": "streamWritable", "type": "stream.Writable" } ], "return": { "textRaw": "Returns: {WritableStream}", "name": "return", "type": "WritableStream" } } ] }, { "textRaw": "`stream.Duplex.from(src)`", "name": "from", "type": "method", "meta": { "added": [ "v16.8.0" ], "changes": [ { "version": [ "v19.5.0", "v18.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/46190", "description": "The `src` argument can now be a `ReadableStream` or `WritableStream`." } ] }, "signatures": [ { "params": [ { "textRaw": "`src` {Stream|Blob|ArrayBuffer|string|Iterable|AsyncIterable|AsyncGeneratorFunction|AsyncFunction|Promise|Object|ReadableStream|WritableStream}", "name": "src", "type": "Stream|Blob|ArrayBuffer|string|Iterable|AsyncIterable|AsyncGeneratorFunction|AsyncFunction|Promise|Object|ReadableStream|WritableStream" } ] } ], "desc": "A utility method for creating duplex streams.
\nStream converts writable stream into writable Duplex and readable stream\nto Duplex.Blob converts into readable Duplex.string converts into readable Duplex.ArrayBuffer converts into readable Duplex.AsyncIterable converts into a readable Duplex. Cannot yield\nnull.AsyncGeneratorFunction converts into a readable/writable transform\nDuplex. Must take a source AsyncIterable as first parameter. Cannot yield\nnull.AsyncFunction converts into a writable Duplex. Must return\neither null or undefinedObject ({ writable, readable }) converts readable and\nwritable into Stream and then combines them into Duplex where the\nDuplex will write to the writable and read from the readable.Promise converts into readable Duplex. Value null is ignored.ReadableStream converts into readable Duplex.WritableStream converts into writable Duplex.<stream.Duplex>If an Iterable object containing promises is passed as an argument,\nit might result in unhandled rejection.
const { Duplex } = require('node:stream');\n\nDuplex.from([\n new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n"
},
{
"textRaw": "`stream.Duplex.fromWeb(pair[, options])`",
"name": "fromWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`pair` {Object}",
"name": "pair",
"type": "Object",
"options": [
{
"textRaw": "`readable` {ReadableStream}",
"name": "readable",
"type": "ReadableStream"
},
{
"textRaw": "`writable` {WritableStream}",
"name": "writable",
"type": "WritableStream"
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`allowHalfOpen` {boolean}",
"name": "allowHalfOpen",
"type": "boolean"
},
{
"textRaw": "`decodeStrings` {boolean}",
"name": "decodeStrings",
"type": "boolean"
},
{
"textRaw": "`encoding` {string}",
"name": "encoding",
"type": "string"
},
{
"textRaw": "`highWaterMark` {number}",
"name": "highWaterMark",
"type": "number"
},
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
},
{
"textRaw": "`signal` {AbortSignal}",
"name": "signal",
"type": "AbortSignal"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Duplex}",
"name": "return",
"type": "stream.Duplex"
}
}
],
"desc": "import { Duplex } from 'node:stream';\nimport {\n ReadableStream,\n WritableStream,\n} from 'node:stream/web';\n\nconst readable = new ReadableStream({\n start(controller) {\n controller.enqueue('world');\n },\n});\n\nconst writable = new WritableStream({\n write(chunk) {\n console.log('writable', chunk);\n },\n});\n\nconst pair = {\n readable,\n writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\n\nfor await (const chunk of duplex) {\n console.log('readable', chunk);\n}\n\nconst { Duplex } = require('node:stream');\nconst {\n ReadableStream,\n WritableStream,\n} = require('node:stream/web');\n\nconst readable = new ReadableStream({\n start(controller) {\n controller.enqueue('world');\n },\n});\n\nconst writable = new WritableStream({\n write(chunk) {\n console.log('writable', chunk);\n },\n});\n\nconst pair = {\n readable,\n writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\nduplex.once('readable', () => console.log('readable', duplex.read()));\n"
},
{
"textRaw": "`stream.Duplex.toWeb(streamDuplex[, options])`",
"name": "toWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": "v25.7.0",
"pr-url": "https://github.com/nodejs/node/pull/61632",
"description": "Added the 'readableType' option to specify the ReadableStream type. The 'type' option is deprecated."
},
{
"version": "v25.4.0",
"pr-url": "https://github.com/nodejs/node/pull/58664",
"description": "Added the 'type' option to specify the ReadableStream type."
},
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`streamDuplex` {stream.Duplex}",
"name": "streamDuplex",
"type": "stream.Duplex"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`readableType` {string} Specifies the type of the `ReadableStream` half of the created readable-writable pair. Must be `'bytes'` or undefined. (`options.type` is a deprecated alias for this option.)",
"name": "readableType",
"type": "string",
"desc": "Specifies the type of the `ReadableStream` half of the created readable-writable pair. Must be `'bytes'` or undefined. (`options.type` is a deprecated alias for this option.)"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`readable` {ReadableStream}",
"name": "readable",
"type": "ReadableStream"
},
{
"textRaw": "`writable` {WritableStream}",
"name": "writable",
"type": "WritableStream"
}
]
}
}
],
"desc": "import { Duplex } from 'node:stream';\n\nconst duplex = Duplex({\n objectMode: true,\n read() {\n this.push('world');\n this.push(null);\n },\n write(chunk, encoding, callback) {\n console.log('writable', chunk);\n callback();\n },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nconst { value } = await readable.getReader().read();\nconsole.log('readable', value);\n\nconst { Duplex } = require('node:stream');\n\nconst duplex = Duplex({\n objectMode: true,\n read() {\n this.push('world');\n this.push(null);\n },\n write(chunk, encoding, callback) {\n console.log('writable', chunk);\n callback();\n },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nreadable.getReader().read().then((result) => {\n console.log('readable', result.value);\n});\n"
},
{
"textRaw": "`stream.addAbortSignal(signal, stream)`",
"name": "addAbortSignal",
"type": "method",
"meta": {
"added": [
"v15.4.0"
],
"changes": [
{
"version": [
"v19.7.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46273",
"description": "Added support for `ReadableStream` and `WritableStream`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`signal` {AbortSignal} A signal representing possible cancellation",
"name": "signal",
"type": "AbortSignal",
"desc": "A signal representing possible cancellation"
},
{
"textRaw": "`stream` {Stream|ReadableStream|WritableStream} A stream to attach a signal to.",
"name": "stream",
"type": "Stream|ReadableStream|WritableStream",
"desc": "A stream to attach a signal to."
}
]
}
],
"desc": "Attaches an AbortSignal to a readable or writeable stream. This lets code\ncontrol stream destruction using an AbortController.
Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the stream, and controller.error(new AbortError()) for webstreams.
const fs = require('node:fs');\n\nconst controller = new AbortController();\nconst read = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json')),\n);\n// Later, abort the operation closing the stream\ncontroller.abort();\n\nOr using an AbortSignal with a readable stream as an async iterable:
const controller = new AbortController();\nsetTimeout(() => controller.abort(), 10_000); // set a timeout\nconst stream = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json')),\n);\n(async () => {\n try {\n for await (const chunk of stream) {\n await process(chunk);\n }\n } catch (e) {\n if (e.name === 'AbortError') {\n // The operation was cancelled\n } else {\n throw e;\n }\n }\n})();\n\nOr using an AbortSignal with a ReadableStream:
const controller = new AbortController();\nconst rs = new ReadableStream({\n start(controller) {\n controller.enqueue('hello');\n controller.enqueue('world');\n controller.close();\n },\n});\n\naddAbortSignal(controller.signal, rs);\n\nfinished(rs, (err) => {\n if (err) {\n if (err.name === 'AbortError') {\n // The operation was cancelled\n }\n }\n});\n\nconst reader = rs.getReader();\n\nreader.read().then(({ value, done }) => {\n console.log(value); // hello\n console.log(done); // false\n controller.abort();\n});\n"
},
{
"textRaw": "`stream.getDefaultHighWaterMark(objectMode)`",
"name": "getDefaultHighWaterMark",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Returns the default highWaterMark used by streams.\nDefaults to 65536 (64 KiB), or 16 for objectMode.
Sets the default highWaterMark used by streams.
" } ] }, { "textRaw": "API for stream implementers", "name": "API for stream implementers", "type": "misc", "desc": "The node:stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.
First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable, stream.Readable,\nstream.Duplex, or stream.Transform), making sure they call the appropriate\nparent class constructor:
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n constructor({ highWaterMark, ...options }) {\n super({ highWaterMark });\n // ...\n }\n}\n\nWhen extending streams, keep in mind what options the user\ncan and should provide before forwarding these to the base constructor. For\nexample, if the implementation makes assumptions in regard to the\nautoDestroy and emitClose options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.
The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n| Use-case | Class | Method(s) to implement |
|---|---|---|
| Reading only | Readable | _read() |
| Writing only | Writable | _write(), _writev(), _final() |
| Reading and writing | Duplex | _read(), _write(), _writev(), _final() |
| Operate on written data, then read the result | Transform | _transform(), _flush(), _final() |
The implementation code for a stream should never call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\nAPI for stream consumers section). Doing so may lead to adverse side effects\nin application code consuming the stream.
\nAvoid overriding public methods such as write(), end(), cork(),\nuncork(), read() and destroy(), or emitting internal events such\nas 'error', 'data', 'end', 'finish' and 'close' through .emit().\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.
For many simple cases, it is possible to create a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable, stream.Readable, stream.Duplex, or stream.Transform\nobjects and passing appropriate methods as constructor options.
const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n construct(callback) {\n // Initialize state and load resources...\n },\n write(chunk, encoding, callback) {\n // ...\n },\n destroy() {\n // Free resources...\n },\n});\n",
"displayName": "Simplified construction"
},
{
"textRaw": "Implementing a writable stream",
"name": "implementing_a_writable_stream",
"type": "misc",
"desc": "The stream.Writable class is extended to implement a Writable stream.
Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() and/or writable._writev()\nmethod.
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n constructor(options) {\n // Calls the stream.Writable() constructor.\n super(options);\n // ...\n }\n}\n\nOr, when using pre-ES6 style constructors:
\nconst { Writable } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyWritable(options) {\n if (!(this instanceof MyWritable))\n return new MyWritable(options);\n Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n\nOr, using the simplified constructor approach:
\nconst { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n },\n});\n\nCalling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the writeable stream.
const { Writable } = require('node:stream');\n\nconst controller = new AbortController();\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n },\n signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n"
}
],
"methods": [
{
"textRaw": "`writable._construct(callback)`",
"name": "_construct",
"type": "method",
"meta": {
"added": [
"v15.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function} Call this function (optionally with an error argument) when the stream has finished initializing.",
"name": "callback",
"type": "Function",
"desc": "Call this function (optionally with an error argument) when the stream has finished initializing."
}
]
}
],
"desc": "The _construct() method MUST NOT be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.
This optional function will be called in a tick after the stream constructor\nhas returned, delaying any _write(), _final() and _destroy() calls until\ncallback is called. This is useful to initialize state or asynchronously\ninitialize resources before the stream can be used.
const { Writable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass WriteStream extends Writable {\n constructor(filename) {\n super();\n this.filename = filename;\n this.fd = null;\n }\n _construct(callback) {\n fs.open(this.filename, 'w', (err, fd) => {\n if (err) {\n callback(err);\n } else {\n this.fd = fd;\n callback();\n }\n });\n }\n _write(chunk, encoding, callback) {\n fs.write(this.fd, chunk, callback);\n }\n _destroy(err, callback) {\n if (this.fd) {\n fs.close(this.fd, (er) => callback(er || err));\n } else {\n callback(err);\n }\n }\n}\n"
},
{
"textRaw": "`writable._write(chunk, encoding, callback)`",
"name": "_write",
"type": "method",
"meta": {
"changes": [
{
"version": "v12.11.0",
"pr-url": "https://github.com/nodejs/node/pull/29639",
"description": "_write() is optional when providing _writev()."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be written, converted from the `string` passed to `stream.write()`. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to `stream.write()`.",
"name": "chunk",
"type": "Buffer|string|any",
"desc": "The `Buffer` to be written, converted from the `string` passed to `stream.write()`. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to `stream.write()`."
},
{
"textRaw": "`encoding` {string} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored.",
"name": "encoding",
"type": "string",
"desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored."
},
{
"textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk.",
"name": "callback",
"type": "Function",
"desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk."
}
]
}
],
"desc": "All Writable stream implementations must provide a\nwritable._write() and/or\nwritable._writev() method to send data to the underlying\nresource.
Transform streams provide their own implementation of the\nwritable._write().
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.
The callback function must be called synchronously inside of\nwritable._write() or asynchronously (i.e. different tick) to signal either\nthat the write completed successfully or failed with an error.\nThe first argument passed to the callback must be the Error object if the\ncall failed or null if the write succeeded.
All calls to writable.write() that occur between the time writable._write()\nis called and the callback is called will cause the written data to be\nbuffered. When the callback is invoked, the stream might emit a 'drain'\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the writable._writev() method should be implemented.
If the decodeStrings property is explicitly set to false in the constructor\noptions, then chunk will remain the same object that is passed to .write(),\nand may be a string rather than a Buffer. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe encoding argument will indicate the character encoding of the string.\nOtherwise, the encoding argument can be safely ignored.
The writable._write() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.
The writable._writev() method may be implemented in addition or alternatively\nto writable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented and if there is buffered data\nfrom previous writes, _writev() will be called instead of _write().
The writable._writev() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.
The _final() method must not be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.
This optional function will be called before the stream closes, delaying the\n'finish' event until callback is called. This is useful to close resources\nor write buffered data before a stream ends.
Errors occurring during the processing of the writable._write(),\nwritable._writev() and writable._final() methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an Error from within these methods or manually emitting an 'error'\nevent results in undefined behavior.
If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.
const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n },\n});\n",
"displayName": "Errors while writing"
},
{
"textRaw": "An example writable stream",
"name": "an_example_writable_stream",
"type": "module",
"desc": "The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n _write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n}\n",
"displayName": "An example writable stream"
},
{
"textRaw": "Decoding buffers in a writable stream",
"name": "decoding_buffers_in_a_writable_stream",
"type": "module",
"desc": "Decoding buffers is a common task, for instance, when using transformers whose\ninput is a string. This is not a trivial process when using multi-byte\ncharacters encoding, such as UTF-8. The following example shows how to decode\nmulti-byte strings using StringDecoder and Writable.
const { Writable } = require('node:stream');\nconst { StringDecoder } = require('node:string_decoder');\n\nclass StringWritable extends Writable {\n constructor(options) {\n super(options);\n this._decoder = new StringDecoder(options?.defaultEncoding);\n this.data = '';\n }\n _write(chunk, encoding, callback) {\n if (encoding === 'buffer') {\n chunk = this._decoder.write(chunk);\n }\n this.data += chunk;\n callback();\n }\n _final(callback) {\n this.data += this._decoder.end();\n callback();\n }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n",
"displayName": "Decoding buffers in a writable stream"
}
],
"displayName": "Implementing a writable stream"
},
{
"textRaw": "Implementing a readable stream",
"name": "implementing_a_readable_stream",
"type": "misc",
"desc": "The stream.Readable class is extended to implement a Readable stream.
Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.
const { Readable } = require('node:stream');\n\nclass MyReadable extends Readable {\n constructor(options) {\n // Calls the stream.Readable(options) constructor.\n super(options);\n // ...\n }\n}\n\nOr, when using pre-ES6 style constructors:
\nconst { Readable } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyReadable(options) {\n if (!(this instanceof MyReadable))\n return new MyReadable(options);\n Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n\nOr, using the simplified constructor approach:
\nconst { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n read(size) {\n // ...\n },\n});\n\nCalling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the readable created.
const { Readable } = require('node:stream');\nconst controller = new AbortController();\nconst read = new Readable({\n read(size) {\n // ...\n },\n signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n"
}
],
"methods": [
{
"textRaw": "`readable._construct(callback)`",
"name": "_construct",
"type": "method",
"meta": {
"added": [
"v15.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function} Call this function (optionally with an error argument) when the stream has finished initializing.",
"name": "callback",
"type": "Function",
"desc": "Call this function (optionally with an error argument) when the stream has finished initializing."
}
]
}
],
"desc": "The _construct() method MUST NOT be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Readable\nclass methods only.
This optional function will be scheduled in the next tick by the stream\nconstructor, delaying any _read() and _destroy() calls until callback is\ncalled. This is useful to initialize state or asynchronously initialize\nresources before the stream can be used.
const { Readable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass ReadStream extends Readable {\n constructor(filename) {\n super();\n this.filename = filename;\n this.fd = null;\n }\n _construct(callback) {\n fs.open(this.filename, (err, fd) => {\n if (err) {\n callback(err);\n } else {\n this.fd = fd;\n callback();\n }\n });\n }\n _read(n) {\n const buf = Buffer.alloc(n);\n fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {\n if (err) {\n this.destroy(err);\n } else {\n this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);\n }\n });\n }\n _destroy(err, callback) {\n if (this.fd) {\n fs.close(this.fd, (er) => callback(er || err));\n } else {\n callback(err);\n }\n }\n}\n"
},
{
"textRaw": "`readable._read(size)`",
"name": "_read",
"type": "method",
"meta": {
"added": [
"v0.9.4"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`size` {number} Number of bytes to read asynchronously",
"name": "size",
"type": "number",
"desc": "Number of bytes to read asynchronously"
}
]
}
],
"desc": "This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.
All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.
When readable._read() is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() will be called again\nafter each call to this.push(dataChunk) once the stream is\nready to accept more data. _read() may continue reading from the resource and\npushing data until readable.push() returns false. Only when _read() is\ncalled again after it has stopped should it resume pushing additional data into\nthe queue.
Once the readable._read() method has been called, it will not be called\nagain until more data is pushed through the readable.push()\nmethod. Empty data such as empty buffers and strings will not cause\nreadable._read() to be called.
The size argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the size argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to \"wait\" until\nsize bytes are available before calling stream.push(chunk).
The readable._read() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.
When chunk is a <Buffer>, <TypedArray>, <DataView> or <string>, the chunk\nof data will be added to the internal queue for users of the stream to consume.\nPassing chunk as null signals the end of the stream (EOF), after which no\nmore data can be written.
When the Readable is operating in paused mode, the data added with\nreadable.push() can be read out by calling the\nreadable.read() method when the 'readable' event is\nemitted.
When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.
The readable.push() method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance:
// `_source` is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n constructor(options) {\n super(options);\n\n this._source = getLowLevelSourceObject();\n\n // Every time there's data, push it into the internal buffer.\n this._source.ondata = (chunk) => {\n // If push() returns false, then stop reading from source.\n if (!this.push(chunk))\n this._source.readStop();\n };\n\n // When the source ends, push the EOF-signaling `null` chunk.\n this._source.onend = () => {\n this.push(null);\n };\n }\n // _read() will be called when the stream wants to pull more data in.\n // The advisory size argument is ignored in this case.\n _read(size) {\n this._source.readStart();\n }\n}\n\nThe readable.push() method is used to push the content\ninto the internal buffer. It can be driven by the readable._read() method.
For streams not operating in object mode, if the chunk parameter of\nreadable.push() is undefined, it will be treated as empty string or\nbuffer. See readable.push('') for more information.
Errors occurring during processing of the readable._read() must be\npropagated through the readable.destroy(err) method.\nThrowing an Error from within readable._read() or manually emitting an\n'error' event results in undefined behavior.
const { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n read(size) {\n const err = checkSomeErrorCondition();\n if (err) {\n this.destroy(err);\n } else {\n // Do some work.\n }\n },\n});\n",
"displayName": "Errors while reading"
}
],
"examples": [
{
"textRaw": "An example counting stream",
"name": "An example counting stream",
"type": "example",
"desc": "The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.
const { Readable } = require('node:stream');\n\nclass Counter extends Readable {\n constructor(opt) {\n super(opt);\n this._max = 1000000;\n this._index = 1;\n }\n\n _read() {\n const i = this._index++;\n if (i > this._max)\n this.push(null);\n else {\n const str = String(i);\n const buf = Buffer.from(str, 'ascii');\n this.push(buf);\n }\n }\n}\n"
}
],
"displayName": "Implementing a readable stream"
},
{
"textRaw": "Implementing a duplex stream",
"name": "implementing_a_duplex_stream",
"type": "misc",
"desc": "A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.
Because JavaScript does not have support for multiple inheritance, the\nstream.Duplex class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable and stream.Writable classes).
The stream.Duplex class prototypically inherits from stream.Readable and\nparasitically from stream.Writable, but instanceof will work properly for\nboth base classes due to overriding Symbol.hasInstance on\nstream.Writable.
Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.
const { Duplex } = require('node:stream');\n\nclass MyDuplex extends Duplex {\n constructor(options) {\n super(options);\n // ...\n }\n}\n\nOr, when using pre-ES6 style constructors:
\nconst { Duplex } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyDuplex(options) {\n if (!(this instanceof MyDuplex))\n return new MyDuplex(options);\n Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n\nOr, using the simplified constructor approach:
\nconst { Duplex } = require('node:stream');\n\nconst myDuplex = new Duplex({\n read(size) {\n // ...\n },\n write(chunk, encoding, callback) {\n // ...\n },\n});\n\nWhen using pipeline:
\nconst { Transform, pipeline } = require('node:stream');\nconst fs = require('node:fs');\n\npipeline(\n fs.createReadStream('object.json')\n .setEncoding('utf8'),\n new Transform({\n decodeStrings: false, // Accept string input rather than Buffers\n construct(callback) {\n this.data = '';\n callback();\n },\n transform(chunk, encoding, callback) {\n this.data += chunk;\n callback();\n },\n flush(callback) {\n try {\n // Make sure is valid json.\n JSON.parse(this.data);\n this.push(this.data);\n callback();\n } catch (err) {\n callback(err);\n }\n },\n }),\n fs.createWriteStream('valid-object.json'),\n (err) => {\n if (err) {\n console.error('failed', err);\n } else {\n console.log('completed');\n }\n },\n);\n"
}
],
"modules": [
{
"textRaw": "An example duplex stream",
"name": "an_example_duplex_stream",
"type": "module",
"desc": "The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.
const { Duplex } = require('node:stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n constructor(source, options) {\n super(options);\n this[kSource] = source;\n }\n\n _write(chunk, encoding, callback) {\n // The underlying source only deals with strings.\n if (Buffer.isBuffer(chunk))\n chunk = chunk.toString();\n this[kSource].writeSomeData(chunk);\n callback();\n }\n\n _read(size) {\n this[kSource].fetchSomeData(size, (data, encoding) => {\n this.push(Buffer.from(data, encoding));\n });\n }\n}\n\nThe most important aspect of a Duplex stream is that the Readable and\nWritable sides operate independently of one another despite co-existing within\na single object instance.
For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.
In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.
const { Transform } = require('node:stream');\n\n// All Transform streams are also Duplex Streams.\nconst myTransform = new Transform({\n writableObjectMode: true,\n\n transform(chunk, encoding, callback) {\n // Coerce the chunk to a number if necessary.\n chunk |= 0;\n\n // Transform the chunk into something else.\n const data = chunk.toString(16);\n\n // Push the data onto the readable queue.\n callback(null, '0'.repeat(data.length % 2) + data);\n },\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n",
"displayName": "Object mode duplex streams"
}
],
"displayName": "Implementing a duplex stream"
},
{
"textRaw": "Implementing a transform stream",
"name": "implementing_a_transform_stream",
"type": "misc",
"desc": "A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.
There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a Hash stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A zlib stream will produce output that is either much smaller or much\nlarger than its input.
The stream.Transform class is extended to implement a Transform stream.
The stream.Transform class prototypically inherits from stream.Duplex and\nimplements its own versions of the writable._write() and\nreadable._read() methods. Custom Transform implementations must\nimplement the transform._transform() method and may\nalso implement the transform._flush() method.
Care must be taken when using Transform streams in that data written to the\nstream can cause the Writable side of the stream to become paused if the\noutput on the Readable side is not consumed.
const { Transform } = require('node:stream');\n\nclass MyTransform extends Transform {\n constructor(options) {\n super(options);\n // ...\n }\n}\n\nOr, when using pre-ES6 style constructors:
\nconst { Transform } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyTransform(options) {\n if (!(this instanceof MyTransform))\n return new MyTransform(options);\n Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n\nOr, using the simplified constructor approach:
\nconst { Transform } = require('node:stream');\n\nconst myTransform = new Transform({\n transform(chunk, encoding, callback) {\n // ...\n },\n});\n"
}
],
"events": [
{
"textRaw": "Event: `'end'`",
"name": "end",
"type": "event",
"params": [],
"desc": "The 'end' event is from the stream.Readable class. The 'end' event is\nemitted after all data has been output, which occurs after the callback in\ntransform._flush() has been called. In the case of an error,\n'end' should not be emitted.
The 'finish' event is from the stream.Writable class. The 'finish'\nevent is emitted after stream.end() is called and all chunks\nhave been processed by stream._transform(). In the case\nof an error, 'finish' should not be emitted.
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.
In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.
Custom Transform implementations may implement the transform._flush()\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end' event is emitted signaling the end of the\nReadable stream.
Within the transform._flush() implementation, the transform.push() method\nmay be called zero or more times, as appropriate. The callback function must\nbe called when the flush operation is complete.
The transform._flush() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.
All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output. The transform._transform()\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the transform.push() method.
The transform.push() method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.
It is possible that no output is generated from any given chunk of input data.
\nThe callback function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback must be an Error object\nif an error occurred while processing the input or null otherwise. If a second\nargument is passed to the callback, it will be forwarded on to the\ntransform.push() method, but only if the first argument is falsy. In other\nwords, the following are equivalent:
transform.prototype._transform = function(data, encoding, callback) {\n this.push(data);\n callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n callback(null, data);\n};\n\nThe transform._transform() method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.
transform._transform() is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, callback must be\ncalled, either synchronously or asynchronously.
The stream.PassThrough class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough is useful as a building block for novel sorts of streams.
With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.
\nSome common interop cases of using Node.js streams with async generators\nand async iterators are provided below.
", "modules": [ { "textRaw": "Consuming readable streams with async iterators", "name": "consuming_readable_streams_with_async_iterators", "type": "module", "desc": "(async function() {\n for await (const chunk of readable) {\n console.log(chunk);\n }\n})();\n\nAsync iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.
", "displayName": "Consuming readable streams with async iterators" }, { "textRaw": "Creating readable streams with async generators", "name": "creating_readable_streams_with_async_generators", "type": "module", "desc": "A Node.js readable stream can be created from an asynchronous generator using\nthe Readable.from() utility method:
const { Readable } = require('node:stream');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nasync function * generate() {\n yield 'a';\n await someLongRunningFn({ signal });\n yield 'b';\n yield 'c';\n}\n\nconst readable = Readable.from(generate());\nreadable.on('close', () => {\n ac.abort();\n});\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n",
"displayName": "Creating readable streams with async generators"
}
],
"miscs": [
{
"textRaw": "Piping to writable streams from async iterators",
"name": "Piping to writable streams from async iterators",
"type": "misc",
"desc": "When writing to a writable stream from an async iterator, ensure correct\nhandling of backpressure and errors. stream.pipeline() abstracts away\nthe handling of backpressure and backpressure-related errors:
const fs = require('node:fs');\nconst { pipeline } = require('node:stream');\nconst { pipeline: pipelinePromise } = require('node:stream/promises');\n\nconst writable = fs.createWriteStream('./file');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nconst iterator = createIterator({ signal });\n\n// Callback Pattern\npipeline(iterator, writable, (err, value) => {\n if (err) {\n console.error(err);\n } else {\n console.log(value, 'value returned');\n }\n}).on('close', () => {\n ac.abort();\n});\n\n// Promise Pattern\npipelinePromise(iterator, writable)\n .then((value) => {\n console.log(value, 'value returned');\n })\n .catch((err) => {\n console.error(err);\n ac.abort();\n });\n"
}
],
"displayName": "Streams compatibility with async generators and async iterators"
},
{
"textRaw": "Compatibility with older Node.js versions",
"name": "Compatibility with older Node.js versions",
"type": "misc",
"desc": "Prior to Node.js 0.10, the Readable stream interface was simpler, but also\nless powerful and less useful.
stream.read() method,\n'data' events would begin emitting immediately. Applications that\nwould need to perform some amount of work to decide how to handle data\nwere required to store read data into buffers so the data would not be lost.stream.pause() method was advisory, rather than\nguaranteed. This meant that it was still necessary to be prepared to receive\n'data' events even when the stream was in a paused state.In Node.js 0.10, the Readable class was added. For backward\ncompatibility with older Node.js programs, Readable streams switch into\n\"flowing mode\" when a 'data' event handler is added, or when the\nstream.resume() method is called. The effect is that, even\nwhen not using the new stream.read() method and\n'readable' event, it is no longer necessary to worry about losing\n'data' chunks.
While most applications will continue to function normally, this introduces an\nedge case in the following conditions:
\n'data' event listener is added.stream.resume() method is never called.For example, consider the following code:
\n// WARNING! BROKEN!\nnet.createServer((socket) => {\n\n // We add an 'end' listener, but never consume the data.\n socket.on('end', () => {\n // It will never get here.\n socket.end('The message was received but was not processed.\\n');\n });\n\n}).listen(1337);\n\nPrior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.
\nThe workaround in this situation is to call the\nstream.resume() method to begin the flow of data:
// Workaround.\nnet.createServer((socket) => {\n socket.on('end', () => {\n socket.end('The message was received but was not processed.\\n');\n });\n\n // Start the flow of data, discarding it.\n socket.resume();\n}).listen(1337);\n\nIn addition to new Readable streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.
The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.
Typically, the size of the current buffer is measured against the\nhighWaterMark in bytes. However, after setEncoding() is called, the\ncomparison function will begin to measure the buffer's size in characters.
This is not a problem in common cases with latin1 or ascii. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.
There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.
If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.
While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.
Use of readable.push('') is not recommended.
Pushing a zero-byte <string>, <Buffer>, <TypedArray> or <DataView> to a stream\nthat is not in object mode has an interesting side effect.\nBecause it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.
A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.
\nconst { finished } = require('node:stream');\nconst fs = require('node:fs');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n if (err) {\n console.error('Stream failed.', err);\n } else {\n console.log('Stream is done reading.');\n }\n});\n\nrs.resume(); // Drain the stream.\n\nEspecially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.
The finished API provides promise version.
stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:
const cleanup = finished(rs, (err) => {\n cleanup();\n // ...\n});\n"
},
{
"textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`",
"name": "pipeline",
"type": "method",
"signatures": [
{
"params": [
{
"name": "source"
},
{
"name": "...transforms",
"optional": true
},
{
"name": "destination"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "`stream.pipeline(streams, callback)`",
"name": "pipeline",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": [
{
"version": [
"v19.7.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46307",
"description": "Added support for webstreams."
},
{
"version": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"version": "v14.0.0",
"pr-url": "https://github.com/nodejs/node/pull/32158",
"description": "The `pipeline(..., cb)` will wait for the `'close'` event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit `'close'`."
},
{
"version": "v13.10.0",
"pr-url": "https://github.com/nodejs/node/pull/31223",
"description": "Add support for async generators."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]|ReadableStream[]|WritableStream[]|TransformStream[]}",
"name": "streams",
"type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]|ReadableStream[]|WritableStream[]|TransformStream[]"
},
{
"textRaw": "`callback` {Function} Called when the pipeline is fully done.",
"name": "callback",
"type": "Function",
"desc": "Called when the pipeline is fully done.",
"options": [
{
"textRaw": "`err` {Error}",
"name": "err",
"type": "Error"
},
{
"textRaw": "`val` Resolved value of `Promise` returned by `destination`.",
"name": "val",
"desc": "Resolved value of `Promise` returned by `destination`."
}
]
}
],
"return": {
"textRaw": "Returns: {Stream}",
"name": "return",
"type": "Stream"
}
}
],
"desc": "A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.
\nconst { pipeline } = require('node:stream');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n },\n);\n\nThe pipeline API provides a promise version.
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\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors. If the last\nstream is readable, dangling event listeners will be removed so that the last\nstream can be consumed later.
stream.pipeline() closes all the streams when an error is raised.\nThe IncomingRequest usage with pipeline could lead to an unexpected behavior\nonce it would destroy the socket without sending the expected response.\nSee the example below:
const fs = require('node:fs');\nconst http = require('node:http');\nconst { pipeline } = require('node:stream');\n\nconst server = http.createServer((req, res) => {\n const fileStream = fs.createReadStream('./fileNotExist.txt');\n pipeline(fileStream, res, (err) => {\n if (err) {\n console.log(err); // No such file\n // this message can't be sent once `pipeline` already destroyed the socket\n return res.end('error!!!');\n }\n });\n});\n"
},
{
"textRaw": "`stream.compose(...streams)`",
"name": "compose",
"type": "method",
"meta": {
"added": [
"v16.9.0"
],
"changes": [
{
"version": [
"v21.1.0",
"v20.10.0"
],
"pr-url": "https://github.com/nodejs/node/pull/50187",
"description": "Added support for stream class."
},
{
"version": [
"v19.8.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46675",
"description": "Added support for webstreams."
}
]
},
"stability": 1,
"stabilityText": "`stream.compose` is experimental.",
"signatures": [
{
"params": [
{
"name": "...streams"
}
],
"return": {
"textRaw": "Returns: {stream.Duplex}",
"name": "return",
"type": "stream.Duplex"
}
}
],
"desc": "Combines two or more streams into a Duplex stream that writes to the\nfirst stream and reads from the last. Each provided stream is piped into\nthe next, using stream.pipeline. If any of the streams error then all\nare destroyed, including the outer Duplex stream.
Because stream.compose returns a new stream that in turn can (and\nshould) be piped into other streams, it enables composition. In contrast,\nwhen passing streams to stream.pipeline, typically the first stream is\na readable stream and the last a writable stream, forming a closed\ncircuit.
If passed a Function it must be a factory method taking a source\nIterable.
import { compose, Transform } from 'node:stream';\n\nconst removeSpaces = new Transform({\n transform(chunk, encoding, callback) {\n callback(null, String(chunk).replace(' ', ''));\n },\n});\n\nasync function* toUpper(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n}\n\nlet res = '';\nfor await (const buf of compose(removeSpaces, toUpper).end('hello world')) {\n res += buf;\n}\n\nconsole.log(res); // prints 'HELLOWORLD'\n\nstream.compose can be used to convert async iterables, generators and\nfunctions into streams.
AsyncIterable converts into a readable Duplex. Cannot yield\nnull.AsyncGeneratorFunction converts into a readable/writable transform Duplex.\nMust take a source AsyncIterable as first parameter. Cannot yield\nnull.AsyncFunction converts into a writable Duplex. Must return\neither null or undefined.import { compose } from 'node:stream';\nimport { finished } from 'node:stream/promises';\n\n// Convert AsyncIterable into readable Duplex.\nconst s1 = compose(async function*() {\n yield 'Hello';\n yield 'World';\n}());\n\n// Convert AsyncGenerator into transform Duplex.\nconst s2 = compose(async function*(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n});\n\nlet res = '';\n\n// Convert AsyncFunction into writable Duplex.\nconst s3 = compose(async function(source) {\n for await (const chunk of source) {\n res += chunk;\n }\n});\n\nawait finished(compose(s1, s2, s3));\n\nconsole.log(res); // prints 'HELLOWORLD'\n\nFor convenience, the readable.compose(stream) method is available on\n<Readable> and <Duplex> streams as a wrapper for this function.
Returns whether the stream has encountered an error.
" }, { "textRaw": "`stream.isReadable(stream)`", "name": "isReadable", "type": "method", "meta": { "added": [ "v17.4.0", "v16.14.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Readable|Duplex|ReadableStream}", "name": "stream", "type": "Readable|Duplex|ReadableStream" } ], "return": { "textRaw": "Returns: {boolean|null} - Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`.", "name": "return", "type": "boolean|null", "desc": "Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`." } } ], "desc": "Returns whether the stream is readable.
" }, { "textRaw": "`stream.isWritable(stream)`", "name": "isWritable", "type": "method", "signatures": [ { "params": [ { "textRaw": "`stream` {Writable|Duplex|WritableStream}", "name": "stream", "type": "Writable|Duplex|WritableStream" } ], "return": { "textRaw": "Returns: {boolean|null} - Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`.", "name": "return", "type": "boolean|null", "desc": "Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`." } } ], "desc": "Returns whether the stream is writable.
" }, { "textRaw": "`stream.Readable.from(iterable[, options])`", "name": "from", "type": "method", "meta": { "added": [ "v12.3.0", "v10.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", "name": "iterable", "type": "Iterable", "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." }, { "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", "name": "options", "type": "Object", "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", "optional": true } ], "return": { "textRaw": "Returns: {stream.Readable}", "name": "return", "type": "stream.Readable" } } ], "desc": "A utility method for creating readable streams out of iterators.
\nconst { Readable } = require('node:stream');\n\nasync function * generate() {\n yield 'hello';\n yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n\nCalling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.
If an Iterable object containing promises is passed as an argument,\nit might result in unhandled rejection.
const { Readable } = require('node:stream');\n\nReadable.from([\n new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n"
},
{
"textRaw": "`stream.Readable.fromWeb(readableStream[, options])`",
"name": "fromWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`readableStream` {ReadableStream}",
"name": "readableStream",
"type": "ReadableStream"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`encoding` {string}",
"name": "encoding",
"type": "string"
},
{
"textRaw": "`highWaterMark` {number}",
"name": "highWaterMark",
"type": "number"
},
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
},
{
"textRaw": "`signal` {AbortSignal}",
"name": "signal",
"type": "AbortSignal"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Readable}",
"name": "return",
"type": "stream.Readable"
}
}
]
},
{
"textRaw": "`stream.Readable.isDisturbed(stream)`",
"name": "isDisturbed",
"type": "method",
"meta": {
"added": [
"v16.8.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {stream.Readable|ReadableStream}",
"name": "stream",
"type": "stream.Readable|ReadableStream"
}
],
"return": {
"textRaw": "Returns: `boolean`",
"name": "return",
"desc": "`boolean`"
}
}
],
"desc": "Returns whether the stream has been read from or cancelled.
" }, { "textRaw": "`stream.Readable.toWeb(streamReadable[, options])`", "name": "toWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": "v25.4.0", "pr-url": "https://github.com/nodejs/node/pull/58664", "description": "Add 'type' option to specify 'bytes'." }, { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." }, { "version": [ "v18.7.0" ], "pr-url": "https://github.com/nodejs/node/pull/43515", "description": "include strategy options on Readable." } ] }, "signatures": [ { "params": [ { "textRaw": "`streamReadable` {stream.Readable}", "name": "streamReadable", "type": "stream.Readable" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`strategy` {Object}", "name": "strategy", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum internal queue size (of the created `ReadableStream`) before backpressure is applied in reading from the given `stream.Readable`. If no value is provided, it will be taken from the given `stream.Readable`.", "name": "highWaterMark", "type": "number", "desc": "The maximum internal queue size (of the created `ReadableStream`) before backpressure is applied in reading from the given `stream.Readable`. If no value is provided, it will be taken from the given `stream.Readable`." }, { "textRaw": "`size` {Function} A function that size of the given chunk of data. If no value is provided, the size will be `1` for all the chunks.", "name": "size", "type": "Function", "desc": "A function that size of the given chunk of data. If no value is provided, the size will be `1` for all the chunks.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ] }, { "textRaw": "`type` {string} Specifies the type of the created `ReadableStream`. Must be `'bytes'` or undefined.", "name": "type", "type": "string", "desc": "Specifies the type of the created `ReadableStream`. Must be `'bytes'` or undefined." } ], "optional": true } ], "return": { "textRaw": "Returns: {ReadableStream}", "name": "return", "type": "ReadableStream" } } ] }, { "textRaw": "`stream.Writable.fromWeb(writableStream[, options])`", "name": "fromWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`writableStream` {WritableStream}", "name": "writableStream", "type": "WritableStream" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`decodeStrings` {boolean}", "name": "decodeStrings", "type": "boolean" }, { "textRaw": "`highWaterMark` {number}", "name": "highWaterMark", "type": "number" }, { "textRaw": "`objectMode` {boolean}", "name": "objectMode", "type": "boolean" }, { "textRaw": "`signal` {AbortSignal}", "name": "signal", "type": "AbortSignal" } ], "optional": true } ], "return": { "textRaw": "Returns: {stream.Writable}", "name": "return", "type": "stream.Writable" } } ] }, { "textRaw": "`stream.Writable.toWeb(streamWritable)`", "name": "toWeb", "type": "method", "meta": { "added": [ "v17.0.0" ], "changes": [ { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57513", "description": "Marking the API stable." } ] }, "signatures": [ { "params": [ { "textRaw": "`streamWritable` {stream.Writable}", "name": "streamWritable", "type": "stream.Writable" } ], "return": { "textRaw": "Returns: {WritableStream}", "name": "return", "type": "WritableStream" } } ] }, { "textRaw": "`stream.Duplex.from(src)`", "name": "from", "type": "method", "meta": { "added": [ "v16.8.0" ], "changes": [ { "version": [ "v19.5.0", "v18.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/46190", "description": "The `src` argument can now be a `ReadableStream` or `WritableStream`." } ] }, "signatures": [ { "params": [ { "textRaw": "`src` {Stream|Blob|ArrayBuffer|string|Iterable|AsyncIterable|AsyncGeneratorFunction|AsyncFunction|Promise|Object|ReadableStream|WritableStream}", "name": "src", "type": "Stream|Blob|ArrayBuffer|string|Iterable|AsyncIterable|AsyncGeneratorFunction|AsyncFunction|Promise|Object|ReadableStream|WritableStream" } ] } ], "desc": "A utility method for creating duplex streams.
\nStream converts writable stream into writable Duplex and readable stream\nto Duplex.Blob converts into readable Duplex.string converts into readable Duplex.ArrayBuffer converts into readable Duplex.AsyncIterable converts into a readable Duplex. Cannot yield\nnull.AsyncGeneratorFunction converts into a readable/writable transform\nDuplex. Must take a source AsyncIterable as first parameter. Cannot yield\nnull.AsyncFunction converts into a writable Duplex. Must return\neither null or undefinedObject ({ writable, readable }) converts readable and\nwritable into Stream and then combines them into Duplex where the\nDuplex will write to the writable and read from the readable.Promise converts into readable Duplex. Value null is ignored.ReadableStream converts into readable Duplex.WritableStream converts into writable Duplex.<stream.Duplex>If an Iterable object containing promises is passed as an argument,\nit might result in unhandled rejection.
const { Duplex } = require('node:stream');\n\nDuplex.from([\n new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n"
},
{
"textRaw": "`stream.Duplex.fromWeb(pair[, options])`",
"name": "fromWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`pair` {Object}",
"name": "pair",
"type": "Object",
"options": [
{
"textRaw": "`readable` {ReadableStream}",
"name": "readable",
"type": "ReadableStream"
},
{
"textRaw": "`writable` {WritableStream}",
"name": "writable",
"type": "WritableStream"
}
]
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`allowHalfOpen` {boolean}",
"name": "allowHalfOpen",
"type": "boolean"
},
{
"textRaw": "`decodeStrings` {boolean}",
"name": "decodeStrings",
"type": "boolean"
},
{
"textRaw": "`encoding` {string}",
"name": "encoding",
"type": "string"
},
{
"textRaw": "`highWaterMark` {number}",
"name": "highWaterMark",
"type": "number"
},
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
},
{
"textRaw": "`signal` {AbortSignal}",
"name": "signal",
"type": "AbortSignal"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Duplex}",
"name": "return",
"type": "stream.Duplex"
}
}
],
"desc": "import { Duplex } from 'node:stream';\nimport {\n ReadableStream,\n WritableStream,\n} from 'node:stream/web';\n\nconst readable = new ReadableStream({\n start(controller) {\n controller.enqueue('world');\n },\n});\n\nconst writable = new WritableStream({\n write(chunk) {\n console.log('writable', chunk);\n },\n});\n\nconst pair = {\n readable,\n writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\n\nfor await (const chunk of duplex) {\n console.log('readable', chunk);\n}\n\nconst { Duplex } = require('node:stream');\nconst {\n ReadableStream,\n WritableStream,\n} = require('node:stream/web');\n\nconst readable = new ReadableStream({\n start(controller) {\n controller.enqueue('world');\n },\n});\n\nconst writable = new WritableStream({\n write(chunk) {\n console.log('writable', chunk);\n },\n});\n\nconst pair = {\n readable,\n writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\nduplex.once('readable', () => console.log('readable', duplex.read()));\n"
},
{
"textRaw": "`stream.Duplex.toWeb(streamDuplex[, options])`",
"name": "toWeb",
"type": "method",
"meta": {
"added": [
"v17.0.0"
],
"changes": [
{
"version": "v25.7.0",
"pr-url": "https://github.com/nodejs/node/pull/61632",
"description": "Added the 'readableType' option to specify the ReadableStream type. The 'type' option is deprecated."
},
{
"version": "v25.4.0",
"pr-url": "https://github.com/nodejs/node/pull/58664",
"description": "Added the 'type' option to specify the ReadableStream type."
},
{
"version": [
"v24.0.0",
"v22.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/57513",
"description": "Marking the API stable."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`streamDuplex` {stream.Duplex}",
"name": "streamDuplex",
"type": "stream.Duplex"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`readableType` {string} Specifies the type of the `ReadableStream` half of the created readable-writable pair. Must be `'bytes'` or undefined. (`options.type` is a deprecated alias for this option.)",
"name": "readableType",
"type": "string",
"desc": "Specifies the type of the `ReadableStream` half of the created readable-writable pair. Must be `'bytes'` or undefined. (`options.type` is a deprecated alias for this option.)"
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object",
"options": [
{
"textRaw": "`readable` {ReadableStream}",
"name": "readable",
"type": "ReadableStream"
},
{
"textRaw": "`writable` {WritableStream}",
"name": "writable",
"type": "WritableStream"
}
]
}
}
],
"desc": "import { Duplex } from 'node:stream';\n\nconst duplex = Duplex({\n objectMode: true,\n read() {\n this.push('world');\n this.push(null);\n },\n write(chunk, encoding, callback) {\n console.log('writable', chunk);\n callback();\n },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nconst { value } = await readable.getReader().read();\nconsole.log('readable', value);\n\nconst { Duplex } = require('node:stream');\n\nconst duplex = Duplex({\n objectMode: true,\n read() {\n this.push('world');\n this.push(null);\n },\n write(chunk, encoding, callback) {\n console.log('writable', chunk);\n callback();\n },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nreadable.getReader().read().then((result) => {\n console.log('readable', result.value);\n});\n"
},
{
"textRaw": "`stream.addAbortSignal(signal, stream)`",
"name": "addAbortSignal",
"type": "method",
"meta": {
"added": [
"v15.4.0"
],
"changes": [
{
"version": [
"v19.7.0",
"v18.16.0"
],
"pr-url": "https://github.com/nodejs/node/pull/46273",
"description": "Added support for `ReadableStream` and `WritableStream`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`signal` {AbortSignal} A signal representing possible cancellation",
"name": "signal",
"type": "AbortSignal",
"desc": "A signal representing possible cancellation"
},
{
"textRaw": "`stream` {Stream|ReadableStream|WritableStream} A stream to attach a signal to.",
"name": "stream",
"type": "Stream|ReadableStream|WritableStream",
"desc": "A stream to attach a signal to."
}
]
}
],
"desc": "Attaches an AbortSignal to a readable or writeable stream. This lets code\ncontrol stream destruction using an AbortController.
Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the stream, and controller.error(new AbortError()) for webstreams.
const fs = require('node:fs');\n\nconst controller = new AbortController();\nconst read = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json')),\n);\n// Later, abort the operation closing the stream\ncontroller.abort();\n\nOr using an AbortSignal with a readable stream as an async iterable:
const controller = new AbortController();\nsetTimeout(() => controller.abort(), 10_000); // set a timeout\nconst stream = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json')),\n);\n(async () => {\n try {\n for await (const chunk of stream) {\n await process(chunk);\n }\n } catch (e) {\n if (e.name === 'AbortError') {\n // The operation was cancelled\n } else {\n throw e;\n }\n }\n})();\n\nOr using an AbortSignal with a ReadableStream:
const controller = new AbortController();\nconst rs = new ReadableStream({\n start(controller) {\n controller.enqueue('hello');\n controller.enqueue('world');\n controller.close();\n },\n});\n\naddAbortSignal(controller.signal, rs);\n\nfinished(rs, (err) => {\n if (err) {\n if (err.name === 'AbortError') {\n // The operation was cancelled\n }\n }\n});\n\nconst reader = rs.getReader();\n\nreader.read().then(({ value, done }) => {\n console.log(value); // hello\n console.log(done); // false\n controller.abort();\n});\n"
},
{
"textRaw": "`stream.getDefaultHighWaterMark(objectMode)`",
"name": "getDefaultHighWaterMark",
"type": "method",
"meta": {
"added": [
"v19.9.0",
"v18.17.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`objectMode` {boolean}",
"name": "objectMode",
"type": "boolean"
}
],
"return": {
"textRaw": "Returns: {integer}",
"name": "return",
"type": "integer"
}
}
],
"desc": "Returns the default highWaterMark used by streams.\nDefaults to 65536 (64 KiB), or 16 for objectMode.
Sets the default highWaterMark used by streams.
" }, { "textRaw": "`readable.read(0)`", "name": "read", "type": "method", "signatures": [ { "params": [ { "name": "0" } ] } ], "desc": "There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.
If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.
While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.
Use of readable.push('') is not recommended.
Pushing a zero-byte <string>, <Buffer>, <TypedArray> or <DataView> to a stream\nthat is not in object mode has an interesting side effect.\nBecause it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.
The node:string_decoder module provides an API for decoding Buffer objects\ninto strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16\ncharacters. It can be accessed using:
import { StringDecoder } from 'node:string_decoder';\n\nconst { StringDecoder } = require('node:string_decoder');\n\nThe following example shows the basic use of the StringDecoder class.
import { StringDecoder } from 'node:string_decoder';\nimport { Buffer } from 'node:buffer';\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent)); // Prints: ¢\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro)); // Prints: €\n\nconst { StringDecoder } = require('node:string_decoder');\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent)); // Prints: ¢\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro)); // Prints: €\n\nWhen a Buffer instance is written to the StringDecoder instance, an\ninternal buffer is used to ensure that the decoded string does not contain\nany incomplete multibyte characters. These are held in the buffer until the\nnext call to stringDecoder.write() or until stringDecoder.end() is called.
In the following example, the three UTF-8 encoded bytes of the European Euro\nsymbol (€) are written over three separate operations:
import { StringDecoder } from 'node:string_decoder';\nimport { Buffer } from 'node:buffer';\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC]))); // Prints: €\n\nconst { StringDecoder } = require('node:string_decoder');\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC]))); // Prints: €\n",
"classes": [
{
"textRaw": "Class: `StringDecoder`",
"name": "StringDecoder",
"type": "class",
"signatures": [
{
"textRaw": "`new StringDecoder([encoding])`",
"name": "StringDecoder",
"type": "ctor",
"meta": {
"added": [
"v0.1.99"
],
"changes": []
},
"params": [
{
"textRaw": "`encoding` {string} The character encoding the `StringDecoder` will use. **Default:** `'utf8'`.",
"name": "encoding",
"type": "string",
"default": "`'utf8'`",
"desc": "The character encoding the `StringDecoder` will use.",
"optional": true
}
],
"desc": "Creates a new StringDecoder instance.
Returns any remaining input stored in the internal buffer as a string. Bytes\nrepresenting incomplete UTF-8 and UTF-16 characters will be replaced with\nsubstitution characters appropriate for the character encoding.
\nIf the buffer argument is provided, one final call to stringDecoder.write()\nis performed before returning the remaining input.\nAfter end() is called, the stringDecoder object can be reused for new input.
Returns a decoded string, ensuring that any incomplete multibyte characters at\nthe end of the Buffer, or TypedArray, or DataView are omitted from the\nreturned string and stored in an internal buffer for the next call to\nstringDecoder.write() or stringDecoder.end().
The node:test module facilitates the creation of JavaScript tests.\nTo access it:
import test from 'node:test';\n\nconst test = require('node:test');\n\nThis module is only available under the node: scheme.
Tests created via the test module consist of a single function that is\nprocessed in one of three ways:
Promise that is considered failing if the\nPromise rejects, and is considered passing if the Promise fulfills.Promise, the test will fail.The following example illustrates how tests are written using the\ntest module.
test('synchronous passing test', (t) => {\n // This test passes because it does not throw an exception.\n assert.strictEqual(1, 1);\n});\n\ntest('synchronous failing test', (t) => {\n // This test fails because it throws an exception.\n assert.strictEqual(1, 2);\n});\n\ntest('asynchronous passing test', async (t) => {\n // This test passes because the Promise returned by the async\n // function is settled and not rejected.\n assert.strictEqual(1, 1);\n});\n\ntest('asynchronous failing test', async (t) => {\n // This test fails because the Promise returned by the async\n // function is rejected.\n assert.strictEqual(1, 2);\n});\n\ntest('failing test using Promises', (t) => {\n // Promises can be used directly as well.\n return new Promise((resolve, reject) => {\n setImmediate(() => {\n reject(new Error('this will cause the test to fail'));\n });\n });\n});\n\ntest('callback passing test', (t, done) => {\n // done() is the callback function. When the setImmediate() runs, it invokes\n // done() with no arguments.\n setImmediate(done);\n});\n\ntest('callback failing test', (t, done) => {\n // When the setImmediate() runs, done() is invoked with an Error object and\n // the test fails.\n setImmediate(() => {\n done(new Error('callback failure'));\n });\n});\n\nIf any tests fail, the process exit code is set to 1.
The test context's test() method allows subtests to be created.\nIt allows you to structure your tests in a hierarchical manner,\nwhere you can create nested tests within a larger test.\nThis method behaves identically to the top level test() function.\nThe following example demonstrates the creation of a\ntop level test with two subtests.
test('top level test', async (t) => {\n await t.test('subtest 1', (t) => {\n assert.strictEqual(1, 1);\n });\n\n await t.test('subtest 2', (t) => {\n assert.strictEqual(2, 2);\n });\n});\n\n\n\nNote:
\nbeforeEachandafterEachhooks are triggered\nbetween each subtest execution.
In this example, await is used to ensure that both subtests have completed.\nThis is necessary because tests do not wait for their subtests to\ncomplete, unlike tests created within suites.\nAny subtests that are still outstanding when their parent finishes\nare cancelled and treated as failures. Any subtest failures cause the parent\ntest to fail.
The test runner supports persisting the state of the run to a file, allowing\nthe test runner to rerun failed tests without having to re-run the entire test suite.\nUse the --test-rerun-failures command-line option to specify a file path where the\nstate of the run is stored. if the state file does not exist, the test runner will\ncreate it.\nthe state file is a JSON file that contains an array of run attempts.\nEach run attempt is an object mapping successful tests to the attempt they have passed in.\nThe key identifying a test in this map is the test file path, with the line and column where the test is defined.\nin a case where a test defined in a specific location is run multiple times,\nfor example within a function or a loop,\na counter will be appended to the key, to disambiguate the test runs.\nnote changing the order of test execution or the location of a test can lead the test runner\nto consider tests as passed on a previous attempt,\nmeaning --test-rerun-failures should be used when tests run in a deterministic order.
example of a state file:
\n[\n {\n \"test.js:10:5\": { \"passed_on_attempt\": 0, \"name\": \"test 1\" }\n },\n {\n \"test.js:10:5\": { \"passed_on_attempt\": 0, \"name\": \"test 1\" },\n \"test.js:20:5\": { \"passed_on_attempt\": 1, \"name\": \"test 2\" }\n }\n]\n\nin this example, there are two run attempts, with two tests defined in test.js,\nthe first test succeeded on the first attempt, and the second test succeeded on the second attempt.
When the --test-rerun-failures option is used, the test runner will only run tests that have not yet passed.
node --test-rerun-failures /path/to/state/file\n",
"displayName": "Rerunning failed tests"
},
{
"textRaw": "`describe()` and `it()` aliases",
"name": "`describe()`_and_`it()`_aliases",
"type": "module",
"desc": "Suites and tests can also be written using the describe() and it()\nfunctions. describe() is an alias for suite(), and it() is an\nalias for test().
describe('A thing', () => {\n it('should work', () => {\n assert.strictEqual(1, 1);\n });\n\n it('should be ok', () => {\n assert.strictEqual(2, 2);\n });\n\n describe('a nested thing', () => {\n it('should work', () => {\n assert.strictEqual(3, 3);\n });\n });\n});\n\ndescribe() and it() are imported from the node:test module.
import { describe, it } from 'node:test';\n\nconst { describe, it } = require('node:test');\n",
"displayName": "`describe()` and `it()` aliases"
},
{
"textRaw": "Skipping tests",
"name": "skipping_tests",
"type": "module",
"desc": "Individual tests can be skipped by passing the skip option to the test, or by\ncalling the test context's skip() method as shown in the\nfollowing example.
// The skip option is used, but no message is provided.\ntest('skip option', { skip: true }, (t) => {\n // This code is never executed.\n});\n\n// The skip option is used, and a message is provided.\ntest('skip option with message', { skip: 'this is skipped' }, (t) => {\n // This code is never executed.\n});\n\ntest('skip() method', (t) => {\n // Make sure to return here as well if the test contains additional logic.\n t.skip();\n});\n\ntest('skip() method with message', (t) => {\n // Make sure to return here as well if the test contains additional logic.\n t.skip('this is skipped');\n});\n",
"displayName": "Skipping tests"
},
{
"textRaw": "TODO tests",
"name": "todo_tests",
"type": "module",
"desc": "Individual tests can be marked as flaky or incomplete by passing the todo\noption to the test, or by calling the test context's todo() method, as shown\nin the following example. These tests represent a pending implementation or bug\nthat needs to be fixed. TODO tests are executed, but are not treated as test\nfailures, and therefore do not affect the process exit code. If a test is marked\nas both TODO and skipped, the TODO option is ignored.
// The todo option is used, but no message is provided.\ntest('todo option', { todo: true }, (t) => {\n // This code is executed, but not treated as a failure.\n throw new Error('this does not fail the test');\n});\n\n// The todo option is used, and a message is provided.\ntest('todo option with message', { todo: 'this is a todo test' }, (t) => {\n // This code is executed.\n});\n\ntest('todo() method', (t) => {\n t.todo();\n});\n\ntest('todo() method with message', (t) => {\n t.todo('this is a todo test and is not treated as a failure');\n throw new Error('this does not fail the test');\n});\n",
"displayName": "TODO tests"
},
{
"textRaw": "Expecting tests to fail",
"name": "expecting_tests_to_fail",
"type": "module",
"meta": {
"added": [
"v25.5.0"
],
"changes": []
},
"desc": "This flips the pass/fail reporting for a specific test or suite: a flagged test\ncase must throw in order to pass, and a flagged test case that does not throw\nfails.
\nIn each of the following, doTheThing() fails to return true, but since the\ntests are flagged expectFailure, they pass.
it.expectFailure('should do the thing', () => {\n assert.strictEqual(doTheThing(), true);\n});\n\nit('should do the thing', { expectFailure: true }, () => {\n assert.strictEqual(doTheThing(), true);\n});\n\nit('should do the thing', { expectFailure: 'feature not implemented' }, () => {\n assert.strictEqual(doTheThing(), true);\n});\n\n