{ "miscs": [ { "textRaw": "About this documentation", "name": "About this documentation", "introduced_in": "v0.10.0", "type": "misc", "desc": "

Welcome to the official API reference documentation for Node.js!

\n

Node.js is a JavaScript runtime built on the V8 JavaScript engine.

", "miscs": [ { "textRaw": "Contributing", "name": "contributing", "desc": "

Report errors in this documentation in the issue tracker. See\nthe contributing guide for directions on how to submit pull requests.

", "type": "misc", "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.

\n

The stability indices are as follows:

\n
\n

Stability: 0 - Deprecated. The feature may emit warnings. Backward\ncompatibility is not guaranteed.

\n
\n\n
\n

Stability: 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.

\n
\n\n
\n

Stability: 2 - Stable. Compatibility with the npm ecosystem is a high\npriority.

\n
\n\n
\n

Stability: 3 - Legacy. The feature is no longer recommended for use. While it\nlikely will not be removed, and is still covered by semantic-versioning\nguarantees, use of the feature should be avoided.

\n
\n

Use caution when making use of Experimental features, particularly within\nmodules. Users may not be aware that experimental features are being used.\nBugs 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", "desc": "\n", "type": "misc", "displayName": "Stability overview" }, { "textRaw": "JSON output", "name": "json_output", "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.

", "type": "misc", "displayName": "JSON output" }, { "textRaw": "System calls and man pages", "name": "system_calls_and_man_pages", "desc": "

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.

\n

Most Unix system calls have Windows analogues. Still, behavior differences may\nbe unavoidable.

", "type": "misc", "displayName": "System calls and man pages" } ], "source": "doc/api/documentation.md" }, { "textRaw": "C++ addons", "name": "C++ addons", "introduced_in": "v0.10.0", "type": "misc", "desc": "

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.

\n

There are three options for implementing addons: Node-API, nan, or direct\nuse of internal V8, libuv and Node.js libraries. Unless there is a need for\ndirect access to functionality which is not exposed by Node-API, use Node-API.\nRefer to C/C++ addons with Node-API for more information on\nNode-API.

\n

When not using Node-API, implementing addons is complicated,\ninvolving knowledge of several components and APIs:

\n\n

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", "desc": "

This \"Hello world\" example is a simple addon, written in C++, that is the\nequivalent of the following JavaScript code:

\n
module.exports.hello = () => 'world';\n
\n

First, create the file hello.cc:

\n
// hello.cc\n#include <node.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 Method(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n  args.GetReturnValue().Set(String::NewFromUtf8(\n      isolate, \"world\").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
\n

All Node.js addons must export an initialization function following\nthe pattern:

\n
void Initialize(Local<Object> exports);\nNODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)\n
\n

There is no semi-colon after NODE_MODULE as it's not a function (see\nnode.h).

\n

The module_name must match the filename of the final binary (excluding\nthe .node suffix).

\n

In the hello.cc example, then, the initialization function is Initialize\nand the addon module name is addon.

\n

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().

", "modules": [ { "textRaw": "Context-aware addons", "name": "context-aware_addons", "desc": "

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.

\n

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:

\n
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
\n

Another 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.

\n

The following three variables may be used inside the function body following an\ninvocation of NODE_MODULE_INIT():

\n\n

The choice to build a context-aware addon carries with it the responsibility of\ncarefully managing global static data. 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.

\n

The context-aware addon can be structured to avoid global static data by\nperforming the following steps:

\n\n

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.

\n

The 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 = context->GetIsolate();\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", "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:

\n\n

In order to support Worker threads, addons need to clean up any resources\nthey may have allocated when such a thread exists. This can be achieved through\nthe usage of the AddEnvironmentCleanupHook() function:

\n
void AddEnvironmentCleanupHook(v8::Isolate* isolate,\n                               void (*fun)(void* arg),\n                               void* arg);\n
\n

This 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.

\n

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.

\n

The following addon.cc uses AddEnvironmentCleanupHook:

\n
// 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 = context->GetIsolate();\n\n  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);\n  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);\n}\n
\n

Test in JavaScript by running:

\n
// test.js\nrequire('./build/Release/addon');\n
", "type": "module", "displayName": "Worker support" } ], "type": "module", "displayName": "Context-aware addons" }, { "textRaw": "Building", "name": "building", "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
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"hello.cc\" ]\n    }\n  ]\n}\n
\n

A 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.

\n

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.

\n

Next, invoke the node-gyp build command to generate the compiled addon.node\nfile. This will be put into the build/Release/ directory.

\n

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.

\n

Once built, the binary addon can be used from within Node.js by pointing\nrequire() to the built addon.node module:

\n
// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n
\n

Because 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.

\n

While the bindings package implementation is more sophisticated in how it\nlocates addon modules, it is essentially using a try…catch pattern similar to:

\n
try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n
", "type": "module", "displayName": "Building" }, { "textRaw": "Linking to libraries included with Node.js", "name": "linking_to_libraries_included_with_node.js", "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:

\n", "type": "module", "displayName": "Linking to libraries included with Node.js" }, { "textRaw": "Loading addons using `require()`", "name": "loading_addons_using_`require()`", "desc": "

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.

\n

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.

", "type": "module", "displayName": "Loading addons using `require()`" } ], "type": "misc", "displayName": "Hello world" }, { "textRaw": "Native abstractions for Node.js", "name": "native_abstractions_for_node.js", "desc": "

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.

\n

The 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.

", "type": "misc", "displayName": "Native abstractions for Node.js" }, { "textRaw": "Node-API", "name": "node-api", "stability": 2, "stabilityText": "Stable", "desc": "

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.

\n

Creating and maintaining an addon that benefits from the ABI stability\nprovided by Node-API carries with it certain\nimplementation considerations.

\n

To use Node-API in the above \"Hello world\" example, replace the content of\nhello.cc with the following. All other instructions remain the same.

\n
// 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
\n

The functions available and how to use them are documented in\nC/C++ addons with Node-API.

", "type": "misc", "displayName": "Node-API" }, { "textRaw": "Addon examples", "name": "addon_examples", "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.

\n

Each of these examples using the following binding.gyp file:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [ \"addon.cc\" ]\n    }\n  ]\n}\n
\n

In cases where there is more than one .cc file, simply add the additional\nfilename to the sources array:

\n
\"sources\": [\"addon.cc\", \"myexample.cc\"]\n
\n

Once the binding.gyp file is ready, the example addons can be configured and\nbuilt using node-gyp:

\n
$ node-gyp configure build\n
", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "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.

\n

The 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
\n

Once 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
", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "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
\n

This 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.

\n

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
\n

In this example, the callback function is invoked synchronously.

", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "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():

\n
// 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
\n

To 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
", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "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
\n

To test:

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n
", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "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:

\n
// 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
\n

Then, in myobject.h, the wrapper class inherits from node::ObjectWrap:

\n
// 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
\n

In myobject.cc, implement the various methods that are to be exposed.\nBelow, the method plusOne() is exposed by adding it to the constructor's\nprototype:

\n
// 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 = exports->GetIsolate();\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).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.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
\n

To build this example, the myobject.cc file must be added to the\nbinding.gyp:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
\n

Test 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
\n

The 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.

", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "

Alternatively, it is possible to use a factory pattern to avoid explicitly\ncreating object instances using the JavaScript new operator:

\n
const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n
\n

First, the createObject() method is implemented in addon.cc:

\n
// 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(exports->GetIsolate());\n\n  NODE_SET_METHOD(module, \"exports\", CreateObject);\n}\n\nNODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)\n\n}  // namespace demo\n
\n

In myobject.h, the static method NewInstance() is added to handle\ninstantiating the object. This method takes the place of using new in\nJavaScript:

\n
// 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::Isolate* isolate);\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
\n

The implementation in myobject.cc is similar to the previous example:

\n
// 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(Isolate* isolate) {\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.Holder());\n  obj->value_ += 1;\n\n  args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n}  // namespace demo\n
\n

Once again, to build this example, the myobject.cc file must be added to the\nbinding.gyp:

\n
{\n  \"targets\": [\n    {\n      \"target_name\": \"addon\",\n      \"sources\": [\n        \"addon.cc\",\n        \"myobject.cc\"\n      ]\n    }\n  ]\n}\n
\n

Test 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
", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "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:

\n
// 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(exports->GetIsolate());\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
\n

In myobject.h, a new public method is added to allow access to private values\nafter unwrapping the object.

\n
// 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::Isolate* isolate);\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
\n

The implementation of myobject.cc is similar to before:

\n
// 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(Isolate* isolate) {\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
\n

Test 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
", "type": "module", "displayName": "Passing wrapped objects around" } ], "type": "misc", "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.

\n

Addons 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.

\n

APIs 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:

\n\n

Node-API is a C API that ensures ABI stability across Node.js versions\nand different compiler levels. A C++ API can be easier to use.\nTo support using C++, the project maintains a\nC++ wrapper module called node-addon-api.\nThis wrapper provides an inlineable C++ API. Binaries built\nwith node-addon-api will depend on the symbols for the Node-API C-based\nfunctions exported by Node.js. node-addon-api is a more\nefficient way to write code that calls Node-API. Take, for example, the\nfollowing node-addon-api code. The first section shows the\nnode-addon-api code and the second section shows what actually gets\nused in the addon.

\n
Object obj = Object::New(env);\nobj[\"foo\"] = String::New(env, \"bar\");\n
\n
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
\n

The end result is that the addon only uses the exported C APIs. As a result,\nit still gets the benefits of the ABI stability provided by the C API.

\n

When using node-addon-api instead of the C APIs, start with the API docs\nfor node-addon-api.

\n

The Node-API Resource offers\nan excellent orientation and tips for developers just getting started with\nNode-API and node-addon-api.

", "miscs": [ { "textRaw": "Implications of ABI stability", "name": "implications_of_abi_stability", "desc": "

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:

\n\n

Thus, 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
\n

and by checking, for all external libraries that it uses, that the external\nlibrary makes ABI stability guarantees similar to Node-API.

", "type": "misc", "displayName": "Implications of ABI stability" }, { "textRaw": "Building", "name": "building", "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.

\n

For 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.

\n

For 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:

\n
xcode-select --install\n
\n

For 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:

\n
npm install --global windows-build-tools\n
\n

The sections below describe the additional tools available for developing\nand deploying Node.js native addons.

", "modules": [ { "textRaw": "Build tools", "name": "build_tools", "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", "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.

\n

Historically, 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.

", "type": "module", "displayName": "node-gyp" } ], "properties": [ { "textRaw": "CMake.js", "name": "js", "desc": "

CMake.js is an alternative build system based on CMake.

\n

CMake.js is a good choice for projects that already use CMake or for\ndevelopers affected by limitations in node-gyp.

" } ], "type": "module", "displayName": "Build tools" }, { "textRaw": "Uploading precompiled binaries", "name": "uploading_precompiled_binaries", "desc": "

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", "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.

", "type": "module", "displayName": "node-pre-gyp" }, { "textRaw": "prebuild", "name": "prebuild", "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.

", "type": "module", "displayName": "prebuild" }, { "textRaw": "prebuildify", "name": "prebuildify", "desc": "

prebuildify is a tool based on node-gyp. The advantage of prebuildify is\nthat the built binaries are bundled with the native module when it's\nuploaded to npm. The binaries are downloaded from npm and are immediately\navailable to the module user when the native module is installed.

", "type": "module", "displayName": "prebuildify" } ], "type": "module", "displayName": "Uploading precompiled binaries" } ], "type": "misc", "displayName": "Building" }, { "textRaw": "Usage", "name": "usage", "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:

\n
#include <node_api.h>\n
\n

This 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:

\n
#define NAPI_VERSION 3\n#include <node_api.h>\n
\n

This restricts the Node-API surface to just the functionality that was available\nin the specified (and earlier) versions.

\n

Some of the Node-API surface is experimental and requires explicit opt-in:

\n
#define NAPI_EXPERIMENTAL\n#include <node_api.h>\n
\n

In this case the entire API surface, including any experimental APIs, will be\navailable to the module code.

", "type": "misc", "displayName": "Usage" }, { "textRaw": "Node-API version matrix", "name": "node-api_version_matrix", "desc": "

Node-API versions are additive and versioned independently from Node.js.\nVersion 4 is an extension to version 3 in that it has all of the APIs\nfrom version 3 with some additions. This means that it is not necessary\nto recompile for new versions of Node.js which are\nlisted as supporting a later version.

\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
123
v6.xv6.14.2*
v8.xv8.6.0**v8.10.0*v8.11.2
v9.xv9.0.0*v9.3.0*v9.11.0*
≥ v10.xall releasesall releasesall releases
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
45678
v10.xv10.16.0v10.17.0v10.20.0v10.23.0
v11.xv11.8.0
v12.xv12.0.0v12.11.0v12.17.0v12.19.0v12.22.0
v13.xv13.0.0v13.0.0
v14.xv14.0.0v14.0.0v14.0.0v14.12.0v14.17.0
v15.xv15.0.0v15.0.0v15.0.0v15.0.0v15.12.0
v16.xv16.0.0v16.0.0v16.0.0v16.0.0v16.0.0
\n

* 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.

\n

Each 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.

\n

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.

\n

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.

\n

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.

\n
// 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 NAPI_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      bool is_pending;                                            \\\n      napi_is_exception_pending((env), &is_pending);              \\\n      if (!is_pending) {                                          \\\n        const char* message = (error_info->error_message == NULL) \\\n            ? \"empty error message\"                               \\\n            : error_info->error_message;                          \\\n        napi_throw_error((env), NULL, message);                   \\\n        return NULL;                                              \\\n      }                                                           \\\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  NAPI_CALL(env, napi_create_object(env, &result));\n\n  napi_value exported_function;\n  NAPI_CALL(env, napi_create_function(env,\n                                      \"doSomethingUseful\",\n                                      NAPI_AUTO_LENGTH,\n                                      DoSomethingUseful,\n                                      NULL,\n                                      &exported_function));\n\n  NAPI_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() {\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
", "type": "misc", "displayName": "Node-API version matrix" }, { "textRaw": "Environment life cycle APIs", "name": "environment_life_cycle_apis", "desc": "

Section 8.7 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.

\n

A 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.

\n

From 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.

\n

Native addons may need to allocate global state which they use during\ntheir entire life cycle such that the state must be unique to each instance of\nthe addon.

\n

To this end, Node-API provides a way to allocate data such that its life cycle\nis tied to the life cycle of the Agent.

", "modules": [ { "textRaw": "napi_set_instance_data", "name": "napi_set_instance_data", "meta": { "added": [ "v12.8.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_set_instance_data(napi_env env,\n                                   void* data,\n                                   napi_finalize finalize_cb,\n                                   void* finalize_hint);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API associates data with the currently running Agent. data can later\nbe retrieved using napi_get_instance_data(). Any existing data associated with\nthe currently running Agent which was set by means of a previous call to\nnapi_set_instance_data() will be overwritten. If a finalize_cb was provided\nby the previous call, it will not be called.

", "type": "module", "displayName": "napi_set_instance_data" }, { "textRaw": "napi_get_instance_data", "name": "napi_get_instance_data", "meta": { "added": [ "v12.8.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_get_instance_data(napi_env env,\n                                   void** data);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API retrieves data that was previously associated with the currently\nrunning Agent via napi_set_instance_data(). If no data is set, the call will\nsucceed and data will be set to NULL.

", "type": "module", "displayName": "napi_get_instance_data" } ], "type": "misc", "displayName": "Environment life cycle APIs" }, { "textRaw": "Basic Node-API data types", "name": "basic_node-api_data_types", "desc": "

Node-API exposes the following fundamental datatypes 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", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

Integral status code indicating the success or failure of a Node-API call.\nCurrently, the following status codes are supported.

\n
typedef 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_status;\n
\n

If additional information is required upon an API returning a failed status,\nit can be obtained by calling napi_get_last_error_info.

", "type": "module", "displayName": "napi_status" }, { "textRaw": "napi_extended_error_info", "name": "napi_extended_error_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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
\n\n

See the Error handling section for additional information.

", "type": "module", "displayName": "napi_extended_error_info" }, { "textRaw": "napi_env", "name": "napi_env", "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.

", "type": "module", "displayName": "napi_env" }, { "textRaw": "napi_value", "name": "napi_value", "desc": "

This is an opaque pointer that is used to represent a JavaScript value.

", "type": "module", "displayName": "napi_value" }, { "textRaw": "napi_threadsafe_function", "name": "napi_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "

This is an opaque pointer that represents a JavaScript function which can be\ncalled asynchronously from multiple threads via\nnapi_call_threadsafe_function().

", "type": "module", "displayName": "napi_threadsafe_function" }, { "textRaw": "napi_threadsafe_function_release_mode", "name": "napi_threadsafe_function_release_mode", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "

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().

\n
typedef enum {\n  napi_tsfn_release,\n  napi_tsfn_abort\n} napi_threadsafe_function_release_mode;\n
", "type": "module", "displayName": "napi_threadsafe_function_release_mode" }, { "textRaw": "napi_threadsafe_function_call_mode", "name": "napi_threadsafe_function_call_mode", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "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.

\n
typedef enum {\n  napi_tsfn_nonblocking,\n  napi_tsfn_blocking\n} napi_threadsafe_function_call_mode;\n
", "type": "module", "displayName": "napi_threadsafe_function_call_mode" }, { "textRaw": "Node-API memory management types", "name": "node-api_memory_management_types", "modules": [ { "textRaw": "napi_handle_scope", "name": "napi_handle_scope", "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.

\n

Handle 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.

\n

For more details, review the Object lifetime management.

", "type": "module", "displayName": "napi_handle_scope" }, { "textRaw": "napi_escapable_handle_scope", "name": "napi_escapable_handle_scope", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

Escapable handle scopes are a special type of handle scope to return values\ncreated within a particular handle scope to a parent scope.

", "type": "module", "displayName": "napi_escapable_handle_scope" }, { "textRaw": "napi_ref", "name": "napi_ref", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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.

\n

For more details, review the Object lifetime management.

", "type": "module", "displayName": "napi_ref" }, { "textRaw": "napi_type_tag", "name": "napi_type_tag", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "napiVersion": [ 8 ], "changes": [] }, "desc": "

A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID\nwith which JavaScript objects can be \"tagged\" in order to ensure that they are\nof a certain type. This is a stronger check than napi_instanceof, because\nthe latter can report a false positive if the object's prototype has been\nmanipulated. Type-tagging is most useful in conjunction with napi_wrap\nbecause it ensures that the pointer retrieved from a wrapped object can be\nsafely cast to the native type corresponding to the type tag that had been\npreviously applied to the JavaScript object.

\n
typedef struct {\n  uint64_t lower;\n  uint64_t upper;\n} napi_type_tag;\n
", "type": "module", "displayName": "napi_type_tag" }, { "textRaw": "napi_async_cleanup_hook_handle", "name": "napi_async_cleanup_hook_handle", "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.

", "type": "module", "displayName": "napi_async_cleanup_hook_handle" } ], "type": "module", "displayName": "Node-API memory management types" }, { "textRaw": "Node-API callback types", "name": "node-api_callback_types", "modules": [ { "textRaw": "napi_callback_info", "name": "napi_callback_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "napi_callback_info" }, { "textRaw": "napi_callback", "name": "napi_callback", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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:

\n
typedef napi_value (*napi_callback)(napi_env, napi_callback_info);\n
\n

Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside a napi_callback is not necessary.

", "type": "module", "displayName": "napi_callback" }, { "textRaw": "napi_finalize", "name": "napi_finalize", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

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 with which it was associated with, has been garbage-collected. The user\nmust provide a function satisfying the following signature which would get\ncalled upon the object's collection. Currently, napi_finalize can be used for\nfinding out when objects that have external data are collected.

\n
typedef void (*napi_finalize)(napi_env env,\n                              void* finalize_data,\n                              void* finalize_hint);\n
\n

Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

", "type": "module", "displayName": "napi_finalize" }, { "textRaw": "napi_async_execute_callback", "name": "napi_async_execute_callback", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

\n
typedef void (*napi_async_execute_callback)(napi_env env, void* data);\n
\n

Implementations 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.

", "type": "module", "displayName": "napi_async_execute_callback" }, { "textRaw": "napi_async_complete_callback", "name": "napi_async_complete_callback", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

Function pointer used with functions that support asynchronous\noperations. Callback functions must satisfy the following signature:

\n
typedef void (*napi_async_complete_callback)(napi_env env,\n                                             napi_status status,\n                                             void* data);\n
\n

Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

", "type": "module", "displayName": "napi_async_complete_callback" }, { "textRaw": "napi_threadsafe_function_call_js", "name": "napi_threadsafe_function_call_js", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "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.

\n

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.

\n

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.

\n

Callback functions must satisfy the following signature:

\n
typedef void (*napi_threadsafe_function_call_js)(napi_env env,\n                                                 napi_value js_callback,\n                                                 void* context,\n                                                 void* data);\n
\n\n

Unless for reasons discussed in Object Lifetime Management, creating a\nhandle and/or callback scope inside the function body is not necessary.

", "type": "module", "displayName": "napi_threadsafe_function_call_js" }, { "textRaw": "napi_async_cleanup_hook", "name": "napi_async_cleanup_hook", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "desc": "

Function pointer used with napi_add_async_cleanup_hook. It will be called\nwhen the environment is being torn down.

\n

Callback functions must satisfy the following signature:

\n
typedef void (*napi_async_cleanup_hook)(napi_async_cleanup_hook_handle handle,\n                                        void* data);\n
\n\n

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.

", "type": "module", "displayName": "napi_async_cleanup_hook" } ], "type": "module", "displayName": "Node-API callback types" } ], "type": "misc", "displayName": "Basic Node-API data types" }, { "textRaw": "Error handling", "name": "error_handling", "desc": "

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", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "

All of the Node-API functions share the same error handling pattern. The\nreturn type of all API functions is napi_status.

\n

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.

\n

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.

\n

The full set of possible napi_status values is defined\nin napi_api_types.h.

\n

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.

\n

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:

\n
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
\n\n

napi_get_last_error_info returns the information for the last\nNode-API call that was made.

\n

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", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status\nnapi_get_last_error_info(napi_env env,\n                         const napi_extended_error_info** result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API retrieves a napi_extended_error_info structure with information\nabout the last error that occurred.

\n

The content of the napi_extended_error_info returned is only valid up until\na Node-API function is called on the same env.

\n

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.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_get_last_error_info" } ], "type": "module", "displayName": "Return values" }, { "textRaw": "Exceptions", "name": "exceptions", "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.

\n

If 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.

\n

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.

\n

When an exception is pending one of two approaches can be employed.

\n

The 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.

\n

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.

\n

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 and\nnapi_is_error.

\n

The following utility functions are also available in case native\ncode needs to create an Error object: napi_create_error,\nnapi_create_type_error, and napi_create_range_error,\nwhere result is the napi_value that refers to the newly created\nJavaScript Error object.

\n

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:

\n
originalName [code]\n
\n

where 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:

\n
TypeError [ERR_ERROR_1]\n
", "modules": [ { "textRaw": "napi_throw", "name": "napi_throw", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API throws the JavaScript value provided.

", "type": "module", "displayName": "napi_throw" }, { "textRaw": "napi_throw_error", "name": "napi_throw_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_throw_error(napi_env env,\n                                         const char* code,\n                                         const char* msg);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API throws a JavaScript Error with the text provided.

", "type": "module", "displayName": "napi_throw_error" }, { "textRaw": "napi_throw_type_error", "name": "napi_throw_type_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,\n                                              const char* code,\n                                              const char* msg);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API throws a JavaScript TypeError with the text provided.

", "type": "module", "displayName": "napi_throw_type_error" }, { "textRaw": "napi_throw_range_error", "name": "napi_throw_range_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,\n                                               const char* code,\n                                               const char* msg);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API throws a JavaScript RangeError with the text provided.

", "type": "module", "displayName": "napi_throw_range_error" }, { "textRaw": "napi_is_error", "name": "napi_is_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_is_error(napi_env env,\n                                      napi_value value,\n                                      bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API queries a napi_value to check if it represents an error object.

", "type": "module", "displayName": "napi_is_error" }, { "textRaw": "napi_create_error", "name": "napi_create_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_create_error(napi_env env,\n                                          napi_value code,\n                                          napi_value msg,\n                                          napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns a JavaScript Error with the text provided.

", "type": "module", "displayName": "napi_create_error" }, { "textRaw": "napi_create_type_error", "name": "napi_create_type_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API returns a JavaScript TypeError with the text provided.

", "type": "module", "displayName": "napi_create_type_error" }, { "textRaw": "napi_create_range_error", "name": "napi_create_range_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API returns a JavaScript RangeError with the text provided.

", "type": "module", "displayName": "napi_create_range_error" }, { "textRaw": "napi_get_and_clear_last_exception", "name": "napi_get_and_clear_last_exception", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_and_clear_last_exception(napi_env env,\n                                              napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_get_and_clear_last_exception" }, { "textRaw": "napi_is_exception_pending", "name": "napi_is_exception_pending", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_exception_pending(napi_env env, bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_is_exception_pending" }, { "textRaw": "napi_fatal_exception", "name": "napi_fatal_exception", "meta": { "added": [ "v9.10.0" ], "napiVersion": [ 3 ], "changes": [] }, "desc": "
napi_status napi_fatal_exception(napi_env env, napi_value err);\n
\n\n

Trigger an 'uncaughtException' in JavaScript. Useful if an async\ncallback throws an exception with no way to recover.

", "type": "module", "displayName": "napi_fatal_exception" } ], "type": "module", "displayName": "Exceptions" }, { "textRaw": "Fatal errors", "name": "fatal_errors", "desc": "

In the event of an unrecoverable error in a native module, a fatal error can be\nthrown to immediately terminate the process.

", "modules": [ { "textRaw": "napi_fatal_error", "name": "napi_fatal_error", "meta": { "added": [ "v8.2.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

The function call does not return, the process will be terminated.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_fatal_error" } ], "type": "module", "displayName": "Fatal errors" } ], "type": "misc", "displayName": "Error handling" }, { "textRaw": "Object lifetime management", "name": "object_lifetime_management", "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.

\n

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.

\n

In 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", "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:

\n
for (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
\n

This 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.

\n

To 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.

\n

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.

\n

Taking 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:

\n
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
\n

When 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.

\n

The methods available to open/close escapable scopes are\nnapi_open_escapable_handle_scope and\nnapi_close_escapable_handle_scope.

\n

The request to promote a handle is made through napi_escape_handle which\ncan only be called once.

", "modules": [ { "textRaw": "napi_open_handle_scope", "name": "napi_open_handle_scope", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,\n                                               napi_handle_scope* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API opens a new scope.

", "type": "module", "displayName": "napi_open_handle_scope" }, { "textRaw": "napi_close_handle_scope", "name": "napi_close_handle_scope", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,\n                                                napi_handle_scope scope);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_close_handle_scope" }, { "textRaw": "napi_open_escapable_handle_scope", "name": "napi_open_escapable_handle_scope", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\n    napi_open_escapable_handle_scope(napi_env env,\n                                     napi_handle_scope* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API opens a new scope from which one object can be promoted\nto the outer scope.

", "type": "module", "displayName": "napi_open_escapable_handle_scope" }, { "textRaw": "napi_close_escapable_handle_scope", "name": "napi_close_escapable_handle_scope", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\n    napi_close_escapable_handle_scope(napi_env env,\n                                      napi_handle_scope scope);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API closes the scope passed in. Scopes must be closed in the\nreverse order from which they were created.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_close_escapable_handle_scope" }, { "textRaw": "napi_escape_handle", "name": "napi_escape_handle", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_escape_handle" } ], "type": "module", "displayName": "Making handle lifespan shorter than that of the native method" }, { "textRaw": "References to objects with a lifespan longer than that of the native method", "name": "references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method", "desc": "

In some cases an addon will need to be able to create and reference objects\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 creates 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.

\n

Node-API provides methods to create persistent references to an object.\nEach persistent reference has an associated count with a value of 0\nor higher. The count determines if the reference will keep\nthe corresponding object live. References with a count of 0 do not\nprevent the object from being collected and are often called 'weak'\nreferences. Any count greater than 0 will prevent the object\nfrom being collected.

\n

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.

\n

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.

\n

There 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.

", "modules": [ { "textRaw": "napi_create_reference", "name": "napi_create_reference", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_create_reference(napi_env env,\n                                              napi_value value,\n                                              uint32_t initial_refcount,\n                                              napi_ref* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API create a new reference with the specified reference count\nto the Object passed in.

", "type": "module", "displayName": "napi_create_reference" }, { "textRaw": "napi_delete_reference", "name": "napi_delete_reference", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API deletes the reference passed in.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_delete_reference" }, { "textRaw": "napi_reference_ref", "name": "napi_reference_ref", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_reference_ref(napi_env env,\n                                           napi_ref ref,\n                                           uint32_t* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API increments the reference count for the reference\npassed in and returns the resulting reference count.

", "type": "module", "displayName": "napi_reference_ref" }, { "textRaw": "napi_reference_unref", "name": "napi_reference_unref", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_reference_unref(napi_env env,\n                                             napi_ref ref,\n                                             uint32_t* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API decrements the reference count for the reference\npassed in and returns the resulting reference count.

", "type": "module", "displayName": "napi_reference_unref" }, { "textRaw": "napi_get_reference_value", "name": "napi_get_reference_value", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,\n                                                 napi_ref ref,\n                                                 napi_value* result);\n
\n

the napi_value passed in or out of these methods is a handle to the\nobject to which the reference is related.

\n\n

Returns napi_ok if the API succeeded.

\n

If still valid, this API returns the napi_value representing the\nJavaScript Object associated with the napi_ref. Otherwise, result\nwill be NULL.

", "type": "module", "displayName": "napi_get_reference_value" } ], "type": "module", "displayName": "References to objects with a lifespan longer than that of the native method" }, { "textRaw": "Cleanup on exit of the current Node.js instance", "name": "cleanup_on_exit_of_the_current_node.js_instance", "desc": "

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 instance exits.

\n

Node-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", "meta": { "added": [ "v10.2.0" ], "napiVersion": [ 3 ], "changes": [] }, "desc": "
NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,\n                                                  void (*fun)(void* arg),\n                                                  void* arg);\n
\n

Registers fun as a function to be run with the arg parameter once the\ncurrent Node.js environment exits.

\n

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.

\n

The hooks will be called in reverse order, i.e. the most recently added one\nwill be called first.

\n

Removing 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.

\n

For asynchronous cleanup, napi_add_async_cleanup_hook is available.

", "type": "module", "displayName": "napi_add_env_cleanup_hook" }, { "textRaw": "napi_remove_env_cleanup_hook", "name": "napi_remove_env_cleanup_hook", "meta": { "added": [ "v10.2.0" ], "napiVersion": [ 3 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,\n                                                     void (*fun)(void* arg),\n                                                     void* arg);\n
\n

Unregisters 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.

\n

The function must have originally been registered\nwith napi_add_env_cleanup_hook, otherwise the process will abort.

", "type": "module", "displayName": "napi_remove_env_cleanup_hook" }, { "textRaw": "napi_add_async_cleanup_hook", "name": "napi_add_async_cleanup_hook", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "napiVersion": [ 8 ], "changes": [ { "version": [ "v14.10.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/34819", "description": "Changed signature of the `hook` callback." } ] }, "desc": "
NAPI_EXTERN napi_status napi_add_async_cleanup_hook(\n    napi_env env,\n    napi_async_cleanup_hook hook,\n    void* arg,\n    napi_async_cleanup_hook_handle* remove_handle);\n
\n\n

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.

\n

Unlike napi_add_env_cleanup_hook, the hook is allowed to be asynchronous.

\n

Otherwise, behavior generally matches that of napi_add_env_cleanup_hook.

\n

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.

", "type": "module", "displayName": "napi_add_async_cleanup_hook" }, { "textRaw": "napi_remove_async_cleanup_hook", "name": "napi_remove_async_cleanup_hook", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "version": [ "v14.10.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/34819", "description": "Removed `env` parameter." } ] }, "desc": "
NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(\n    napi_async_cleanup_hook_handle remove_handle);\n
\n\n

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.

", "type": "module", "displayName": "napi_remove_async_cleanup_hook" } ], "type": "module", "displayName": "Cleanup on exit of the current Node.js instance" } ], "type": "misc", "displayName": "Object lifetime management" }, { "textRaw": "Module registration", "name": "module_registration", "desc": "

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:

\n
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)\n
\n

The next difference is the signature for the Init method. For a Node-API\nmodule it is as follows:

\n
napi_value Init(napi_env env, napi_value exports);\n
\n

The 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.

\n

To add the method hello as a function so that it can be called as a method\nprovided by the addon:

\n
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
\n

To set a function to be returned by the require() for the addon:

\n
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
\n

To 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
\n

You can also use the NAPI_MODULE_INIT macro, which acts as a shorthand\nfor NAPI_MODULE and defining an Init function:

\n
NAPI_MODULE_INIT() {\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
\n

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.

\n

The variables env and exports will be available inside the function body\nfollowing the macro invocation.

\n

For more details on setting properties on objects, see the section on\nWorking with JavaScript properties.

\n

For more details on building addon modules in general, refer to the existing\nAPI.

", "type": "misc", "displayName": "Module registration" }, { "textRaw": "Working with JavaScript values", "name": "working_with_javascript_values", "desc": "

Node-API exposes a set of APIs to create all types of JavaScript values.\nSome of these types are documented under Section 6\nof the ECMAScript Language Specification.

\n

Fundamentally, these APIs are used to do one of the following:

\n
    \n
  1. Create a new JavaScript object
  2. \n
  3. Convert from a primitive C type to a Node-API value
  4. \n
  5. Convert from Node-API value to a primitive C type
  6. \n
  7. Get global instances including undefined and null
  8. \n
\n

Node-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.

", "modules": [ { "textRaw": "Enum types", "name": "enum_types", "modules": [ { "textRaw": "napi_key_collection_mode", "name": "napi_key_collection_mode", "meta": { "added": [ "v13.7.0", "v12.17.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
typedef enum {\n  napi_key_include_prototypes,\n  napi_key_own_only\n} napi_key_collection_mode;\n
\n

Describes the Keys/Properties filter enums:

\n

napi_key_collection_mode limits the range of collected properties.

\n

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.

", "type": "module", "displayName": "napi_key_collection_mode" }, { "textRaw": "napi_key_filter", "name": "napi_key_filter", "meta": { "added": [ "v13.7.0", "v12.17.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
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
\n

Property filter bits. They can be or'ed to build a composite filter.

", "type": "module", "displayName": "napi_key_filter" }, { "textRaw": "napi_key_conversion", "name": "napi_key_conversion", "meta": { "added": [ "v13.7.0", "v12.17.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
typedef enum {\n  napi_key_keep_numbers,\n  napi_key_numbers_to_strings\n} napi_key_conversion;\n
\n

napi_key_numbers_to_strings will convert integer indices to\nstrings. napi_key_keep_numbers will return numbers for integer\nindices.

", "type": "module", "displayName": "napi_key_conversion" }, { "textRaw": "napi_valuetype", "name": "napi_valuetype", "desc": "
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
\n

Describes the type of a napi_value. This generally corresponds to the types\ndescribed in Section 6.1 of the ECMAScript Language Specification.\nIn addition to types in that section, napi_valuetype can also represent\nFunctions and Objects with external data.

\n

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.

", "type": "module", "displayName": "napi_valuetype" }, { "textRaw": "napi_typedarray_type", "name": "napi_typedarray_type", "desc": "
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_typedarray_type;\n
\n

This represents the underlying binary scalar datatype of the TypedArray.\nElements of this enum correspond to\nSection 22.2 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_typedarray_type" } ], "type": "module", "displayName": "Enum types" }, { "textRaw": "Object creation functions", "name": "object_creation_functions", "modules": [ { "textRaw": "napi_create_array", "name": "napi_create_array", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_array(napi_env env, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns a Node-API value corresponding to a JavaScript Array type.\nJavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_array" }, { "textRaw": "napi_create_array_with_length", "name": "napi_create_array_with_length", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_array_with_length(napi_env env,\n                                          size_t length,\n                                          napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

\n

JavaScript arrays are described in\nSection 22.1 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_array_with_length" }, { "textRaw": "napi_create_arraybuffer", "name": "napi_create_arraybuffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_arraybuffer(napi_env env,\n                                    size_t byte_length,\n                                    void** data,\n                                    napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

\n

JavaScript ArrayBuffer objects are described in\nSection 24.1 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_arraybuffer" }, { "textRaw": "napi_create_buffer", "name": "napi_create_buffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_buffer(napi_env env,\n                               size_t size,\n                               void** data,\n                               napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API allocates a node::Buffer object. While this is still a\nfully-supported data structure, in most cases using a TypedArray will suffice.

", "type": "module", "displayName": "napi_create_buffer" }, { "textRaw": "napi_create_buffer_copy", "name": "napi_create_buffer_copy", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_create_buffer_copy" }, { "textRaw": "napi_create_date", "name": "napi_create_date", "meta": { "added": [ "v11.11.0", "v10.17.0" ], "napiVersion": [ 5 ], "changes": [] }, "desc": "
napi_status napi_create_date(napi_env env,\n                             double time,\n                             napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

\n

This API allocates a JavaScript Date object.

\n

JavaScript Date objects are described in\nSection 20.3 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_date" }, { "textRaw": "napi_create_external", "name": "napi_create_external", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

\n\n

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.

", "type": "module", "displayName": "napi_create_external" }, { "textRaw": "napi_create_external_arraybuffer", "name": "napi_create_external_arraybuffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

\n\n

JavaScript ArrayBuffers are described in\nSection 24.1 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_external_arraybuffer" }, { "textRaw": "napi_create_external_buffer", "name": "napi_create_external_buffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

The API adds a napi_finalize callback which will be called when the JavaScript\nobject just created is ready for garbage collection. It is similar to\nnapi_wrap() except that:

\n\n

For Node.js >=4 Buffers are Uint8Arrays.

", "type": "module", "displayName": "napi_create_external_buffer" }, { "textRaw": "napi_create_object", "name": "napi_create_object", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_object(napi_env env, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API allocates a default JavaScript Object.\nIt is the equivalent of doing new Object() in JavaScript.

\n

The JavaScript Object type is described in Section 6.1.7 of the\nECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_object" }, { "textRaw": "napi_create_symbol", "name": "napi_create_symbol", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_symbol(napi_env env,\n                               napi_value description,\n                               napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API creates a JavaScript symbol value from a UTF8-encoded C string.

\n

The JavaScript symbol type is described in Section 19.4\nof the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_symbol" }, { "textRaw": "napi_create_typedarray", "name": "napi_create_typedarray", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

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.

\n

JavaScript TypedArray objects are described in\nSection 22.2 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_typedarray" }, { "textRaw": "napi_create_dataview", "name": "napi_create_dataview", "meta": { "added": [ "v8.3.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API creates a JavaScript DataView object over an existing ArrayBuffer.\nDataView objects provide an array-like view over an underlying data buffer,\nbut one which allows items of different size and type in the ArrayBuffer.

\n

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.

\n

JavaScript DataView objects are described in\nSection 24.3 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_dataview" } ], "type": "module", "displayName": "Object creation functions" }, { "textRaw": "Functions to convert from C types to Node-API", "name": "functions_to_convert_from_c_types_to_node-api", "modules": [ { "textRaw": "napi_create_int32", "name": "napi_create_int32", "meta": { "added": [ "v8.4.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to convert from the C int32_t type to the JavaScript\nnumber type.

\n

The JavaScript number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_int32" }, { "textRaw": "napi_create_uint32", "name": "napi_create_uint32", "meta": { "added": [ "v8.4.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to convert from the C uint32_t type to the JavaScript\nnumber type.

\n

The JavaScript number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_uint32" }, { "textRaw": "napi_create_int64", "name": "napi_create_int64", "meta": { "added": [ "v8.4.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to convert from the C int64_t type to the JavaScript\nnumber type.

\n

The JavaScript number type is described in Section 6.1.6\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.

", "type": "module", "displayName": "napi_create_int64" }, { "textRaw": "napi_create_double", "name": "napi_create_double", "meta": { "added": [ "v8.4.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_double(napi_env env, double value, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to convert from the C double type to the JavaScript\nnumber type.

\n

The JavaScript number type is described in\nSection 6.1.6 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_double" }, { "textRaw": "napi_create_bigint_int64", "name": "napi_create_bigint_int64", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_create_bigint_int64(napi_env env,\n                                     int64_t value,\n                                     napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API converts the C int64_t type to the JavaScript BigInt type.

", "type": "module", "displayName": "napi_create_bigint_int64" }, { "textRaw": "napi_create_bigint_uint64", "name": "napi_create_bigint_uint64", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_create_bigint_uint64(napi_env env,\n                                      uint64_t value,\n                                      napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API converts the C uint64_t type to the JavaScript BigInt type.

", "type": "module", "displayName": "napi_create_bigint_uint64" }, { "textRaw": "napi_create_bigint_words", "name": "napi_create_bigint_words", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API converts an array of unsigned 64-bit words into a single BigInt\nvalue.

\n

The resulting BigInt is calculated as: (–1)sign_bit (words[0]\n× (264)0 + words[1] × (264)1 + …)

", "type": "module", "displayName": "napi_create_bigint_words" }, { "textRaw": "napi_create_string_latin1", "name": "napi_create_string_latin1", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_string_latin1(napi_env env,\n                                      const char* str,\n                                      size_t length,\n                                      napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API creates a JavaScript string value from an ISO-8859-1-encoded C\nstring. The native string is copied.

\n

The JavaScript string type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_string_latin1" }, { "textRaw": "napi_create_string_utf16", "name": "napi_create_string_utf16", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_string_utf16(napi_env env,\n                                     const char16_t* str,\n                                     size_t length,\n                                     napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API creates a JavaScript string value from a UTF16-LE-encoded C string.\nThe native string is copied.

\n

The JavaScript string type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_string_utf16" }, { "textRaw": "napi_create_string_utf8", "name": "napi_create_string_utf8", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_string_utf8(napi_env env,\n                                    const char* str,\n                                    size_t length,\n                                    napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API creates a JavaScript string value from a UTF8-encoded C string.\nThe native string is copied.

\n

The JavaScript string type is described in\nSection 6.1.4 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_create_string_utf8" } ], "type": "module", "displayName": "Functions to convert from C types to Node-API" }, { "textRaw": "Functions to convert from Node-API to C types", "name": "functions_to_convert_from_node-api_to_c_types", "modules": [ { "textRaw": "napi_get_array_length", "name": "napi_get_array_length", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_array_length(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns the length of an array.

\n

Array length is described in Section 22.1.4.1 of the ECMAScript Language\nSpecification.

", "type": "module", "displayName": "napi_get_array_length" }, { "textRaw": "napi_get_arraybuffer_info", "name": "napi_get_arraybuffer_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_arraybuffer_info(napi_env env,\n                                      napi_value arraybuffer,\n                                      void** data,\n                                      size_t* byte_length)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to retrieve the underlying data buffer of an ArrayBuffer and\nits length.

\n

WARNING: Use caution while using this API. The lifetime of the underlying data\nbuffer is managed by the ArrayBuffer 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. 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.

", "type": "module", "displayName": "napi_get_arraybuffer_info" }, { "textRaw": "napi_get_buffer_info", "name": "napi_get_buffer_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_buffer_info(napi_env env,\n                                 napi_value value,\n                                 void** data,\n                                 size_t* length)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to retrieve the underlying data buffer of a node::Buffer\nand its length.

\n

Warning: Use caution while using this API since the underlying data buffer's\nlifetime is not guaranteed if it's managed by the VM.

", "type": "module", "displayName": "napi_get_buffer_info" }, { "textRaw": "napi_get_prototype", "name": "napi_get_prototype", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_prototype(napi_env env,\n                               napi_value object,\n                               napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

", "type": "module", "displayName": "napi_get_prototype" }, { "textRaw": "napi_get_typedarray_info", "name": "napi_get_typedarray_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API returns various properties of a typed array.

\n

Warning: Use caution while using this API since the underlying data buffer\nis managed by the VM.

", "type": "module", "displayName": "napi_get_typedarray_info" }, { "textRaw": "napi_get_dataview_info", "name": "napi_get_dataview_info", "meta": { "added": [ "v8.3.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded.

\n

This API returns various properties of a DataView.

", "type": "module", "displayName": "napi_get_dataview_info" }, { "textRaw": "napi_get_date_value", "name": "napi_get_date_value", "meta": { "added": [ "v11.11.0", "v10.17.0" ], "napiVersion": [ 5 ], "changes": [] }, "desc": "
napi_status napi_get_date_value(napi_env env,\n                                napi_value value,\n                                double* result)\n
\n\n

This API does not observe leap seconds; they are ignored, as\nECMAScript aligns with POSIX time specification.

\n

Returns napi_ok if the API succeeded. If a non-date napi_value is passed\nin it returns napi_date_expected.

\n

This API returns the C double primitive of time value for the given JavaScript\nDate.

", "type": "module", "displayName": "napi_get_date_value" }, { "textRaw": "napi_get_value_bool", "name": "napi_get_value_bool", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-boolean napi_value is\npassed in it returns napi_boolean_expected.

\n

This API returns the C boolean primitive equivalent of the given JavaScript\nBoolean.

", "type": "module", "displayName": "napi_get_value_bool" }, { "textRaw": "napi_get_value_double", "name": "napi_get_value_double", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_double(napi_env env,\n                                  napi_value value,\n                                  double* result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-number napi_value is passed\nin it returns napi_number_expected.

\n

This API returns the C double primitive equivalent of the given JavaScript\nnumber.

", "type": "module", "displayName": "napi_get_value_double" }, { "textRaw": "napi_get_value_bigint_int64", "name": "napi_get_value_bigint_int64", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_get_value_bigint_int64(napi_env env,\n                                        napi_value value,\n                                        int64_t* result,\n                                        bool* lossless);\n
\n\n

Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

\n

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.

", "type": "module", "displayName": "napi_get_value_bigint_int64" }, { "textRaw": "napi_get_value_bigint_uint64", "name": "napi_get_value_bigint_uint64", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
napi_status napi_get_value_bigint_uint64(napi_env env,\n                                        napi_value value,\n                                        uint64_t* result,\n                                        bool* lossless);\n
\n\n

Returns napi_ok if the API succeeded. If a non-BigInt is passed in it\nreturns napi_bigint_expected.

\n

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.

", "type": "module", "displayName": "napi_get_value_bigint_uint64" }, { "textRaw": "napi_get_value_bigint_words", "name": "napi_get_value_bigint_words", "meta": { "added": [ "v10.7.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_get_value_bigint_words" }, { "textRaw": "napi_get_value_external", "name": "napi_get_value_external", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_external(napi_env env,\n                                    napi_value value,\n                                    void** result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-external napi_value is\npassed in it returns napi_invalid_arg.

\n

This API retrieves the external data pointer that was previously passed to\nnapi_create_external().

", "type": "module", "displayName": "napi_get_value_external" }, { "textRaw": "napi_get_value_int32", "name": "napi_get_value_int32", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_int32(napi_env env,\n                                 napi_value value,\n                                 int32_t* result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in napi_number_expected.

\n

This API returns the C int32 primitive equivalent\nof the given JavaScript number.

\n

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.

\n

Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

", "type": "module", "displayName": "napi_get_value_int32" }, { "textRaw": "napi_get_value_int64", "name": "napi_get_value_int64", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_int64(napi_env env,\n                                 napi_value value,\n                                 int64_t* result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

\n

This API returns the C int64 primitive equivalent of the given JavaScript\nnumber.

\n

number values outside the range of Number.MIN_SAFE_INTEGER\n-(2**53 - 1) - Number.MAX_SAFE_INTEGER (2**53 - 1) will lose\nprecision.

\n

Non-finite number values (NaN, +Infinity, or -Infinity) set the\nresult to zero.

", "type": "module", "displayName": "napi_get_value_int64" }, { "textRaw": "napi_get_value_string_latin1", "name": "napi_get_value_string_latin1", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.

\n

This API returns the ISO-8859-1-encoded string corresponding the value passed\nin.

", "type": "module", "displayName": "napi_get_value_string_latin1" }, { "textRaw": "napi_get_value_string_utf8", "name": "napi_get_value_string_utf8", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.

\n

This API returns the UTF8-encoded string corresponding the value passed in.

", "type": "module", "displayName": "napi_get_value_string_utf8" }, { "textRaw": "napi_get_value_string_utf16", "name": "napi_get_value_string_utf16", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded. If a non-string napi_value\nis passed in it returns napi_string_expected.

\n

This API returns the UTF16-encoded string corresponding the value passed in.

", "type": "module", "displayName": "napi_get_value_string_utf16" }, { "textRaw": "napi_get_value_uint32", "name": "napi_get_value_uint32", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_value_uint32(napi_env env,\n                                  napi_value value,\n                                  uint32_t* result)\n
\n\n

Returns napi_ok if the API succeeded. If a non-number napi_value\nis passed in it returns napi_number_expected.

\n

This API returns the C primitive equivalent of the given napi_value as a\nuint32_t.

", "type": "module", "displayName": "napi_get_value_uint32" } ], "type": "module", "displayName": "Functions to convert from Node-API to C types" }, { "textRaw": "Functions to get global instances", "name": "functions_to_get_global_instances", "modules": [ { "textRaw": "napi_get_boolean", "name": "napi_get_boolean", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API is used to return the JavaScript singleton object that is used to\nrepresent the given boolean value.

", "type": "module", "displayName": "napi_get_boolean" }, { "textRaw": "napi_get_global", "name": "napi_get_global", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_global(napi_env env, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns the global object.

", "type": "module", "displayName": "napi_get_global" }, { "textRaw": "napi_get_null", "name": "napi_get_null", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_null(napi_env env, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns the null object.

", "type": "module", "displayName": "napi_get_null" }, { "textRaw": "napi_get_undefined", "name": "napi_get_undefined", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_undefined(napi_env env, napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns the Undefined object.

", "type": "module", "displayName": "napi_get_undefined" } ], "type": "module", "displayName": "Functions to get global instances" } ], "type": "misc", "displayName": "Working with JavaScript values" }, { "textRaw": "Working with JavaScript values and abstract operations", "name": "working_with_javascript_values_and_abstract_operations", "desc": "

Node-API exposes a set of APIs to perform some abstract operations on JavaScript\nvalues. Some of these operations are documented under Section 7\nof the ECMAScript Language Specification.

\n

These APIs support doing one of the following:

\n
    \n
  1. Coerce JavaScript values to specific JavaScript types (such as number or\nstring).
  2. \n
  3. Check the type of a JavaScript value.
  4. \n
  5. Check for equality between two JavaScript values.
  6. \n
", "modules": [ { "textRaw": "napi_coerce_to_bool", "name": "napi_coerce_to_bool", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_coerce_to_bool(napi_env env,\n                                napi_value value,\n                                napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API implements the abstract operation ToBoolean() as defined in\nSection 7.1.2 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

", "type": "module", "displayName": "napi_coerce_to_bool" }, { "textRaw": "napi_coerce_to_number", "name": "napi_coerce_to_number", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_coerce_to_number(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API implements the abstract operation ToNumber() as defined in\nSection 7.1.3 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

", "type": "module", "displayName": "napi_coerce_to_number" }, { "textRaw": "napi_coerce_to_object", "name": "napi_coerce_to_object", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_coerce_to_object(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API implements the abstract operation ToObject() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

", "type": "module", "displayName": "napi_coerce_to_object" }, { "textRaw": "napi_coerce_to_string", "name": "napi_coerce_to_string", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_coerce_to_string(napi_env env,\n                                  napi_value value,\n                                  napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API implements the abstract operation ToString() as defined in\nSection 7.1.13 of the ECMAScript Language Specification.\nThis API can be re-entrant if getters are defined on the passed-in Object.

", "type": "module", "displayName": "napi_coerce_to_string" }, { "textRaw": "napi_typeof", "name": "napi_typeof", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n\n

This API represents behavior similar to invoking the typeof Operator on\nthe object as defined in Section 12.5.5 of the ECMAScript Language\nSpecification. However, there are some differences:

\n
    \n
  1. It has support for detecting an External value.
  2. \n
  3. It detects null as a separate type, while ECMAScript typeof would detect\nobject.
  4. \n
\n

If value has a type that is invalid, an error is returned.

", "type": "module", "displayName": "napi_typeof" }, { "textRaw": "napi_instanceof", "name": "napi_instanceof", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_instanceof(napi_env env,\n                            napi_value object,\n                            napi_value constructor,\n                            bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API represents invoking the instanceof Operator on the object as\ndefined in Section 12.10.4 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_instanceof" }, { "textRaw": "napi_is_array", "name": "napi_is_array", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_array(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API represents invoking the IsArray operation on the object\nas defined in Section 7.2.2 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_is_array" }, { "textRaw": "napi_is_arraybuffer", "name": "napi_is_arraybuffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is an array buffer.

", "type": "module", "displayName": "napi_is_arraybuffer" }, { "textRaw": "napi_is_buffer", "name": "napi_is_buffer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is a buffer.

", "type": "module", "displayName": "napi_is_buffer" }, { "textRaw": "napi_is_date", "name": "napi_is_date", "meta": { "added": [ "v11.11.0", "v10.17.0" ], "napiVersion": [ 5 ], "changes": [] }, "desc": "
napi_status napi_is_date(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is a date.

", "type": "module", "displayName": "napi_is_date" }, { "textRaw": "napi_is_error", "name": "napi_is_error", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_error(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is an Error.

", "type": "module", "displayName": "napi_is_error" }, { "textRaw": "napi_is_typedarray", "name": "napi_is_typedarray", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is a typed array.

", "type": "module", "displayName": "napi_is_typedarray" }, { "textRaw": "napi_is_dataview", "name": "napi_is_dataview", "meta": { "added": [ "v8.3.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in is a DataView.

", "type": "module", "displayName": "napi_is_dataview" }, { "textRaw": "napi_strict_equals", "name": "napi_strict_equals", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_strict_equals(napi_env env,\n                               napi_value lhs,\n                               napi_value rhs,\n                               bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API represents the invocation of the Strict Equality algorithm as\ndefined in Section 7.2.14 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_strict_equals" }, { "textRaw": "napi_detach_arraybuffer", "name": "napi_detach_arraybuffer", "meta": { "added": [ "v13.0.0", "v12.16.0", "v10.22.0" ], "napiVersion": [ 7 ], "changes": [] }, "desc": "
napi_status napi_detach_arraybuffer(napi_env env,\n                                    napi_value arraybuffer)\n
\n\n

Returns napi_ok if the API succeeded. If a non-detachable ArrayBuffer is\npassed in it returns napi_detachable_arraybuffer_expected.

\n

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.

\n

This API represents the invocation of the ArrayBuffer detach operation as\ndefined in Section 24.1.1.3 of the ECMAScript Language Specification.

", "type": "module", "displayName": "napi_detach_arraybuffer" }, { "textRaw": "napi_is_detached_arraybuffer", "name": "napi_is_detached_arraybuffer", "meta": { "added": [ "v13.3.0", "v12.16.0", "v10.22.0" ], "napiVersion": [ 7 ], "changes": [] }, "desc": "
napi_status napi_is_detached_arraybuffer(napi_env env,\n                                         napi_value arraybuffer,\n                                         bool* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

The ArrayBuffer is considered detached if its internal data is null.

\n

This API represents the invocation of the ArrayBuffer IsDetachedBuffer\noperation as defined in Section 24.1.1.2 of the ECMAScript Language\nSpecification.

", "type": "module", "displayName": "napi_is_detached_arraybuffer" } ], "type": "misc", "displayName": "Working with JavaScript values and abstract operations" }, { "textRaw": "Working with JavaScript properties", "name": "working_with_javascript_properties", "desc": "

Node-API exposes a set of APIs to get and set properties on JavaScript\nobjects. Some of these types are documented under Section 7 of the\nECMAScript Language Specification.

\n

Properties 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:

\n\n

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.

\n

The APIs documented in this section provide a simple interface to\nget and set properties on arbitrary JavaScript objects represented by\nnapi_value.

\n

For instance, consider the following JavaScript code snippet:

\n
const obj = {};\nobj.myProp = 123;\n
\n

The equivalent can be done using Node-API values with the following snippet:

\n
napi_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
\n

Indexed properties can be set in a similar manner. Consider the following\nJavaScript snippet:

\n
const arr = [];\narr[123] = 'hello';\n
\n

The equivalent can be done using Node-API values with the following snippet:

\n
napi_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
\n

Properties can be retrieved using the APIs described in this section.\nConsider the following JavaScript snippet:

\n
const arr = [];\nconst value = arr[123];\n
\n

The following is the approximate equivalent of the Node-API counterpart:

\n
napi_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
\n

Finally, multiple properties can also be defined on an object for performance\nreasons. Consider the following JavaScript:

\n
const 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
\n

The following is the approximate equivalent of the Node-API counterpart:

\n
napi_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", "modules": [ { "textRaw": "napi_property_attributes", "name": "napi_property_attributes", "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
\n

napi_property_attributes are flags used to control the behavior of properties\nset on a JavaScript object. Other than napi_static they correspond to the\nattributes listed in Section 6.1.7.1\nof the ECMAScript Language Specification.\nThey can be one or more of the following bitflags:

\n", "type": "module", "displayName": "napi_property_attributes" }, { "textRaw": "napi_property_descriptor", "name": "napi_property_descriptor", "desc": "
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
\n", "type": "module", "displayName": "napi_property_descriptor" } ], "type": "module", "displayName": "Structures" }, { "textRaw": "Functions", "name": "functions", "modules": [ { "textRaw": "napi_get_property_names", "name": "napi_get_property_names", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_property_names(napi_env env,\n                                    napi_value object,\n                                    napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_get_property_names" }, { "textRaw": "napi_get_all_property_names", "name": "napi_get_all_property_names", "meta": { "added": [ "v13.7.0", "v12.17.0", "v10.20.0" ], "napiVersion": [ 6 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

This API returns an array containing the names of the available properties\nof this object.

", "type": "module", "displayName": "napi_get_all_property_names" }, { "textRaw": "napi_set_property", "name": "napi_set_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_set_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value value);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API set a property on the Object passed in.

", "type": "module", "displayName": "napi_set_property" }, { "textRaw": "napi_get_property", "name": "napi_get_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API gets the requested property from the Object passed in.

", "type": "module", "displayName": "napi_get_property" }, { "textRaw": "napi_has_property", "name": "napi_has_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_has_property(napi_env env,\n                              napi_value object,\n                              napi_value key,\n                              bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API checks if the Object passed in has the named property.

", "type": "module", "displayName": "napi_has_property" }, { "textRaw": "napi_delete_property", "name": "napi_delete_property", "meta": { "added": [ "v8.2.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_delete_property(napi_env env,\n                                 napi_value object,\n                                 napi_value key,\n                                 bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API attempts to delete the key own property from object.

", "type": "module", "displayName": "napi_delete_property" }, { "textRaw": "napi_has_own_property", "name": "napi_has_own_property", "meta": { "added": [ "v8.2.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_has_own_property(napi_env env,\n                                  napi_value object,\n                                  napi_value key,\n                                  bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_has_own_property" }, { "textRaw": "napi_set_named_property", "name": "napi_set_named_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_set_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value value);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This method is equivalent to calling napi_set_property with a napi_value\ncreated from the string passed in as utf8Name.

", "type": "module", "displayName": "napi_set_named_property" }, { "textRaw": "napi_get_named_property", "name": "napi_get_named_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This method is equivalent to calling napi_get_property with a napi_value\ncreated from the string passed in as utf8Name.

", "type": "module", "displayName": "napi_get_named_property" }, { "textRaw": "napi_has_named_property", "name": "napi_has_named_property", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_has_named_property(napi_env env,\n                                    napi_value object,\n                                    const char* utf8Name,\n                                    bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This method is equivalent to calling napi_has_property with a napi_value\ncreated from the string passed in as utf8Name.

", "type": "module", "displayName": "napi_has_named_property" }, { "textRaw": "napi_set_element", "name": "napi_set_element", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_set_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value value);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API sets and element on the Object passed in.

", "type": "module", "displayName": "napi_set_element" }, { "textRaw": "napi_get_element", "name": "napi_get_element", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             napi_value* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API gets the element at the requested index.

", "type": "module", "displayName": "napi_get_element" }, { "textRaw": "napi_has_element", "name": "napi_has_element", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_has_element(napi_env env,\n                             napi_value object,\n                             uint32_t index,\n                             bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns if the Object passed in has an element at the\nrequested index.

", "type": "module", "displayName": "napi_has_element" }, { "textRaw": "napi_delete_element", "name": "napi_delete_element", "meta": { "added": [ "v8.2.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_delete_element(napi_env env,\n                                napi_value object,\n                                uint32_t index,\n                                bool* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API attempts to delete the specified index from object.

", "type": "module", "displayName": "napi_delete_element" }, { "textRaw": "napi_define_properties", "name": "napi_define_properties", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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 9.1.6 of the ECMA-262\nspecification).

", "type": "module", "displayName": "napi_define_properties" }, { "textRaw": "napi_object_freeze", "name": "napi_object_freeze", "meta": { "added": [ "v14.14.0", "v12.20.0" ], "napiVersion": [ 8 ], "changes": [] }, "desc": "
napi_status napi_object_freeze(napi_env env,\n                               napi_value object);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_object_freeze" }, { "textRaw": "napi_object_seal", "name": "napi_object_seal", "meta": { "added": [ "v14.14.0", "v12.20.0" ], "napiVersion": [ 8 ], "changes": [] }, "desc": "
napi_status napi_object_seal(napi_env env,\n                             napi_value object);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_object_seal" } ], "type": "module", "displayName": "Functions" } ], "type": "misc", "displayName": "Working with JavaScript properties" }, { "textRaw": "Working with JavaScript functions", "name": "working_with_javascript_functions", "desc": "

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:

\n\n

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.

\n

Any 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.

", "modules": [ { "textRaw": "napi_call_function", "name": "napi_call_function", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

A sample use case might look as follows. Consider the following JavaScript\nsnippet:

\n
function AddTwo(num) {\n  return num + 2;\n}\n
\n

Then, 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
", "type": "module", "displayName": "napi_call_function" }, { "textRaw": "napi_create_function", "name": "napi_create_function", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

The 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.

\n

In 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:

\n
napi_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
\n

Given the above code, the add-on can be used from JavaScript as follows:

\n
const myaddon = require('./addon');\nmyaddon.sayHello();\n
\n

The string passed to require() is the name of the target in binding.gyp\nresponsible for creating the .node file.

\n

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.

\n

JavaScript Functions are described in Section 19.2 of the ECMAScript\nLanguage Specification.

", "type": "module", "displayName": "napi_create_function" }, { "textRaw": "napi_get_cb_info", "name": "napi_get_cb_info", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_get_cb_info" }, { "textRaw": "napi_get_new_target", "name": "napi_get_new_target", "meta": { "added": [ "v8.6.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_new_target(napi_env env,\n                                napi_callback_info cbinfo,\n                                napi_value* result)\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API returns the new.target of the constructor call. If the current\ncallback is not a constructor call, the result is NULL.

", "type": "module", "displayName": "napi_get_new_target" }, { "textRaw": "napi_new_instance", "name": "napi_new_instance", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

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:

\n
function MyObject(param) {\n  this.param = param;\n}\n\nconst arg = 'hello';\nconst value = new MyObject(arg);\n
\n

The 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
\n

Returns napi_ok if the API succeeded.

", "type": "module", "displayName": "napi_new_instance" } ], "type": "misc", "displayName": "Working with JavaScript functions" }, { "textRaw": "Object wrap", "name": "object_wrap", "desc": "

Node-API offers a way to \"wrap\" C++ classes and instances so that the class\nconstructor and methods can be called from JavaScript.

\n
    \n
  1. The napi_define_class API defines a JavaScript class with constructor,\nstatic properties and methods, and instance properties and methods that\ncorrespond to the C++ class.
  2. \n
  3. When JavaScript code invokes the constructor, the constructor callback\nuses napi_wrap to wrap a new C++ instance in a JavaScript object,\nthen returns the wrapper object.
  4. \n
  5. When JavaScript code invokes a method or property accessor on the class,\nthe corresponding napi_callback C++ function is invoked. For an instance\ncallback, napi_unwrap obtains the C++ instance that is the target of\nthe call.
  6. \n
\n

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.

\n
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
\n

The reference must be freed once it is no longer needed.

\n

There 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.

\n
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
\n

In 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.

\n

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.

\n

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.

\n

To this end, Node-API provides type-tagging capabilities.

\n

A 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 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.

\n

Continuing the above example, the following skeleton addon implementation\nillustrates the use of napi_type_tag_object() and\nnapi_check_object_type_tag().

\n
// 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", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded.

\n

Defines a JavaScript class, including:

\n\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "napi_define_class" }, { "textRaw": "napi_wrap", "name": "napi_wrap", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

Wraps a native instance in a JavaScript object. The native instance can be\nretrieved later using napi_unwrap().

\n

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.)

\n

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.

\n

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.

\n

Caution: 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.

\n

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.

", "type": "module", "displayName": "napi_wrap" }, { "textRaw": "napi_unwrap", "name": "napi_unwrap", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_unwrap(napi_env env,\n                        napi_value js_object,\n                        void** result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

Retrieves a native instance that was previously wrapped in a JavaScript\nobject using napi_wrap().

\n

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.

", "type": "module", "displayName": "napi_unwrap" }, { "textRaw": "napi_remove_wrap", "name": "napi_remove_wrap", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_remove_wrap(napi_env env,\n                             napi_value js_object,\n                             void** result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_remove_wrap" }, { "textRaw": "napi_type_tag_object", "name": "napi_type_tag_object", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "napiVersion": [ 8 ], "changes": [] }, "desc": "
napi_status napi_type_tag_object(napi_env env,\n                                 napi_value js_object,\n                                 const napi_type_tag* type_tag);\n
\n\n

Returns napi_ok if the API succeeded.

\n

Associates the value of the type_tag pointer with the JavaScript object.\nnapi_check_object_type_tag() can then be used to compare the tag that was\nattached to the object with one owned by the addon to ensure that the object\nhas the right type.

\n

If the object already has an associated type tag, this API will return\nnapi_invalid_arg.

", "type": "module", "displayName": "napi_type_tag_object" }, { "textRaw": "napi_check_object_type_tag", "name": "napi_check_object_type_tag", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "napiVersion": [ 8 ], "changes": [] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_check_object_type_tag" }, { "textRaw": "napi_add_finalizer", "name": "napi_add_finalizer", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 5 ], "changes": [] }, "desc": "
napi_status napi_add_finalizer(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\n

Returns napi_ok if the API succeeded.

\n

Adds a napi_finalize callback which will be called when the JavaScript object\nin js_object is ready for garbage collection. This API is similar to\nnapi_wrap() except that:

\n\n

Caution: 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.

", "type": "module", "displayName": "napi_add_finalizer" } ], "type": "misc", "displayName": "Object wrap" }, { "textRaw": "Simple asynchronous operations", "name": "simple_asynchronous_operations", "desc": "

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.

\n

Node-API provides an ABI-stable interface for these\nsupporting functions which covers the most common asynchronous use cases.

\n

Node-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.

\n

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.

\n

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.

\n

These functions implement the following interfaces:

\n
typedef 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
\n

When 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.

\n

Once created the async worker can be queued\nfor execution using the napi_queue_async_work function:

\n
napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
\n

napi_cancel_async_work can be used if the work needs\nto be cancelled before the work has started execution.

\n

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.

", "modules": [ { "textRaw": "napi_create_async_work", "name": "napi_create_async_work", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [ { "version": "v8.6.0", "pr-url": "https://github.com/nodejs/node/pull/14697", "description": "Added `async_resource` and `async_resource_name` parameters." } ] }, "desc": "
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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

async_resource_name should be a null-terminated, UTF-8-encoded string.

\n

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.

", "type": "module", "displayName": "napi_create_async_work" }, { "textRaw": "napi_delete_async_work", "name": "napi_delete_async_work", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_delete_async_work(napi_env env,\n                                   napi_async_work work);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API frees a previously allocated work object.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_delete_async_work" }, { "textRaw": "napi_queue_async_work", "name": "napi_queue_async_work", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_queue_async_work(napi_env env,\n                                  napi_async_work work);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

", "type": "module", "displayName": "napi_queue_async_work" }, { "textRaw": "napi_cancel_async_work", "name": "napi_cancel_async_work", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_cancel_async_work(napi_env env,\n                                   napi_async_work work);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_cancel_async_work" } ], "type": "misc", "displayName": "Simple asynchronous operations" }, { "textRaw": "Custom asynchronous operations", "name": "custom_asynchronous_operations", "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", "meta": { "added": [ "v8.6.0" ], "napiVersion": [ 1 ], "changes": [] }, "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\n

Returns napi_ok if the API succeeded.

\n

The async_resource object needs to be kept alive until\nnapi_async_destroy to keep async_hooks related API acts correctly. In\norder to retain ABI compatibility with previous versions, napi_async_contexts\nare not maintaining the strong reference to the async_resource objects to\navoid introducing causing memory leaks. However, if the async_resource is\ngarbage collected by JavaScript engine before the napi_async_context was\ndestroyed by napi_async_destroy, calling napi_async_context related APIs\nlike napi_open_callback_scope and napi_make_callback can cause\nproblems like loss of async context when using the AsyncLocalStorage API.

\n

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 poor results 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.

", "type": "module", "displayName": "napi_async_init" }, { "textRaw": "napi_async_destroy", "name": "napi_async_destroy", "meta": { "added": [ "v8.6.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_async_destroy(napi_env env,\n                               napi_async_context async_context);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_async_destroy" }, { "textRaw": "napi_make_callback", "name": "napi_make_callback", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [ { "version": "v8.6.0", "pr-url": "https://github.com/nodejs/node/pull/15189", "description": "Added `async_context` parameter." } ] }, "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\n

Returns napi_ok if the API succeeded.

\n

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.

\n

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.

\n

Any process.nextTicks or Promises scheduled on the microtask queue by\nJavaScript during the callback are ran before returning back to C/C++.

", "type": "module", "displayName": "napi_make_callback" }, { "textRaw": "napi_open_callback_scope", "name": "napi_open_callback_scope", "meta": { "added": [ "v9.6.0" ], "napiVersion": [ 3 ], "changes": [] }, "desc": "
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\n

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.

", "type": "module", "displayName": "napi_open_callback_scope" }, { "textRaw": "napi_close_callback_scope", "name": "napi_close_callback_scope", "meta": { "added": [ "v9.6.0" ], "napiVersion": [ 3 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,\n                                                  napi_callback_scope scope)\n
\n\n

This API can be called even if there is a pending JavaScript exception.

", "type": "module", "displayName": "napi_close_callback_scope" } ], "type": "misc", "displayName": "Custom asynchronous operations" }, { "textRaw": "Version management", "name": "version_management", "modules": [ { "textRaw": "napi_get_node_version", "name": "napi_get_node_version", "meta": { "added": [ "v8.4.0" ], "napiVersion": [ 1 ], "changes": [] }, "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(napi_env env,\n                                  const napi_node_version** version);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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.

\n

The returned buffer is statically allocated and does not need to be freed.

", "type": "module", "displayName": "napi_get_node_version" }, { "textRaw": "napi_get_version", "name": "napi_get_version", "meta": { "added": [ "v8.0.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_get_version(napi_env env,\n                             uint32_t* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

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:

\n", "type": "module", "displayName": "napi_get_version" } ], "type": "misc", "displayName": "Version management" }, { "textRaw": "Memory management", "name": "memory_management", "modules": [ { "textRaw": "napi_adjust_external_memory", "name": "napi_adjust_external_memory", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,\n                                                    int64_t change_in_bytes,\n                                                    int64_t* result);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This function gives V8 an indication of the amount of externally allocated\nmemory that is kept alive by JavaScript objects (i.e. a JavaScript object\nthat points to its own memory allocated by a native module). Registering\nexternally allocated memory will trigger global garbage collections more\noften than it would otherwise.

", "type": "module", "displayName": "napi_adjust_external_memory" } ], "type": "misc", "displayName": "Memory management" }, { "textRaw": "Promises", "name": "promises", "desc": "

Node-API provides facilities for creating Promise objects as described in\nSection 25.4 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.

\n

For example, to create a promise and pass it to an asynchronous worker:

\n
napi_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
\n

The 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:

\n
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", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_create_promise(napi_env env,\n                                napi_deferred* deferred,\n                                napi_value* promise);\n
\n\n

Returns napi_ok if the API succeeded.

\n

This API creates a deferred object and a JavaScript promise.

", "type": "module", "displayName": "napi_create_promise" }, { "textRaw": "napi_resolve_deferred", "name": "napi_resolve_deferred", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_resolve_deferred(napi_env env,\n                                  napi_deferred deferred,\n                                  napi_value resolution);\n
\n\n

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.

\n

The deferred object is freed upon successful completion.

", "type": "module", "displayName": "napi_resolve_deferred" }, { "textRaw": "napi_reject_deferred", "name": "napi_reject_deferred", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_reject_deferred(napi_env env,\n                                 napi_deferred deferred,\n                                 napi_value rejection);\n
\n\n

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.

\n

The deferred object is freed upon successful completion.

", "type": "module", "displayName": "napi_reject_deferred" }, { "textRaw": "napi_is_promise", "name": "napi_is_promise", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
napi_status napi_is_promise(napi_env env,\n                            napi_value value,\n                            bool* is_promise);\n
\n", "type": "module", "displayName": "napi_is_promise" } ], "type": "misc", "displayName": "Promises" }, { "textRaw": "Script execution", "name": "script_execution", "desc": "

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", "meta": { "added": [ "v8.5.0" ], "napiVersion": [ 1 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_run_script(napi_env env,\n                                        napi_value script,\n                                        napi_value* result);\n
\n\n

This function executes a string of JavaScript code and returns its result with\nthe following caveats:

\n", "type": "module", "displayName": "napi_run_script" } ], "type": "misc", "displayName": "Script execution" }, { "textRaw": "libuv event loop", "name": "libuv_event_loop", "desc": "

Node-API provides a function for getting the current event loop associated with\na specific napi_env.

", "modules": [ { "textRaw": "napi_get_uv_event_loop", "name": "napi_get_uv_event_loop", "meta": { "added": [ "v9.3.0", "v8.10.0" ], "napiVersion": [ 2 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,\n                                               struct uv_loop_s** loop);\n
\n", "type": "module", "displayName": "napi_get_uv_event_loop" } ], "type": "misc", "displayName": "libuv event loop" }, { "textRaw": "Asynchronous thread-safe function calls", "name": "asynchronous_thread-safe_function_calls", "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.

\n

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.

\n

These 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.

\n

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.

\n

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().

", "modules": [ { "textRaw": "Calling a thread-safe function", "name": "calling_a_thread-safe_function", "desc": "

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.

\n

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.

\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "Calling a thread-safe function" }, { "textRaw": "Reference counting of thread-safe functions", "name": "reference_counting_of_thread-safe_functions", "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.

\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "Reference counting of thread-safe functions" }, { "textRaw": "Deciding whether to keep the process running", "name": "deciding_whether_to_keep_the_process_running", "desc": "

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.

\n

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.

", "type": "module", "displayName": "Deciding whether to keep the process running" }, { "textRaw": "napi_create_threadsafe_function", "name": "napi_create_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [ { "version": [ "v12.6.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/27791", "description": "Made `func` parameter optional with custom `call_js_cb`." } ] }, "desc": "
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", "type": "module", "displayName": "napi_create_threadsafe_function" }, { "textRaw": "napi_get_threadsafe_function_context", "name": "napi_get_threadsafe_function_context", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\nnapi_get_threadsafe_function_context(napi_threadsafe_function func,\n                                     void** result);\n
\n\n

This API may be called from any thread which makes use of func.

", "type": "module", "displayName": "napi_get_threadsafe_function_context" }, { "textRaw": "napi_call_threadsafe_function", "name": "napi_call_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [ { "version": "v14.5.0", "pr-url": "https://github.com/nodejs/node/pull/33453", "description": "Support for `napi_would_deadlock` has been reverted." }, { "version": "v14.1.0", "pr-url": "https://github.com/nodejs/node/pull/32689", "description": "Return `napi_would_deadlock` when called with `napi_tsfn_blocking` from the main thread or a worker thread and the queue is full." } ] }, "desc": "
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\n

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.

\n

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.

\n

This API may be called from any thread which makes use of func.

", "type": "module", "displayName": "napi_call_threadsafe_function" }, { "textRaw": "napi_acquire_threadsafe_function", "name": "napi_acquire_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\nnapi_acquire_threadsafe_function(napi_threadsafe_function func);\n
\n\n

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.

\n

This API may be called from any thread which will start making use of func.

", "type": "module", "displayName": "napi_acquire_threadsafe_function" }, { "textRaw": "napi_release_threadsafe_function", "name": "napi_release_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\nnapi_release_threadsafe_function(napi_threadsafe_function func,\n                                 napi_threadsafe_function_release_mode mode);\n
\n\n

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.

\n

This API may be called from any thread which will stop making use of func.

", "type": "module", "displayName": "napi_release_threadsafe_function" }, { "textRaw": "napi_ref_threadsafe_function", "name": "napi_ref_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\nnapi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
\n\n

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.

\n

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.

\n

This API may only be called from the main thread.

", "type": "module", "displayName": "napi_ref_threadsafe_function" }, { "textRaw": "napi_unref_threadsafe_function", "name": "napi_unref_threadsafe_function", "meta": { "added": [ "v10.6.0" ], "napiVersion": [ 4 ], "changes": [] }, "desc": "
NAPI_EXTERN napi_status\nnapi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);\n
\n\n

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.

\n

This API may only be called from the main thread.

", "type": "module", "displayName": "napi_unref_threadsafe_function" } ], "type": "misc", "displayName": "Asynchronous thread-safe function calls" }, { "textRaw": "Miscellaneous utilities", "name": "miscellaneous_utilities", "meta": { "added": [ "v15.9.0", "v12.22.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "
NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
\n\n

result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

", "type": "misc", "displayName": "Miscellaneous utilities" }, { "textRaw": "node_api_get_module_file_name", "name": "node_api_get_module_file_name", "meta": { "added": [ "v15.9.0", "v12.22.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "
NAPI_EXTERN napi_status\nnode_api_get_module_file_name(napi_env env, const char** result);\n\n
\n\n

result may be an empty string if the add-on loading process fails to establish\nthe add-on's file name during loading.

", "type": "misc", "displayName": "node_api_get_module_file_name" } ], "source": "doc/api/n-api.md" }, { "textRaw": "Command-line options", "name": "Command-line options", "introduced_in": "v5.9.1", "type": "misc", "desc": "

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.

\n

To view this documentation as a manual page in a terminal, run man node.

", "miscs": [ { "textRaw": "Synopsis", "name": "synopsis", "desc": "

node [options] [V8 options] [script.js | -e \"script\" | -] [--] [arguments]

\n

node inspect [script.js | -e \"script\" | <host>:<port>] …

\n

node --v8-options

\n

Execute without arguments to start the REPL.

\n

For more info about node inspect, see the debugger documentation.

", "type": "misc", "displayName": "Synopsis" }, { "textRaw": "Options", "name": "options", "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." } ] }, "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.

\n

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.

", "modules": [ { "textRaw": "`-`", "name": "`-`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`-`" }, { "textRaw": "`--`", "name": "`--`", "meta": { "added": [ "v6.11.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`--`" }, { "textRaw": "`--abort-on-uncaught-exception`", "name": "`--abort-on-uncaught-exception`", "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).

\n

If this flag is passed, the behavior can still be set to not abort through\nprocess.setUncaughtExceptionCaptureCallback() (and through usage of the\ndomain module that uses it).

", "type": "module", "displayName": "`--abort-on-uncaught-exception`" }, { "textRaw": "`--completion-bash`", "name": "`--completion-bash`", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "desc": "

Print source-able bash completion script for Node.js.

\n
$ node --completion-bash > node_bash_completion\n$ source node_bash_completion\n
", "type": "module", "displayName": "`--completion-bash`" }, { "textRaw": "`-C=condition`, `--conditions=condition`", "name": "`-c=condition`,_`--conditions=condition`", "meta": { "added": [ "v14.9.0", "v12.19.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Enable experimental support for custom conditional exports resolution\nconditions.

\n

Any number of custom string condition names are permitted.

\n

The default Node.js conditions of \"node\", \"default\", \"import\", and\n\"require\" will always apply as defined.

\n

For example, to run a module with \"development\" resolutions:

\n
$ node -C=development app.js\n
", "type": "module", "displayName": "`-C=condition`, `--conditions=condition`" }, { "textRaw": "`--cpu-prof`", "name": "`--cpu-prof`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Starts the V8 CPU profiler on start up, and writes the CPU profile to disk\nbefore exit.

\n

If --cpu-prof-dir is not specified, the generated profile is placed\nin the current working directory.

\n

If --cpu-prof-name is not specified, the generated profile is\nnamed CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.

\n
$ node --cpu-prof index.js\n$ ls *.cpuprofile\nCPU.20190409.202950.15293.0.0.cpuprofile\n
", "type": "module", "displayName": "`--cpu-prof`" }, { "textRaw": "`--cpu-prof-dir`", "name": "`--cpu-prof-dir`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the directory where the CPU profiles generated by --cpu-prof will\nbe placed.

\n

The default value is controlled by the\n--diagnostic-dir command-line option.

", "type": "module", "displayName": "`--cpu-prof-dir`" }, { "textRaw": "`--cpu-prof-interval`", "name": "`--cpu-prof-interval`", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the sampling interval in microseconds for the CPU profiles generated\nby --cpu-prof. The default is 1000 microseconds.

", "type": "module", "displayName": "`--cpu-prof-interval`" }, { "textRaw": "`--cpu-prof-name`", "name": "`--cpu-prof-name`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the file name of the CPU profile generated by --cpu-prof.

", "type": "module", "displayName": "`--cpu-prof-name`" }, { "textRaw": "`--diagnostic-dir=directory`", "name": "`--diagnostic-dir=directory`", "desc": "

Set the directory to which all diagnostic output files are written.\nDefaults to current working directory.

\n

Affects the default output directory of:

\n", "type": "module", "displayName": "`--diagnostic-dir=directory`" }, { "textRaw": "`--disable-proto=mode`", "name": "`--disable-proto=mode`", "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.

", "type": "module", "displayName": "`--disable-proto=mode`" }, { "textRaw": "`--disallow-code-generation-from-strings`", "name": "`--disallow-code-generation-from-strings`", "meta": { "added": [ "v9.8.0" ], "changes": [] }, "desc": "

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\nvm module.

", "type": "module", "displayName": "`--disallow-code-generation-from-strings`" }, { "textRaw": "`--dns-result-order=order`", "name": "`--dns-result-order=order`", "meta": { "added": [ "v16.4.0" ], "changes": [] }, "desc": "

Set the default value of verbatim in dns.lookup() and\ndnsPromises.lookup(). The value could be:

\n\n

The default is ipv4first and dns.setDefaultResultOrder() have higher\npriority than --dns-result-order.

", "type": "module", "displayName": "`--dns-result-order=order`" }, { "textRaw": "`--enable-fips`", "name": "`--enable-fips`", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

Enable FIPS-compliant crypto at startup. (Requires Node.js to be built\nagainst FIPS-compatible OpenSSL.)

", "type": "module", "displayName": "`--enable-fips`" }, { "textRaw": "`--enable-source-maps`", "name": "`--enable-source-maps`", "meta": { "added": [ "v12.12.0" ], "changes": [ { "version": "v15.11.0", "pr-url": "https://github.com/nodejs/node/pull/37362", "description": "This API is no longer experimental." } ] }, "desc": "

Enable Source Map v3 support for stack traces.

\n

When 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.

\n

Overriding Error.prepareStackTrace prevents --enable-source-maps from\nmodifying the stack trace.

", "type": "module", "displayName": "`--enable-source-maps`" }, { "textRaw": "`--experimental-abortcontroller`", "name": "`--experimental-abortcontroller`", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33527", "description": "--experimental-abortcontroller is no longer required." } ] }, "desc": "

AbortController and AbortSignal support is enabled by default.\nUse of this command-line flag is no longer required.

", "type": "module", "displayName": "`--experimental-abortcontroller`" }, { "textRaw": "`--experimental-import-meta-resolve`", "name": "`--experimental-import-meta-resolve`", "meta": { "added": [ "v13.9.0", "v12.16.2" ], "changes": [] }, "desc": "

Enable experimental import.meta.resolve() support.

", "type": "module", "displayName": "`--experimental-import-meta-resolve`" }, { "textRaw": "`--experimental-json-modules`", "name": "`--experimental-json-modules`", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

Enable experimental JSON support for the ES Module loader.

", "type": "module", "displayName": "`--experimental-json-modules`" }, { "textRaw": "`--experimental-loader=module`", "name": "`--experimental-loader=module`", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "desc": "

Specify the module of a custom experimental ECMAScript Module loader.\nmodule may be either a path to a file, or an ECMAScript Module name.

", "type": "module", "displayName": "`--experimental-loader=module`" }, { "textRaw": "`--experimental-modules`", "name": "`--experimental-modules`", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

Enable latest experimental modules features (deprecated).

", "type": "module", "displayName": "`--experimental-modules`" }, { "textRaw": "`--experimental-policy`", "name": "`--experimental-policy`", "meta": { "added": [ "v11.8.0" ], "changes": [] }, "desc": "

Use the specified file as a security policy.

", "type": "module", "displayName": "`--experimental-policy`" }, { "textRaw": "`--no-experimental-repl-await`", "name": "`--no-experimental-repl-await`", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "

Use this flag to disable top-level await in REPL.

", "type": "module", "displayName": "`--no-experimental-repl-await`" }, { "textRaw": "`--experimental-specifier-resolution=mode`", "name": "`--experimental-specifier-resolution=mode`", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "desc": "

Sets the resolution algorithm for resolving ES module specifiers. Valid options\nare explicit and node.

\n

The default is explicit, which requires providing the full path to a\nmodule. The node mode enables support for optional file extensions and\nthe ability to import a directory that has an index file.

\n

See customizing ESM specifier resolution for example usage.

", "type": "module", "displayName": "`--experimental-specifier-resolution=mode`" }, { "textRaw": "`--experimental-vm-modules`", "name": "`--experimental-vm-modules`", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "desc": "

Enable experimental ES Module support in the vm module.

", "type": "module", "displayName": "`--experimental-vm-modules`" }, { "textRaw": "`--experimental-wasi-unstable-preview1`", "name": "`--experimental-wasi-unstable-preview1`", "meta": { "added": [ "v13.3.0", "v12.16.0" ], "changes": [ { "version": "v13.6.0", "pr-url": "https://github.com/nodejs/node/pull/30980", "description": "changed from `--experimental-wasi-unstable-preview0` to `--experimental-wasi-unstable-preview1`." } ] }, "desc": "

Enable experimental WebAssembly System Interface (WASI) support.

", "type": "module", "displayName": "`--experimental-wasi-unstable-preview1`" }, { "textRaw": "`--experimental-wasm-modules`", "name": "`--experimental-wasm-modules`", "meta": { "added": [ "v12.3.0" ], "changes": [] }, "desc": "

Enable experimental WebAssembly module support.

", "type": "module", "displayName": "`--experimental-wasm-modules`" }, { "textRaw": "`--force-context-aware`", "name": "`--force-context-aware`", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "desc": "

Disable loading native addons that are not context-aware.

", "type": "module", "displayName": "`--force-context-aware`" }, { "textRaw": "`--force-fips`", "name": "`--force-fips`", "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.)

", "type": "module", "displayName": "`--force-fips`" }, { "textRaw": "`--frozen-intrinsics`", "name": "`--frozen-intrinsics`", "meta": { "added": [ "v11.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Enable experimental frozen intrinsics like Array and Object.

\n

Support is currently only provided for the root context and no guarantees are\ncurrently provided that global.Array is indeed the default intrinsic\nreference. Code may break under this flag.

\n

--require runs prior to freezing intrinsics in order to allow polyfills to\nbe added.

", "type": "module", "displayName": "`--frozen-intrinsics`" }, { "textRaw": "`--heapsnapshot-near-heap-limit=max_count`", "name": "`--heapsnapshot-near-heap-limit=max_count`", "meta": { "added": [ "v15.1.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

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).

\n

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.

\n

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
", "type": "module", "displayName": "`--heapsnapshot-near-heap-limit=max_count`" }, { "textRaw": "`--heapsnapshot-signal=signal`", "name": "`--heapsnapshot-signal=signal`", "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.

\n
$ 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
", "type": "module", "displayName": "`--heapsnapshot-signal=signal`" }, { "textRaw": "`--heap-prof`", "name": "`--heap-prof`", "meta": { "added": [ "v12.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Starts the V8 heap profiler on start up, and writes the heap profile to disk\nbefore exit.

\n

If --heap-prof-dir is not specified, the generated profile is placed\nin the current working directory.

\n

If --heap-prof-name is not specified, the generated profile is\nnamed Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.

\n
$ node --heap-prof index.js\n$ ls *.heapprofile\nHeap.20190409.202950.15293.0.001.heapprofile\n
", "type": "module", "displayName": "`--heap-prof`" }, { "textRaw": "`--heap-prof-dir`", "name": "`--heap-prof-dir`", "meta": { "added": [ "v12.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the directory where the heap profiles generated by --heap-prof will\nbe placed.

\n

The default value is controlled by the\n--diagnostic-dir command-line option.

", "type": "module", "displayName": "`--heap-prof-dir`" }, { "textRaw": "`--heap-prof-interval`", "name": "`--heap-prof-interval`", "meta": { "added": [ "v12.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the average sampling interval in bytes for the heap profiles generated\nby --heap-prof. The default is 512 * 1024 bytes.

", "type": "module", "displayName": "`--heap-prof-interval`" }, { "textRaw": "`--heap-prof-name`", "name": "`--heap-prof-name`", "meta": { "added": [ "v12.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Specify the file name of the heap profile generated by --heap-prof.

", "type": "module", "displayName": "`--heap-prof-name`" }, { "textRaw": "`--icu-data-dir=file`", "name": "`--icu-data-dir=file`", "meta": { "added": [ "v0.11.15" ], "changes": [] }, "desc": "

Specify ICU data load path. (Overrides NODE_ICU_DATA.)

", "type": "module", "displayName": "`--icu-data-dir=file`" }, { "textRaw": "`--input-type=type`", "name": "`--input-type=type`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "desc": "

This configures Node.js to interpret string input as CommonJS or as an ES\nmodule. String input is input via --eval, --print, or STDIN.

\n

Valid values are \"commonjs\" and \"module\". The default is \"commonjs\".

", "type": "module", "displayName": "`--input-type=type`" }, { "textRaw": "`--inspect-brk[=[host:]port]`", "name": "`--inspect-brk[=[host:]port]`", "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.

", "type": "module", "displayName": "`--inspect-brk[=[host:]port]`" }, { "textRaw": "`--inspect-port=[host:]port`", "name": "`--inspect-port=[host:]port`", "meta": { "added": [ "v7.6.0" ], "changes": [] }, "desc": "

Set the host:port to be used when the inspector is activated.\nUseful when activating the inspector by sending the SIGUSR1 signal.

\n

Default host is 127.0.0.1.

\n

See the security warning below regarding the host\nparameter usage.

", "type": "module", "displayName": "`--inspect-port=[host:]port`" }, { "textRaw": "`--inspect[=[host:]port]`", "name": "`--inspect[=[host:]port]`", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "

Activate inspector on host:port. Default is 127.0.0.1:9229.

\n

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.

\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", "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.

\n

If specifying a host, make sure that either:

\n\n

More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by\ndefault) is not firewall-protected.

\n

See the debugging security implications section for more information.

", "type": "module", "displayName": "Warning: binding inspector to a public IP:port combination is insecure" } ], "type": "module", "displayName": "`--inspect[=[host:]port]`" }, { "textRaw": "`--inspect-publish-uid=stderr,http`", "name": "`--inspect-publish-uid=stderr,http`", "desc": "

Specify ways of the inspector web socket url exposure.

\n

By default inspector websocket url is available in stderr and under /json/list\nendpoint on http://host:port/json/list.

", "type": "module", "displayName": "`--inspect-publish-uid=stderr,http`" }, { "textRaw": "`--insecure-http-parser`", "name": "`--insecure-http-parser`", "meta": { "added": [ "v13.4.0", "v12.15.0", "v10.19.0" ], "changes": [] }, "desc": "

Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow\ninteroperability with non-conformant HTTP implementations. It may also allow\nrequest smuggling and other HTTP attacks that rely on invalid headers being\naccepted. Avoid using this option.

", "type": "module", "displayName": "`--insecure-http-parser`" }, { "textRaw": "`--jitless`", "name": "`--jitless`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "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.

\n

This flag is inherited from V8 and is subject to change upstream. It may\ndisappear in a non-semver-major release.

", "type": "module", "displayName": "`--jitless`" }, { "textRaw": "`--max-http-header-size=size`", "name": "`--max-http-header-size=size`", "meta": { "added": [ "v11.6.0", "v10.15.0" ], "changes": [ { "version": "v13.13.0", "pr-url": "https://github.com/nodejs/node/pull/32520", "description": "Change maximum default size of HTTP headers from 8 KB to 16 KB." } ] }, "desc": "

Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KB.

", "type": "module", "displayName": "`--max-http-header-size=size`" }, { "textRaw": "`--napi-modules`", "name": "`--napi-modules`", "meta": { "added": [ "v7.10.0" ], "changes": [] }, "desc": "

This option is a no-op. It is kept for compatibility.

", "type": "module", "displayName": "`--napi-modules`" }, { "textRaw": "`--no-deprecation`", "name": "`--no-deprecation`", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Silence deprecation warnings.

", "type": "module", "displayName": "`--no-deprecation`" }, { "textRaw": "`--no-force-async-hooks-checks`", "name": "`--no-force-async-hooks-checks`", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "desc": "

Disables runtime checks for async_hooks. These will still be enabled\ndynamically when async_hooks is enabled.

", "type": "module", "displayName": "`--no-force-async-hooks-checks`" }, { "textRaw": "`--no-warnings`", "name": "`--no-warnings`", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

Silence all process warnings (including deprecations).

", "type": "module", "displayName": "`--no-warnings`" }, { "textRaw": "`--node-memory-debug`", "name": "`--node-memory-debug`", "meta": { "added": [ "v15.0.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.

", "type": "module", "displayName": "`--node-memory-debug`" }, { "textRaw": "`--openssl-config=file`", "name": "`--openssl-config=file`", "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.

", "type": "module", "displayName": "`--openssl-config=file`" }, { "textRaw": "`--pending-deprecation`", "name": "`--pending-deprecation`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

Emit pending deprecation warnings.

\n

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.

", "type": "module", "displayName": "`--pending-deprecation`" }, { "textRaw": "`--policy-integrity=sri`", "name": "`--policy-integrity=sri`", "meta": { "added": [ "v12.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Instructs Node.js to error prior to running any code if the policy does not have\nthe specified integrity. It expects a Subresource Integrity string as a\nparameter.

", "type": "module", "displayName": "`--policy-integrity=sri`" }, { "textRaw": "`--preserve-symlinks`", "name": "`--preserve-symlinks`", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "

Instructs the module loader to preserve symbolic links when resolving and\ncaching modules.

\n

By 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:

\n
{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
\n

The --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.

\n

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).

\n

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.

", "type": "module", "displayName": "`--preserve-symlinks`" }, { "textRaw": "`--preserve-symlinks-main`", "name": "`--preserve-symlinks-main`", "meta": { "added": [ "v10.2.0" ], "changes": [] }, "desc": "

Instructs the module loader to preserve symbolic links when resolving and\ncaching the main module (require.main).

\n

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.

\n

--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.

\n

See --preserve-symlinks for more information.

", "type": "module", "displayName": "`--preserve-symlinks-main`" }, { "textRaw": "`--prof`", "name": "`--prof`", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "desc": "

Generate V8 profiler output.

", "type": "module", "displayName": "`--prof`" }, { "textRaw": "`--prof-process`", "name": "`--prof-process`", "meta": { "added": [ "v5.2.0" ], "changes": [] }, "desc": "

Process V8 profiler output generated using the V8 option --prof.

", "type": "module", "displayName": "`--prof-process`" }, { "textRaw": "`--redirect-warnings=file`", "name": "`--redirect-warnings=file`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

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.

\n

The 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.

", "type": "module", "displayName": "`--redirect-warnings=file`" }, { "textRaw": "`--report-compact`", "name": "`--report-compact`", "meta": { "added": [ "v13.12.0", "v12.17.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`--report-compact`" }, { "textRaw": "`--report-dir=directory`, `report-directory=directory`", "name": "`--report-dir=directory`,_`report-directory=directory`", "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.

", "type": "module", "displayName": "`--report-dir=directory`, `report-directory=directory`" }, { "textRaw": "`--report-filename=filename`", "name": "`--report-filename=filename`", "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-filename` to `--report-filename`." } ] }, "desc": "

Name of the file to which the report will be written.

", "type": "module", "displayName": "`--report-filename=filename`" }, { "textRaw": "`--report-on-fatalerror`", "name": "`--report-on-fatalerror`", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v14.0.0", "v13.14.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32496", "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-fatalerror` to `--report-on-fatalerror`." } ] }, "desc": "

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.

", "type": "module", "displayName": "`--report-on-fatalerror`" }, { "textRaw": "`--report-on-signal`", "name": "`--report-on-signal`", "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.

", "type": "module", "displayName": "`--report-on-signal`" }, { "textRaw": "`--report-signal=signal`", "name": "`--report-signal=signal`", "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-signal` to `--report-signal`." } ] }, "desc": "

Sets or resets the signal for report generation (not supported on Windows).\nDefault signal is SIGUSR2.

", "type": "module", "displayName": "`--report-signal=signal`" }, { "textRaw": "`--report-uncaught-exception`", "name": "`--report-uncaught-exception`", "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-uncaught-exception` to `--report-uncaught-exception`." } ] }, "desc": "

Enables report to be generated on uncaught exceptions. Useful when inspecting\nthe JavaScript stack in conjunction with native stack and other runtime\nenvironment data.

", "type": "module", "displayName": "`--report-uncaught-exception`" }, { "textRaw": "`--secure-heap=n`", "name": "`--secure-heap=n`", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

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.

\n

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.

\n

The heap size given must be a power of two. Any value less than 2\nwill disable the secure heap.

\n

The secure heap is disabled by default.

\n

The secure heap is not available on Windows.

\n

See CRYPTO_secure_malloc_init for more details.

", "type": "module", "displayName": "`--secure-heap=n`" }, { "textRaw": "`--secure-heap-min=n`", "name": "`--secure-heap-min=n`", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`--secure-heap-min=n`" }, { "textRaw": "`--throw-deprecation`", "name": "`--throw-deprecation`", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "

Throw errors for deprecations.

", "type": "module", "displayName": "`--throw-deprecation`" }, { "textRaw": "`--title=title`", "name": "`--title=title`", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "desc": "

Set process.title on startup.

", "type": "module", "displayName": "`--title=title`" }, { "textRaw": "`--tls-cipher-list=list`", "name": "`--tls-cipher-list=list`", "meta": { "added": [ "v4.0.0" ], "changes": [] }, "desc": "

Specify an alternative default TLS cipher list. Requires Node.js to be built\nwith crypto support (default).

", "type": "module", "displayName": "`--tls-cipher-list=list`" }, { "textRaw": "`--tls-keylog=file`", "name": "`--tls-keylog=file`", "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.

", "type": "module", "displayName": "`--tls-keylog=file`" }, { "textRaw": "`--tls-max-v1.2`", "name": "`--tls-max-v1.2`", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "desc": "

Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for\nTLSv1.3.

", "type": "module", "displayName": "`--tls-max-v1.2`" }, { "textRaw": "`--tls-max-v1.3`", "name": "`--tls-max-v1.3`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "desc": "

Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support\nfor TLSv1.3.

", "type": "module", "displayName": "`--tls-max-v1.3`" }, { "textRaw": "`--tls-min-v1.0`", "name": "`--tls-min-v1.0`", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "desc": "

Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with\nold TLS clients or servers.

", "type": "module", "displayName": "`--tls-min-v1.0`" }, { "textRaw": "`--tls-min-v1.1`", "name": "`--tls-min-v1.1`", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "desc": "

Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility\nwith old TLS clients or servers.

", "type": "module", "displayName": "`--tls-min-v1.1`" }, { "textRaw": "`--tls-min-v1.2`", "name": "`--tls-min-v1.2`", "meta": { "added": [ "v12.2.0", "v10.20.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`--tls-min-v1.2`" }, { "textRaw": "`--tls-min-v1.3`", "name": "`--tls-min-v1.3`", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "desc": "

Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support\nfor TLSv1.2, which is not as secure as TLSv1.3.

", "type": "module", "displayName": "`--tls-min-v1.3`" }, { "textRaw": "`--trace-atomics-wait`", "name": "`--trace-atomics-wait`", "meta": { "added": [ "v14.3.0" ], "changes": [] }, "desc": "

Print short summaries of calls to Atomics.wait() to stderr.\nThe output could look like this:

\n
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) started\n(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) did not wait because the values mismatched\n(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) started\n(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) timed out\n(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) started\n(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) started\n(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) was woken up by another thread\n(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) was woken up by another thread\n
\n

The fields here correspond to:

\n", "type": "module", "displayName": "`--trace-atomics-wait`" }, { "textRaw": "`--trace-deprecation`", "name": "`--trace-deprecation`", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Print stack traces for deprecations.

", "type": "module", "displayName": "`--trace-deprecation`" }, { "textRaw": "`--trace-event-categories`", "name": "`--trace-event-categories`", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "desc": "

A comma separated list of categories that should be traced when trace event\ntracing is enabled using --trace-events-enabled.

", "type": "module", "displayName": "`--trace-event-categories`" }, { "textRaw": "`--trace-event-file-pattern`", "name": "`--trace-event-file-pattern`", "meta": { "added": [ "v9.8.0" ], "changes": [] }, "desc": "

Template string specifying the filepath for the trace event data, it\nsupports ${rotation} and ${pid}.

", "type": "module", "displayName": "`--trace-event-file-pattern`" }, { "textRaw": "`--trace-events-enabled`", "name": "`--trace-events-enabled`", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "desc": "

Enables the collection of trace event tracing information.

", "type": "module", "displayName": "`--trace-events-enabled`" }, { "textRaw": "`--trace-exit`", "name": "`--trace-exit`", "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().

", "type": "module", "displayName": "`--trace-exit`" }, { "textRaw": "`--trace-sigint`", "name": "`--trace-sigint`", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "desc": "

Prints a stack trace on SIGINT.

", "type": "module", "displayName": "`--trace-sigint`" }, { "textRaw": "`--trace-sync-io`", "name": "`--trace-sync-io`", "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.

", "type": "module", "displayName": "`--trace-sync-io`" }, { "textRaw": "`--trace-tls`", "name": "`--trace-tls`", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "desc": "

Prints TLS packet trace information to stderr. This can be used to debug TLS\nconnection problems.

", "type": "module", "displayName": "`--trace-tls`" }, { "textRaw": "`--trace-uncaught`", "name": "`--trace-uncaught`", "meta": { "added": [ "v13.1.0" ], "changes": [] }, "desc": "

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).

\n

Enabling this option may affect garbage collection behavior negatively.

", "type": "module", "displayName": "`--trace-uncaught`" }, { "textRaw": "`--trace-warnings`", "name": "`--trace-warnings`", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

Print stack traces for process warnings (including deprecations).

", "type": "module", "displayName": "`--trace-warnings`" }, { "textRaw": "`--track-heap-objects`", "name": "`--track-heap-objects`", "meta": { "added": [ "v2.4.0" ], "changes": [] }, "desc": "

Track heap object allocations for heap snapshots.

", "type": "module", "displayName": "`--track-heap-objects`" }, { "textRaw": "`--unhandled-rejections=mode`", "name": "`--unhandled-rejections=mode`", "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:

\n", "type": "module", "displayName": "`--unhandled-rejections=mode`" }, { "textRaw": "`--use-bundled-ca`, `--use-openssl-ca`", "name": "`--use-bundled-ca`,_`--use-openssl-ca`", "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.

\n

The 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.

\n

Using 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.

\n

See SSL_CERT_DIR and SSL_CERT_FILE.

", "type": "module", "displayName": "`--use-bundled-ca`, `--use-openssl-ca`" }, { "textRaw": "`--use-largepages=mode`", "name": "`--use-largepages=mode`", "meta": { "added": [ "v13.6.0", "v12.17.0" ], "changes": [] }, "desc": "

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.

\n

The following values are valid for mode:

\n", "type": "module", "displayName": "`--use-largepages=mode`" }, { "textRaw": "`--v8-options`", "name": "`--v8-options`", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "

Print V8 command-line options.

", "type": "module", "displayName": "`--v8-options`" }, { "textRaw": "`--v8-pool-size=num`", "name": "`--v8-pool-size=num`", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "desc": "

Set V8's thread pool size which will be used to allocate background jobs.

\n

If set to 0 then V8 will choose an appropriate size of the thread pool based\non the number of online processors.

\n

If the value provided is larger than V8's maximum, then the largest value\nwill be chosen.

", "type": "module", "displayName": "`--v8-pool-size=num`" }, { "textRaw": "`--zero-fill-buffers`", "name": "`--zero-fill-buffers`", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

Automatically zero-fills all newly allocated Buffer and SlowBuffer\ninstances.

", "type": "module", "displayName": "`--zero-fill-buffers`" }, { "textRaw": "`-c`, `--check`", "name": "`-c`,_`--check`", "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.

", "type": "module", "displayName": "`-c`, `--check`" }, { "textRaw": "`-e`, `--eval \"script\"`", "name": "`-e`,_`--eval_\"script\"`", "meta": { "added": [ "v0.5.2" ], "changes": [ { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/5348", "description": "Built-in libraries are now available as predefined variables." } ] }, "desc": "

Evaluate the following argument as JavaScript. The modules which are\npredefined in the REPL can also be used in script.

\n

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.

", "type": "module", "displayName": "`-e`, `--eval \"script\"`" }, { "textRaw": "`-h`, `--help`", "name": "`-h`,_`--help`", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "

Print node command-line options.\nThe output of this option is less detailed than this document.

", "type": "module", "displayName": "`-h`, `--help`" }, { "textRaw": "`-i`, `--interactive`", "name": "`-i`,_`--interactive`", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

Opens the REPL even if stdin does not appear to be a terminal.

", "type": "module", "displayName": "`-i`, `--interactive`" }, { "textRaw": "`-p`, `--print \"script\"`", "name": "`-p`,_`--print_\"script\"`", "meta": { "added": [ "v0.6.4" ], "changes": [ { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/5348", "description": "Built-in libraries are now available as predefined variables." } ] }, "desc": "

Identical to -e but prints the result.

", "type": "module", "displayName": "`-p`, `--print \"script\"`" }, { "textRaw": "`-r`, `--require module`", "name": "`-r`,_`--require_module`", "meta": { "added": [ "v1.6.0" ], "changes": [] }, "desc": "

Preload the specified module at startup.

\n

Follows require()'s module resolution\nrules. module may be either a path to a file, or a node module name.

\n

Only CommonJS modules are supported. Attempting to preload a\nES6 Module using --require will fail with an error.

", "type": "module", "displayName": "`-r`, `--require module`" }, { "textRaw": "`-v`, `--version`", "name": "`-v`,_`--version`", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "

Print node's version.

", "type": "module", "displayName": "`-v`, `--version`" } ], "type": "misc", "displayName": "Options" }, { "textRaw": "Environment variables", "name": "environment_variables", "modules": [ { "textRaw": "`FORCE_COLOR=[1, 2, 3]`", "name": "`force_color=[1,_2,_3]`", "desc": "

The FORCE_COLOR environment variable is used to\nenable ANSI colorized output. The value may be:

\n\n

When FORCE_COLOR is used and set to a supported value, both the NO_COLOR,\nand NODE_DISABLE_COLORS environment variables are ignored.

\n

Any other value will result in colorized output being disabled.

", "type": "module", "displayName": "`FORCE_COLOR=[1, 2, 3]`" }, { "textRaw": "`NODE_DEBUG=module[,…]`", "name": "`node_debug=module[,…]`", "meta": { "added": [ "v0.1.32" ], "changes": [] }, "desc": "

','-separated list of core modules that should print debug information.

", "type": "module", "displayName": "`NODE_DEBUG=module[,…]`" }, { "textRaw": "`NODE_DEBUG_NATIVE=module[,…]`", "name": "`node_debug_native=module[,…]`", "desc": "

','-separated list of core C++ modules that should print debug information.

", "type": "module", "displayName": "`NODE_DEBUG_NATIVE=module[,…]`" }, { "textRaw": "`NODE_DISABLE_COLORS=1`", "name": "`node_disable_colors=1`", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

When set, colors will not be used in the REPL.

", "type": "module", "displayName": "`NODE_DISABLE_COLORS=1`" }, { "textRaw": "`NODE_EXTRA_CA_CERTS=file`", "name": "`node_extra_ca_certs=file`", "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.

\n

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.

\n

This environment variable is ignored when node runs as setuid root or\nhas Linux file capabilities set.

\n

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.

", "type": "module", "displayName": "`NODE_EXTRA_CA_CERTS=file`" }, { "textRaw": "`NODE_ICU_DATA=file`", "name": "`node_icu_data=file`", "meta": { "added": [ "v0.11.15" ], "changes": [] }, "desc": "

Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.

", "type": "module", "displayName": "`NODE_ICU_DATA=file`" }, { "textRaw": "`NODE_NO_WARNINGS=1`", "name": "`node_no_warnings=1`", "meta": { "added": [ "v6.11.0" ], "changes": [] }, "desc": "

When set to 1, process warnings are silenced.

", "type": "module", "displayName": "`NODE_NO_WARNINGS=1`" }, { "textRaw": "`NODE_OPTIONS=options...`", "name": "`node_options=options...`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

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.

\n

If an option value contains a space, it can be escaped using double quotes:

\n
NODE_OPTIONS='--require \"./my path/file.js\"'\n
\n

A singleton flag passed as a command-line option will override the same flag\npassed into NODE_OPTIONS:

\n
# The inspector will be available on port 5555\nNODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555\n
\n

A 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:

\n
NODE_OPTIONS='--require \"./a.js\"' node --require \"./b.js\"\n# is equivalent to:\nnode --require \"./a.js\" --require \"./b.js\"\n
\n

Node.js options that are allowed are:

\n\n\n\n

V8 options that are allowed are:

\n\n\n\n

--perf-basic-prof-only-functions, --perf-basic-prof,\n--perf-prof-unwinding-info, and --perf-prof are only available on Linux.

", "type": "module", "displayName": "`NODE_OPTIONS=options...`" }, { "textRaw": "`NODE_PATH=path[:…]`", "name": "`node_path=path[:…]`", "meta": { "added": [ "v0.1.32" ], "changes": [] }, "desc": "

':'-separated list of directories prefixed to the module search path.

\n

On Windows, this is a ';'-separated list instead.

", "type": "module", "displayName": "`NODE_PATH=path[:…]`" }, { "textRaw": "`NODE_PENDING_DEPRECATION=1`", "name": "`node_pending_deprecation=1`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

When set to 1, emit pending deprecation warnings.

\n

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.

", "type": "module", "displayName": "`NODE_PENDING_DEPRECATION=1`" }, { "textRaw": "`NODE_PENDING_PIPE_INSTANCES=instances`", "name": "`node_pending_pipe_instances=instances`", "desc": "

Set the number of pending pipe instance handles when the pipe server is waiting\nfor connections. This setting applies to Windows only.

", "type": "module", "displayName": "`NODE_PENDING_PIPE_INSTANCES=instances`" }, { "textRaw": "`NODE_PRESERVE_SYMLINKS=1`", "name": "`node_preserve_symlinks=1`", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "desc": "

When set to 1, instructs the module loader to preserve symbolic links when\nresolving and caching modules.

", "type": "module", "displayName": "`NODE_PRESERVE_SYMLINKS=1`" }, { "textRaw": "`NODE_REDIRECT_WARNINGS=file`", "name": "`node_redirect_warnings=file`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`NODE_REDIRECT_WARNINGS=file`" }, { "textRaw": "`NODE_REPL_HISTORY=file`", "name": "`node_repl_history=file`", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`NODE_REPL_HISTORY=file`" }, { "textRaw": "`NODE_REPL_EXTERNAL_MODULE=file`", "name": "`node_repl_external_module=file`", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`NODE_REPL_EXTERNAL_MODULE=file`" }, { "textRaw": "`NODE_SKIP_PLATFORM_CHECK=value`", "name": "`node_skip_platform_check=value`", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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.

", "type": "module", "displayName": "`NODE_SKIP_PLATFORM_CHECK=value`" }, { "textRaw": "`NODE_TLS_REJECT_UNAUTHORIZED=value`", "name": "`node_tls_reject_unauthorized=value`", "desc": "

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.

", "type": "module", "displayName": "`NODE_TLS_REJECT_UNAUTHORIZED=value`" }, { "textRaw": "`NODE_V8_COVERAGE=dir`", "name": "`node_v8_coverage=dir`", "desc": "

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).

\n

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.

", "modules": [ { "textRaw": "Coverage output", "name": "coverage_output", "desc": "

Coverage is output as an array of ScriptCoverage objects on the top-level\nkey result:

\n
{\n  \"result\": [\n    {\n      \"scriptId\": \"67\",\n      \"url\": \"internal/tty.js\",\n      \"functions\": []\n    }\n  ]\n}\n
", "type": "module", "displayName": "Coverage output" }, { "textRaw": "Source map cache", "name": "source_map_cache", "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.

\n

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
{\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
", "type": "module", "displayName": "Source map cache" } ], "type": "module", "displayName": "`NODE_V8_COVERAGE=dir`" }, { "textRaw": "`NO_COLOR=`", "name": "`no_color=`", "desc": "

NO_COLOR is an alias for NODE_DISABLE_COLORS. The value of the\nenvironment variable is arbitrary.

", "type": "module", "displayName": "`NO_COLOR=`" }, { "textRaw": "`OPENSSL_CONF=file`", "name": "`openssl_conf=file`", "meta": { "added": [ "v6.11.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 with ./configure --openssl-fips.

\n

If the --openssl-config command-line option is used, the environment\nvariable is ignored.

", "type": "module", "displayName": "`OPENSSL_CONF=file`" }, { "textRaw": "`SSL_CERT_DIR=dir`", "name": "`ssl_cert_dir=dir`", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "desc": "

If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.

\n

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.

", "type": "module", "displayName": "`SSL_CERT_DIR=dir`" }, { "textRaw": "`SSL_CERT_FILE=file`", "name": "`ssl_cert_file=file`", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "desc": "

If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file\ncontaining trusted certificates.

\n

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.

", "type": "module", "displayName": "`SSL_CERT_FILE=file`" }, { "textRaw": "`TZ`", "name": "`tz`", "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.

\n

While the Node.js support for TZ will not handle all of the various\nways that TZ is handled in other environments, it will support basic\ntimezone IDs (such as '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.

\n
$ TZ=Europe/Dublin node -pe \"new Date().toString()\"\nWed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time)\n
", "type": "module", "displayName": "`TZ`" }, { "textRaw": "`UV_THREADPOOL_SIZE=size`", "name": "`uv_threadpool_size=size`", "desc": "

Set the number of threads used in libuv's threadpool to size threads.

\n

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:

\n
    \n
  • all fs APIs, other than the file watcher APIs and those that are explicitly\nsynchronous
  • \n
  • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(),\ncrypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
  • \n
  • dns.lookup()
  • \n
  • all zlib APIs, other than those that are explicitly synchronous
  • \n
\n

Because 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). For more information, see the\nlibuv threadpool documentation.

", "type": "module", "displayName": "`UV_THREADPOOL_SIZE=size`" } ], "type": "misc", "displayName": "Environment variables" }, { "textRaw": "Useful V8 options", "name": "useful_v8_options", "desc": "

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:

", "modules": [ { "textRaw": "`--max-old-space-size=SIZE` (in megabytes)", "name": "`--max-old-space-size=size`_(in_megabytes)", "desc": "

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.

\n

On a machine with 2 GB of memory, consider setting this to\n1536 (1.5 GB) to leave some memory for other uses and avoid swapping.

\n
$ node --max-old-space-size=1536 index.js\n
", "type": "module", "displayName": "`--max-old-space-size=SIZE` (in megabytes)" } ], "type": "misc", "displayName": "Useful V8 options" } ], "source": "doc/api/cli.md" }, { "textRaw": "Debugger", "name": "Debugger", "introduced_in": "v0.9.12", "stability": 2, "stabilityText": "Stable", "type": "misc", "desc": "

Node.js includes a command-line debugging utility. To use it, start Node.js\nwith the inspect argument followed by the path to the script to debug.

\n
$ 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<\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
\n

The Node.js debugger client is not a full-featured debugger, but simple step and\ninspection are possible.

\n

Inserting the statement debugger; into the source code of a script will\nenable a breakpoint at that position in the code:

\n\n
// myscript.js\nglobal.x = 5;\nsetTimeout(() => {\n  debugger;\n  console.log('world');\n}, 1000);\nconsole.log('hello');\n
\n

Once the debugger is run, a breakpoint will occur at line 3:

\n
$ 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<\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> cont\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
\n

The 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.

\n

Pressing enter without typing a command will repeat the previous debugger\ncommand.

", "miscs": [ { "textRaw": "Watchers", "name": "watchers", "desc": "

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.

\n

To begin watching an expression, type watch('my_expression'). The command\nwatchers will print the active watchers. To remove a watcher, type\nunwatch('my_expression').

", "type": "misc", "displayName": "Watchers" }, { "textRaw": "Command reference", "name": "command_reference", "modules": [ { "textRaw": "Stepping", "name": "stepping", "desc": "
    \n
  • cont, c: Continue execution
  • \n
  • next, n: Step next
  • \n
  • step, s: Step in
  • \n
  • out, o: Step out
  • \n
  • pause: Pause running code (like pause button in Developer Tools)
  • \n
", "type": "module", "displayName": "Stepping" }, { "textRaw": "Breakpoints", "name": "breakpoints", "desc": "
    \n
  • setBreakpoint(), sb(): Set breakpoint on current line
  • \n
  • setBreakpoint(line), sb(line): Set breakpoint on specific line
  • \n
  • setBreakpoint('fn()'), sb(...): Set breakpoint on a first statement in\nfunction's body
  • \n
  • setBreakpoint('script.js', 1), sb(...): Set breakpoint on first line of\nscript.js
  • \n
  • setBreakpoint('script.js', 1, 'num < 4'), sb(...): Set conditional\nbreakpoint on first line of script.js that only breaks when num < 4\nevaluates to true
  • \n
  • clearBreakpoint('script.js', 1), cb(...): Clear breakpoint in script.js\non line 1
  • \n
\n

It 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<\n< Debugger attached.\n<\n ok\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
\n

It is also possible to set a conditional breakpoint that only breaks when a\ngiven expression evaluates to true:

\n
$ 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< 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
", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Information", "name": "information", "desc": "
    \n
  • backtrace, bt: Print backtrace of current execution frame
  • \n
  • list(5): List scripts source code with 5 line context (5 lines before and\nafter)
  • \n
  • watch(expr): Add expression to watch list
  • \n
  • unwatch(expr): Remove expression from watch list
  • \n
  • watchers: List all watchers and their values (automatically listed on each\nbreakpoint)
  • \n
  • repl: Open debugger's repl for evaluation in debugging script's context
  • \n
  • exec expr: Execute an expression in debugging script's context
  • \n
", "type": "module", "displayName": "Information" }, { "textRaw": "Execution control", "name": "execution_control", "desc": "
    \n
  • run: Run script (automatically runs on debugger's start)
  • \n
  • restart: Restart script
  • \n
  • kill: Kill script
  • \n
", "type": "module", "displayName": "Execution control" }, { "textRaw": "Various", "name": "various", "desc": "
    \n
  • scripts: List all loaded scripts
  • \n
  • version: Display V8's version
  • \n
", "type": "module", "displayName": "Various" } ], "type": "misc", "displayName": "Command reference" }, { "textRaw": "Advanced usage", "name": "advanced_usage", "modules": [ { "textRaw": "V8 inspector integration for Node.js", "name": "v8_inspector_integration_for_node.js", "desc": "

V8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling. It uses the\nChrome DevTools Protocol.

\n

V8 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.

\n

To break on the first line of the application code, pass the --inspect-brk\nflag instead of --inspect.

\n
$ 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.)

\n

If the Chrome browser is older than 66.0.3345.0,\nuse inspector.html instead of js_app.html in the above URL.

\n

Chrome DevTools doesn't support debugging worker threads yet.\nndb can be used to debug them.

", "type": "module", "displayName": "V8 inspector integration for Node.js" } ], "type": "misc", "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:

\n
    \n
  • Use of the API is unsafe.
  • \n
  • An improved alternative API is available.
  • \n
  • Breaking changes to the API are expected in a future major release.
  • \n
\n

Node.js uses three kinds of Deprecations:

\n
    \n
  • Documentation-only
  • \n
  • Runtime
  • \n
  • End-of-Life
  • \n
\n

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.

\n

A Runtime deprecation will, by default, generate a process warning that will\nbe printed to stderr the first time the deprecated API is used. When the\n--throw-deprecation command-line flag is used, a Runtime deprecation will\ncause an error to be thrown.

\n

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", "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.

", "type": "misc", "displayName": "Revoking deprecations" }, { "textRaw": "List of deprecated APIs", "name": "list_of_deprecated_apis", "modules": [ { "textRaw": "DEP0001: `http.OutgoingMessage.prototype.flush`", "name": "dep0001:_`http.outgoingmessage.prototype.flush`", "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

\n

OutgoingMessage.prototype.flush() has been removed. Use\nOutgoingMessage.prototype.flushHeaders() instead.

", "type": "module", "displayName": "DEP0001: `http.OutgoingMessage.prototype.flush`" }, { "textRaw": "DEP0002: `require('_linklist')`", "name": "dep0002:_`require('_linklist')`", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12113", "description": "End-of-Life." }, { "version": "v6.12.0", "pr-url": "https://github.com/nodejs/node/pull/10116", "description": "A deprecation code has been assigned." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/3078", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The _linklist module is deprecated. Please use a userland alternative.

", "type": "module", "displayName": "DEP0002: `require('_linklist')`" }, { "textRaw": "DEP0003: `_writableState.buffer`", "name": "dep0003:_`_writablestate.buffer`", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31165", "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.15", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/8826", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The _writableState.buffer has been removed. Use _writableState.getBuffer()\ninstead.

", "type": "module", "displayName": "DEP0003: `_writableState.buffer`" }, { "textRaw": "DEP0004: `CryptoStream.prototype.readyState`", "name": "dep0004:_`cryptostream.prototype.readystate`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17882", "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.4.0", "commit": "9c7f89bf56abd37a796fea621ad2e47dd33d2b82", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The CryptoStream.prototype.readyState property was removed.

", "type": "module", "displayName": "DEP0004: `CryptoStream.prototype.readyState`" }, { "textRaw": "DEP0005: `Buffer()` constructor", "name": "dep0005:_`buffer()`_constructor", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19524", "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/4682", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime (supports --pending-deprecation)

\n

The Buffer() function and new Buffer() constructor are deprecated due to\nAPI usability issues that can lead to accidental security issues.

\n

As an alternative, use one of the following methods of constructing Buffer\nobjects:

\n\n

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": "module", "displayName": "DEP0005: `Buffer()` constructor" }, { "textRaw": "DEP0006: `child_process` `options.customFds`", "name": "dep0006:_`child_process`_`options.customfds`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25279", "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.14", "description": "Runtime deprecation." }, { "version": "v0.5.10", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Within 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": "module", "displayName": "DEP0006: `child_process` `options.customFds`" }, { "textRaw": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`", "name": "dep0007:_replace_`cluster`_`worker.suicide`_with_`worker.exitedafterdisconnect`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/13702", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/3747", "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/3743", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

In 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": "module", "displayName": "DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`" }, { "textRaw": "DEP0008: `require('constants')`", "name": "dep0008:_`require('constants')`", "meta": { "changes": [ { "version": "v6.12.0", "pr-url": "https://github.com/nodejs/node/pull/10116", "description": "A deprecation code has been assigned." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6534", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The 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('fs').constants and require('os').constants.

", "type": "module", "displayName": "DEP0008: `require('constants')`" }, { "textRaw": "DEP0009: `crypto.pbkdf2` without digest", "name": "dep0009:_`crypto.pbkdf2`_without_digest", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31166", "description": "End-of-Life (for `digest === null`)." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22861", "description": "Runtime deprecation (for `digest === null`)." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11305", "description": "End-of-Life (for `digest === undefined`)." }, { "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/4047", "description": "Runtime deprecation (for `digest === undefined`)." } ] }, "desc": "

Type: End-of-Life

\n

Use 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.

\n

Beginning in Node.js v11.0.0, calling these functions with digest set to\nnull would print a deprecation warning to align with the behavior when digest\nis undefined.

\n

Now, however, passing either undefined or null will throw a TypeError.

", "type": "module", "displayName": "DEP0009: `crypto.pbkdf2` without digest" }, { "textRaw": "DEP0010: `crypto.createCredentials`", "name": "dep0010:_`crypto.createcredentials`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/21153", "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.13", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The crypto.createCredentials() API was removed. Please use\ntls.createSecureContext() instead.

", "type": "module", "displayName": "DEP0010: `crypto.createCredentials`" }, { "textRaw": "DEP0011: `crypto.Credentials`", "name": "dep0011:_`crypto.credentials`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/21153", "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.13", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7265", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The crypto.Credentials class was removed. Please use tls.SecureContext\ninstead.

", "type": "module", "displayName": "DEP0011: `crypto.Credentials`" }, { "textRaw": "DEP0012: `Domain.dispose`", "name": "dep0012:_`domain.dispose`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15412", "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.7", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/5021", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Domain.dispose() has been removed. Recover from failed I/O actions\nexplicitly via error event handlers set on the domain instead.

", "type": "module", "displayName": "DEP0012: `Domain.dispose`" }, { "textRaw": "DEP0013: `fs` asynchronous function without callback", "name": "dep0013:_`fs`_asynchronous_function_without_callback", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18668", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7897", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Calling 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": "module", "displayName": "DEP0013: `fs` asynchronous function without callback" }, { "textRaw": "DEP0014: `fs.read` legacy String interface", "name": "dep0014:_`fs.read`_legacy_string_interface", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/9683", "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": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4525", "description": "Runtime deprecation." }, { "version": "v0.1.96", "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The fs.read() legacy String interface is deprecated. Use the Buffer\nAPI as mentioned in the documentation instead.

", "type": "module", "displayName": "DEP0014: `fs.read` legacy String interface" }, { "textRaw": "DEP0015: `fs.readSync` legacy String interface", "name": "dep0015:_`fs.readsync`_legacy_string_interface", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/9683", "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": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4525", "description": "Runtime deprecation." }, { "version": "v0.1.96", "commit": "c93e0aaf062081db3ec40ac45b3e2c979d5759d6", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The fs.readSync() legacy String interface is deprecated. Use the\nBuffer API as mentioned in the documentation instead.

", "type": "module", "displayName": "DEP0015: `fs.readSync` legacy String interface" }, { "textRaw": "DEP0016: `GLOBAL`/`root`", "name": "dep0016:_`global`/`root`", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31167", "description": "End-of-Life." }, { "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/1838", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The GLOBAL and root aliases for the global property were deprecated\nin Node.js 6.0.0 and have since been removed.

", "type": "module", "displayName": "DEP0016: `GLOBAL`/`root`" }, { "textRaw": "DEP0017: `Intl.v8BreakIterator`", "name": "dep0017:_`intl.v8breakiterator`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15238", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/8908", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Intl.v8BreakIterator was a non-standard extension and has been removed.\nSee Intl.Segmenter.

", "type": "module", "displayName": "DEP0017: `Intl.v8BreakIterator`" }, { "textRaw": "DEP0018: Unhandled promise rejections", "name": "dep0018:_unhandled_promise_rejections", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35316", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/8217", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Unhandled 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": "module", "displayName": "DEP0018: Unhandled promise rejections" }, { "textRaw": "DEP0019: `require('.')` resolved outside directory", "name": "dep0019:_`require('.')`_resolved_outside_directory", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26973", "description": "Removed functionality." }, { "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.8.1", "pr-url": "https://github.com/nodejs/node/pull/1363", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

In certain cases, require('.') could resolve outside the package directory.\nThis behavior has been removed.

", "type": "module", "displayName": "DEP0019: `require('.')` resolved outside directory" }, { "textRaw": "DEP0020: `Server.connections`", "name": "dep0020:_`server.connections`", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33647", "description": "Server.connections has been removed." }, { "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.9.7", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/4595", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The Server.connections property was deprecated in Node.js v0.9.7 and has\nbeen removed. Please use the Server.getConnections() method instead.

", "type": "module", "displayName": "DEP0020: `Server.connections`" }, { "textRaw": "DEP0021: `Server.listenFD`", "name": "dep0021:_`server.listenfd`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27127", "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.7.12", "commit": "41421ff9da1288aa241a5e9dcf915b685ade1c23", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The Server.listenFD() method was deprecated and removed. Please use\nServer.listen({fd: <number>}) instead.

", "type": "module", "displayName": "DEP0021: `Server.listenFD`" }, { "textRaw": "DEP0022: `os.tmpDir()`", "name": "dep0022:_`os.tmpdir()`", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31169", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/6739", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The os.tmpDir() API was deprecated in Node.js 7.0.0 and has since been\nremoved. Please use os.tmpdir() instead.

", "type": "module", "displayName": "DEP0022: `os.tmpDir()`" }, { "textRaw": "DEP0023: `os.getNetworkInterfaces()`", "name": "dep0023:_`os.getnetworkinterfaces()`", "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

\n

The os.getNetworkInterfaces() method is deprecated. Please use the\nos.networkInterfaces() method instead.

", "type": "module", "displayName": "DEP0023: `os.getNetworkInterfaces()`" }, { "textRaw": "DEP0024: `REPLServer.prototype.convertToContext()`", "name": "dep0024:_`replserver.prototype.converttocontext()`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/13434", "description": "End-of-Life." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7829", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The REPLServer.prototype.convertToContext() API has been removed.

", "type": "module", "displayName": "DEP0024: `REPLServer.prototype.convertToContext()`" }, { "textRaw": "DEP0025: `require('sys')`", "name": "dep0025:_`require('sys')`", "meta": { "changes": [ { "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.0.0", "pr-url": "https://github.com/nodejs/node/pull/317", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The sys module is deprecated. Please use the util module instead.

", "type": "module", "displayName": "DEP0025: `require('sys')`" }, { "textRaw": "DEP0026: `util.print()`", "name": "dep0026:_`util.print()`", "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

\n

util.print() has been removed. Please use console.log() instead.

", "type": "module", "displayName": "DEP0026: `util.print()`" }, { "textRaw": "DEP0027: `util.puts()`", "name": "dep0027:_`util.puts()`", "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

\n

util.puts() has been removed. Please use console.log() instead.

", "type": "module", "displayName": "DEP0027: `util.puts()`" }, { "textRaw": "DEP0028: `util.debug()`", "name": "dep0028:_`util.debug()`", "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

\n

util.debug() has been removed. Please use console.error() instead.

", "type": "module", "displayName": "DEP0028: `util.debug()`" }, { "textRaw": "DEP0029: `util.error()`", "name": "dep0029:_`util.error()`", "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

\n

util.error() has been removed. Please use console.error() instead.

", "type": "module", "displayName": "DEP0029: `util.error()`" }, { "textRaw": "DEP0030: `SlowBuffer`", "name": "dep0030:_`slowbuffer`", "meta": { "changes": [ { "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: Documentation-only

\n

The SlowBuffer class is deprecated. Please use\nBuffer.allocUnsafeSlow(size) instead.

", "type": "module", "displayName": "DEP0030: `SlowBuffer`" }, { "textRaw": "DEP0031: `ecdh.setPublicKey()`", "name": "dep0031:_`ecdh.setpublickey()`", "meta": { "changes": [ { "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: Documentation-only

\n

The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful.

", "type": "module", "displayName": "DEP0031: `ecdh.setPublicKey()`" }, { "textRaw": "DEP0032: `domain` module", "name": "dep0032:_`domain`_module", "meta": { "changes": [ { "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.4.2", "pr-url": "https://github.com/nodejs/node/pull/943", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The domain module is deprecated and should not be used.

", "type": "module", "displayName": "DEP0032: `domain` module" }, { "textRaw": "DEP0033: `EventEmitter.listenerCount()`", "name": "dep0033:_`eventemitter.listenercount()`", "meta": { "changes": [ { "version": [ "v6.12.0", "v4.8.6" ], "pr-url": "https://github.com/nodejs/node/pull/10116", "description": "A deprecation code has been assigned." }, { "version": "v3.2.0", "pr-url": "https://github.com/nodejs/node/pull/2349", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The events.listenerCount(emitter, eventName) API is\ndeprecated. Please use emitter.listenerCount(eventName) instead.

", "type": "module", "displayName": "DEP0033: `EventEmitter.listenerCount()`" }, { "textRaw": "DEP0034: `fs.exists(path, callback)`", "name": "dep0034:_`fs.exists(path,_callback)`", "meta": { "changes": [ { "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.0.0", "pr-url": "https://github.com/nodejs/node/pull/166", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The fs.exists(path, callback) API is deprecated. Please use\nfs.stat() or fs.access() instead.

", "type": "module", "displayName": "DEP0034: `fs.exists(path, callback)`" }, { "textRaw": "DEP0035: `fs.lchmod(path, mode, callback)`", "name": "dep0035:_`fs.lchmod(path,_mode,_callback)`", "meta": { "changes": [ { "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.4.7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The fs.lchmod(path, mode, callback) API is deprecated.

", "type": "module", "displayName": "DEP0035: `fs.lchmod(path, mode, callback)`" }, { "textRaw": "DEP0036: `fs.lchmodSync(path, mode)`", "name": "dep0036:_`fs.lchmodsync(path,_mode)`", "meta": { "changes": [ { "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.4.7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The fs.lchmodSync(path, mode) API is deprecated.

", "type": "module", "displayName": "DEP0036: `fs.lchmodSync(path, mode)`" }, { "textRaw": "DEP0037: `fs.lchown(path, uid, gid, callback)`", "name": "dep0037:_`fs.lchown(path,_uid,_gid,_callback)`", "meta": { "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/21498", "description": "Deprecation revoked." }, { "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.4.7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Deprecation revoked

\n

The fs.lchown(path, uid, gid, callback) API was deprecated. The\ndeprecation was revoked because the requisite supporting APIs were added in\nlibuv.

", "type": "module", "displayName": "DEP0037: `fs.lchown(path, uid, gid, callback)`" }, { "textRaw": "DEP0038: `fs.lchownSync(path, uid, gid)`", "name": "dep0038:_`fs.lchownsync(path,_uid,_gid)`", "meta": { "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/21498", "description": "Deprecation revoked." }, { "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.4.7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Deprecation revoked

\n

The fs.lchownSync(path, uid, gid) API was deprecated. The deprecation was\nrevoked because the requisite supporting APIs were added in libuv.

", "type": "module", "displayName": "DEP0038: `fs.lchownSync(path, uid, gid)`" }, { "textRaw": "DEP0039: `require.extensions`", "name": "dep0039:_`require.extensions`", "meta": { "changes": [ { "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.10.6", "commit": "7bd8a5a2a60b75266f89f9a32877d55294a3881c", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The require.extensions property is deprecated.

", "type": "module", "displayName": "DEP0039: `require.extensions`" }, { "textRaw": "DEP0040: `punycode` module", "name": "dep0040:_`punycode`_module", "meta": { "changes": [ { "version": "v16.6.0", "pr-url": "https://github.com/nodejs/node/pull/38444", "description": "Added support for `--pending-deprecation`." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7941", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

The punycode module is deprecated. Please use a userland alternative\ninstead.

", "type": "module", "displayName": "DEP0040: `punycode` module" }, { "textRaw": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable", "name": "dep0041:_`node_repl_history_file`_environment_variable", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/13876", "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": "v3.0.0", "pr-url": "https://github.com/nodejs/node/pull/2224", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The NODE_REPL_HISTORY_FILE environment variable was removed. Please use\nNODE_REPL_HISTORY instead.

", "type": "module", "displayName": "DEP0041: `NODE_REPL_HISTORY_FILE` environment variable" }, { "textRaw": "DEP0042: `tls.CryptoStream`", "name": "dep0042:_`tls.cryptostream`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17882", "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": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The tls.CryptoStream class was removed. Please use\ntls.TLSSocket instead.

", "type": "module", "displayName": "DEP0042: `tls.CryptoStream`" }, { "textRaw": "DEP0043: `tls.SecurePair`", "name": "dep0043:_`tls.securepair`", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11349", "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/6063", "description": "Documentation-only deprecation." }, { "version": "v0.11.15", "pr-url": [ "https://github.com/nodejs/node-v0.x-archive/pull/8695", "https://github.com/nodejs/node-v0.x-archive/pull/8700" ], "description": "Deprecation revoked." }, { "version": "v0.11.3", "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", "description": "Runtime deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The tls.SecurePair class is deprecated. Please use\ntls.TLSSocket instead.

", "type": "module", "displayName": "DEP0043: `tls.SecurePair`" }, { "textRaw": "DEP0044: `util.isArray()`", "name": "dep0044:_`util.isarray()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isArray() API is deprecated. Please use Array.isArray()\ninstead.

", "type": "module", "displayName": "DEP0044: `util.isArray()`" }, { "textRaw": "DEP0045: `util.isBoolean()`", "name": "dep0045:_`util.isboolean()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isBoolean() API is deprecated.

", "type": "module", "displayName": "DEP0045: `util.isBoolean()`" }, { "textRaw": "DEP0046: `util.isBuffer()`", "name": "dep0046:_`util.isbuffer()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isBuffer() API is deprecated. Please use\nBuffer.isBuffer() instead.

", "type": "module", "displayName": "DEP0046: `util.isBuffer()`" }, { "textRaw": "DEP0047: `util.isDate()`", "name": "dep0047:_`util.isdate()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isDate() API is deprecated.

", "type": "module", "displayName": "DEP0047: `util.isDate()`" }, { "textRaw": "DEP0048: `util.isError()`", "name": "dep0048:_`util.iserror()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isError() API is deprecated.

", "type": "module", "displayName": "DEP0048: `util.isError()`" }, { "textRaw": "DEP0049: `util.isFunction()`", "name": "dep0049:_`util.isfunction()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isFunction() API is deprecated.

", "type": "module", "displayName": "DEP0049: `util.isFunction()`" }, { "textRaw": "DEP0050: `util.isNull()`", "name": "dep0050:_`util.isnull()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isNull() API is deprecated.

", "type": "module", "displayName": "DEP0050: `util.isNull()`" }, { "textRaw": "DEP0051: `util.isNullOrUndefined()`", "name": "dep0051:_`util.isnullorundefined()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isNullOrUndefined() API is deprecated.

", "type": "module", "displayName": "DEP0051: `util.isNullOrUndefined()`" }, { "textRaw": "DEP0052: `util.isNumber()`", "name": "dep0052:_`util.isnumber()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isNumber() API is deprecated.

", "type": "module", "displayName": "DEP0052: `util.isNumber()`" }, { "textRaw": "DEP0053: `util.isObject()`", "name": "dep0053:_`util.isobject()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isObject() API is deprecated.

", "type": "module", "displayName": "DEP0053: `util.isObject()`" }, { "textRaw": "DEP0054: `util.isPrimitive()`", "name": "dep0054:_`util.isprimitive()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isPrimitive() API is deprecated.

", "type": "module", "displayName": "DEP0054: `util.isPrimitive()`" }, { "textRaw": "DEP0055: `util.isRegExp()`", "name": "dep0055:_`util.isregexp()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isRegExp() API is deprecated.

", "type": "module", "displayName": "DEP0055: `util.isRegExp()`" }, { "textRaw": "DEP0056: `util.isString()`", "name": "dep0056:_`util.isstring()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isString() API is deprecated.

", "type": "module", "displayName": "DEP0056: `util.isString()`" }, { "textRaw": "DEP0057: `util.isSymbol()`", "name": "dep0057:_`util.issymbol()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isSymbol() API is deprecated.

", "type": "module", "displayName": "DEP0057: `util.isSymbol()`" }, { "textRaw": "DEP0058: `util.isUndefined()`", "name": "dep0058:_`util.isundefined()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.isUndefined() API is deprecated.

", "type": "module", "displayName": "DEP0058: `util.isUndefined()`" }, { "textRaw": "DEP0059: `util.log()`", "name": "dep0059:_`util.log()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util.log() API is deprecated.

", "type": "module", "displayName": "DEP0059: `util.log()`" }, { "textRaw": "DEP0060: `util._extend()`", "name": "dep0060:_`util._extend()`", "meta": { "changes": [ { "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: Documentation-only

\n

The util._extend() API is deprecated.

", "type": "module", "displayName": "DEP0060: `util._extend()`" }, { "textRaw": "DEP0061: `fs.SyncWriteStream`", "name": "dep0061:_`fs.syncwritestream`", "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

\n

The 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": "module", "displayName": "DEP0061: `fs.SyncWriteStream`" }, { "textRaw": "DEP0062: `node --debug`", "name": "dep0062:_`node_--debug`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25828", "description": "End-of-Life." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10970", "description": "Runtime deprecation." } ] }, "desc": "

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": "module", "displayName": "DEP0062: `node --debug`" }, { "textRaw": "DEP0063: `ServerResponse.prototype.writeHeader()`", "name": "dep0063:_`serverresponse.prototype.writeheader()`", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11355", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The http module ServerResponse.prototype.writeHeader() API is\ndeprecated. Please use ServerResponse.prototype.writeHead() instead.

\n

The ServerResponse.prototype.writeHeader() method was never documented as an\nofficially supported API.

", "type": "module", "displayName": "DEP0063: `ServerResponse.prototype.writeHeader()`" }, { "textRaw": "DEP0064: `tls.createSecurePair()`", "name": "dep0064:_`tls.createsecurepair()`", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11349", "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/6063", "description": "Documentation-only deprecation." }, { "version": "v0.11.15", "pr-url": [ "https://github.com/nodejs/node-v0.x-archive/pull/8695", "https://github.com/nodejs/node-v0.x-archive/pull/8700" ], "description": "Deprecation revoked." }, { "version": "v0.11.3", "commit": "af80e7bc6e6f33c582eb1f7d37c7f5bbe9f910f7", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The tls.createSecurePair() API was deprecated in documentation in Node.js\n0.11.3. Users should use tls.Socket instead.

", "type": "module", "displayName": "DEP0064: `tls.createSecurePair()`" }, { "textRaw": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`", "name": "dep0065:_`repl.repl_mode_magic`_and_`node_repl_mode=magic`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19187", "description": "End-of-Life." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11599", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The repl module's REPL_MODE_MAGIC constant, used for replMode option, has\nbeen 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.

\n

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": "module", "displayName": "DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`" }, { "textRaw": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`", "name": "dep0066:_`outgoingmessage.prototype._headers,_outgoingmessage.prototype._headernames`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/24167", "description": "Runtime deprecation." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10941", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime

\n

The 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.

\n

The OutgoingMessage.prototype._headers and\nOutgoingMessage.prototype._headerNames properties were never documented as\nofficially supported properties.

", "type": "module", "displayName": "DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`" }, { "textRaw": "DEP0067: `OutgoingMessage.prototype._renderHeaders`", "name": "dep0067:_`outgoingmessage.prototype._renderheaders`", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10941", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The http module OutgoingMessage.prototype._renderHeaders() API is\ndeprecated.

\n

The OutgoingMessage.prototype._renderHeaders property was never documented as\nan officially supported API.

", "type": "module", "displayName": "DEP0067: `OutgoingMessage.prototype._renderHeaders`" }, { "textRaw": "DEP0068: `node debug`", "name": "dep0068:_`node_debug`", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33648", "description": "The legacy `node debug` command was removed." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11441", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

node debug corresponds to the legacy CLI debugger which has been replaced with\na V8-inspector based CLI debugger available through node inspect.

", "type": "module", "displayName": "DEP0068: `node debug`" }, { "textRaw": "DEP0069: `vm.runInDebugContext(string)`", "name": "dep0069:_`vm.runindebugcontext(string)`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/13295", "description": "End-of-Life." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/12815", "description": "Runtime deprecation." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12243", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

DebugContext has been removed in V8 and is not available in Node.js 10+.

\n

DebugContext was an experimental API.

", "type": "module", "displayName": "DEP0069: `vm.runInDebugContext(string)`" }, { "textRaw": "DEP0070: `async_hooks.currentId()`", "name": "dep0070:_`async_hooks.currentid()`", "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

\n

async_hooks.currentId() was renamed to async_hooks.executionAsyncId() for\nclarity.

\n

This change was made while async_hooks was an experimental API.

", "type": "module", "displayName": "DEP0070: `async_hooks.currentId()`" }, { "textRaw": "DEP0071: `async_hooks.triggerId()`", "name": "dep0071:_`async_hooks.triggerid()`", "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

\n

async_hooks.triggerId() was renamed to async_hooks.triggerAsyncId() for\nclarity.

\n

This change was made while async_hooks was an experimental API.

", "type": "module", "displayName": "DEP0071: `async_hooks.triggerId()`" }, { "textRaw": "DEP0072: `async_hooks.AsyncResource.triggerId()`", "name": "dep0072:_`async_hooks.asyncresource.triggerid()`", "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

\n

async_hooks.AsyncResource.triggerId() was renamed to\nasync_hooks.AsyncResource.triggerAsyncId() for clarity.

\n

This change was made while async_hooks was an experimental API.

", "type": "module", "displayName": "DEP0072: `async_hooks.AsyncResource.triggerId()`" }, { "textRaw": "DEP0073: Several internal properties of `net.Server`", "name": "dep0073:_several_internal_properties_of_`net.server`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17141", "description": "End-of-Life." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/14449", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Accessing several internal, undocumented properties of net.Server instances\nwith inappropriate names is deprecated.

\n

As the original API was undocumented and not generally useful for non-internal\ncode, no replacement API is provided.

", "type": "module", "displayName": "DEP0073: Several internal properties of `net.Server`" }, { "textRaw": "DEP0074: `REPLServer.bufferedCommand`", "name": "dep0074:_`replserver.bufferedcommand`", "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

\n

The REPLServer.bufferedCommand property was deprecated in favor of\nREPLServer.clearBufferedCommand().

", "type": "module", "displayName": "DEP0074: `REPLServer.bufferedCommand`" }, { "textRaw": "DEP0075: `REPLServer.parseREPLKeyword()`", "name": "dep0075:_`replserver.parsereplkeyword()`", "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/14223", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

REPLServer.parseREPLKeyword() was removed from userland visibility.

", "type": "module", "displayName": "DEP0075: `REPLServer.parseREPLKeyword()`" }, { "textRaw": "DEP0076: `tls.parseCertString()`", "name": "dep0076:_`tls.parsecertstring()`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/14249", "description": "Runtime deprecation." }, { "version": "v8.6.0", "pr-url": "https://github.com/nodejs/node/pull/14245", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime

\n

tls.parseCertString() is a trivial parsing helper that was made public by\nmistake. This function can usually be replaced with:

\n
const querystring = require('querystring');\nquerystring.parse(str, '\\n', '=');\n
\n

This function is not completely equivalent to querystring.parse(). One\ndifference is that querystring.parse() does url decoding:

\n
> querystring.parse('%E5%A5%BD=1', '\\n', '=');\n{ '好': '1' }\n> tls.parseCertString('%E5%A5%BD=1');\n{ '%E5%A5%BD': '1' }\n
", "type": "module", "displayName": "DEP0076: `tls.parseCertString()`" }, { "textRaw": "DEP0077: `Module._debug()`", "name": "dep0077:_`module._debug()`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/13948", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Module._debug() is deprecated.

\n

The Module._debug() function was never documented as an officially\nsupported API.

", "type": "module", "displayName": "DEP0077: `Module._debug()`" }, { "textRaw": "DEP0078: `REPLServer.turnOffEditorMode()`", "name": "dep0078:_`replserver.turnoffeditormode()`", "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/15136", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

REPLServer.turnOffEditorMode() was removed from userland visibility.

", "type": "module", "displayName": "DEP0078: `REPLServer.turnOffEditorMode()`" }, { "textRaw": "DEP0079: Custom inspection function on objects via `.inspect()`", "name": "dep0079:_custom_inspection_function_on_objects_via_`.inspect()`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/20722", "description": "End-of-Life." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16393", "description": "Runtime deprecation." }, { "version": "v8.7.0", "pr-url": "https://github.com/nodejs/node/pull/15631", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Using 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": "module", "displayName": "DEP0079: Custom inspection function on objects via `.inspect()`" }, { "textRaw": "DEP0080: `path._makeLong()`", "name": "dep0080:_`path._makelong()`", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/14956", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The 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": "module", "displayName": "DEP0080: `path._makeLong()`" }, { "textRaw": "DEP0081: `fs.truncate()` using a file descriptor", "name": "dep0081:_`fs.truncate()`_using_a_file_descriptor", "meta": { "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15990", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

fs.truncate() fs.truncateSync() usage with a file descriptor is\ndeprecated. Please use fs.ftruncate() or fs.ftruncateSync() to work with\nfile descriptors.

", "type": "module", "displayName": "DEP0081: `fs.truncate()` using a file descriptor" }, { "textRaw": "DEP0082: `REPLServer.prototype.memory()`", "name": "dep0082:_`replserver.prototype.memory()`", "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

\n

REPLServer.prototype.memory() is only necessary for the internal mechanics of\nthe REPLServer itself. Do not use this function.

", "type": "module", "displayName": "DEP0082: `REPLServer.prototype.memory()`" }, { "textRaw": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`", "name": "dep0083:_disabling_ecdh_by_setting_`ecdhcurve`_to_`false`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19794", "description": "End-of-Life." }, { "version": "v9.2.0", "pr-url": "https://github.com/nodejs/node/pull/16130", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life.

\n

The 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": "module", "displayName": "DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`" }, { "textRaw": "DEP0084: requiring bundled internal dependencies", "name": "dep0084:_requiring_bundled_internal_dependencies", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25138", "description": "This functionality has been removed." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16392", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Since 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:

\n
    \n
  • v8/tools/codemap
  • \n
  • v8/tools/consarray
  • \n
  • v8/tools/csvparser
  • \n
  • v8/tools/logreader
  • \n
  • v8/tools/profile_view
  • \n
  • v8/tools/profile
  • \n
  • v8/tools/SourceMap
  • \n
  • v8/tools/splaytree
  • \n
  • v8/tools/tickprocessor-driver
  • \n
  • v8/tools/tickprocessor
  • \n
  • node-inspect/lib/_inspect (from 7.6.0)
  • \n
  • node-inspect/lib/internal/inspect_client (from 7.6.0)
  • \n
  • node-inspect/lib/internal/inspect_repl (from 7.6.0)
  • \n
\n

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().

\n

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": "module", "displayName": "DEP0084: requiring bundled internal dependencies" }, { "textRaw": "DEP0085: AsyncHooks sensitive API", "name": "dep0085:_asynchooks_sensitive_api", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17147", "description": "End-of-Life." }, { "version": [ "v9.4.0", "v8.10.0" ], "pr-url": "https://github.com/nodejs/node/pull/16972", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The 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": "module", "displayName": "DEP0085: AsyncHooks sensitive API" }, { "textRaw": "DEP0086: Remove `runInAsyncIdScope`", "name": "dep0086:_remove_`runinasyncidscope`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17147", "description": "End-of-Life." }, { "version": [ "v9.4.0", "v8.10.0" ], "pr-url": "https://github.com/nodejs/node/pull/16972", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

runInAsyncIdScope 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": "module", "displayName": "DEP0086: Remove `runInAsyncIdScope`" }, { "textRaw": "DEP0089: `require('assert')`", "name": "dep0089:_`require('assert')`", "meta": { "changes": [ { "version": "v12.8.0", "pr-url": "https://github.com/nodejs/node/pull/28892", "description": "Deprecation revoked." }, { "version": [ "v9.9.0", "v8.13.0" ], "pr-url": "https://github.com/nodejs/node/pull/17002", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Deprecation revoked

\n

Importing assert directly was not recommended as the exposed functions use\nloose equality checks. The deprecation was revoked because use of the assert\nmodule is not discouraged, and the deprecation caused developer confusion.

", "type": "module", "displayName": "DEP0089: `require('assert')`" }, { "textRaw": "DEP0090: Invalid GCM authentication tag lengths", "name": "dep0090:_invalid_gcm_authentication_tag_lengths", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/17825", "description": "End-of-Life." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18017", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Node.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": "module", "displayName": "DEP0090: Invalid GCM authentication tag lengths" }, { "textRaw": "DEP0091: `crypto.DEFAULT_ENCODING`", "name": "dep0091:_`crypto.default_encoding`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18333", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The crypto.DEFAULT_ENCODING property is deprecated.

", "type": "module", "displayName": "DEP0091: `crypto.DEFAULT_ENCODING`" }, { "textRaw": "DEP0092: Top-level `this` bound to `module.exports`", "name": "dep0092:_top-level_`this`_bound_to_`module.exports`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16878", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

Assigning properties to the top-level this as an alternative\nto module.exports is deprecated. Developers should use exports\nor module.exports instead.

", "type": "module", "displayName": "DEP0092: Top-level `this` bound to `module.exports`" }, { "textRaw": "DEP0093: `crypto.fips` is deprecated and replaced", "name": "dep0093:_`crypto.fips`_is_deprecated_and_replaced", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18335", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The crypto.fips property is deprecated. Please use crypto.setFips()\nand crypto.getFips() instead.

", "type": "module", "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", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18418", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Using assert.fail() with more than one argument is deprecated. Use\nassert.fail() with only one argument or use a different assert module\nmethod.

", "type": "module", "displayName": "DEP0094: Using `assert.fail()` with more than one argument" }, { "textRaw": "DEP0095: `timers.enroll()`", "name": "dep0095:_`timers.enroll()`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18066", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

timers.enroll() is deprecated. Please use the publicly documented\nsetTimeout() or setInterval() instead.

", "type": "module", "displayName": "DEP0095: `timers.enroll()`" }, { "textRaw": "DEP0096: `timers.unenroll()`", "name": "dep0096:_`timers.unenroll()`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18066", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

timers.unenroll() is deprecated. Please use the publicly documented\nclearTimeout() or clearInterval() instead.

", "type": "module", "displayName": "DEP0096: `timers.unenroll()`" }, { "textRaw": "DEP0097: `MakeCallback` with `domain` property", "name": "dep0097:_`makecallback`_with_`domain`_property", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17417", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Users 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": "module", "displayName": "DEP0097: `MakeCallback` with `domain` property" }, { "textRaw": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs", "name": "dep0098:_asynchooks_embedder_`asyncresource.emitbefore`_and_`asyncresource.emitafter`_apis", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26530", "description": "End-of-Life." }, { "version": [ "v10.0.0", "v9.6.0", "v8.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/18632", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The embedded API provided by AsyncHooks exposes .emitBefore() and\n.emitAfter() methods which are very easy to use incorrectly which can lead\nto unrecoverable errors.

\n

Use asyncResource.runInAsyncScope() API instead which provides a much\nsafer, and more convenient, alternative. See\nhttps://github.com/nodejs/node/pull/18513.

", "type": "module", "displayName": "DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs" }, { "textRaw": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs", "name": "dep0099:_async_context-unaware_`node::makecallback`_c++_apis", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18632", "description": "Compile-time deprecation." } ] }, "desc": "

Type: Compile-time

\n

Certain versions of node::MakeCallback APIs available to native modules are\ndeprecated. Please use the versions of the API that accept an async_context\nparameter.

", "type": "module", "displayName": "DEP0099: Async context-unaware `node::MakeCallback` C++ APIs" }, { "textRaw": "DEP0100: `process.assert()`", "name": "dep0100:_`process.assert()`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18666", "description": "Runtime deprecation." }, { "version": "v0.3.7", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime

\n

process.assert() is deprecated. Please use the assert module instead.

\n

This was never a documented feature.

", "type": "module", "displayName": "DEP0100: `process.assert()`" }, { "textRaw": "DEP0101: `--with-lttng`", "name": "dep0101:_`--with-lttng`", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18982", "description": "End-of-Life." } ] }, "desc": "

Type: End-of-Life

\n

The --with-lttng compile-time option has been removed.

", "type": "module", "displayName": "DEP0101: `--with-lttng`" }, { "textRaw": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations", "name": "dep0102:_using_`noassert`_in_`buffer#(read|write)`_operations", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18395", "description": "End-of-Life." } ] }, "desc": "

Type: End-of-Life

\n

Using the noAssert argument has no functionality anymore. All input is going\nto be verified, no matter if it is set to true or not. Skipping the verification\ncould lead to hard to find errors and crashes.

", "type": "module", "displayName": "DEP0102: Using `noAssert` in `Buffer#(read|write)` operations" }, { "textRaw": "DEP0103: `process.binding('util').is[...]` typechecks", "name": "dep0103:_`process.binding('util').is[...]`_typechecks", "meta": { "changes": [ { "version": "v10.9.0", "pr-url": "https://github.com/nodejs/node/pull/22004", "description": "Superseded by [DEP0111](#DEP0111)." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18415", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

Using process.binding() in general should be avoided. The type checking\nmethods in particular can be replaced by using util.types.

\n

This deprecation has been superseded by the deprecation of the\nprocess.binding() API (DEP0111).

", "type": "module", "displayName": "DEP0103: `process.binding('util').is[...]` typechecks" }, { "textRaw": "DEP0104: `process.env` string coercion", "name": "dep0104:_`process.env`_string_coercion", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18990", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

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": "module", "displayName": "DEP0104: `process.env` string coercion" }, { "textRaw": "DEP0105: `decipher.finaltol`", "name": "dep0105:_`decipher.finaltol`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/19941", "description": "End-of-Life." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19353", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

decipher.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": "module", "displayName": "DEP0105: `decipher.finaltol`" }, { "textRaw": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`", "name": "dep0106:_`crypto.createcipher`_and_`crypto.createdecipher`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22089", "description": "Runtime deprecation." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19343", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime

\n

Using crypto.createCipher() and crypto.createDecipher() should be\navoided as they use a weak key derivation function (MD5 with no salt) and static\ninitialization vectors. It is recommended to derive a key using\ncrypto.pbkdf2() or crypto.scrypt() and to use\ncrypto.createCipheriv() and crypto.createDecipheriv() to obtain the\nCipher and Decipher objects respectively.

", "type": "module", "displayName": "DEP0106: `crypto.createCipher` and `crypto.createDecipher`" }, { "textRaw": "DEP0107: `tls.convertNPNProtocols()`", "name": "dep0107:_`tls.convertnpnprotocols()`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/20736", "description": "End-of-Life." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19403", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

This was an undocumented helper function not intended for use outside Node.js\ncore and obsoleted by the removal of NPN (Next Protocol Negotiation) support.

", "type": "module", "displayName": "DEP0107: `tls.convertNPNProtocols()`" }, { "textRaw": "DEP0108: `zlib.bytesRead`", "name": "dep0108:_`zlib.bytesread`", "meta": { "changes": [ { "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: Runtime

\n

Deprecated 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.

", "type": "module", "displayName": "DEP0108: `zlib.bytesRead`" }, { "textRaw": "DEP0109: `http`, `https`, and `tls` support for invalid URLs", "name": "dep0109:_`http`,_`https`,_and_`tls`_support_for_invalid_urls", "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

\n

Some 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": "module", "displayName": "DEP0109: `http`, `https`, and `tls` support for invalid URLs" }, { "textRaw": "DEP0110: `vm.Script` cached data", "name": "dep0110:_`vm.script`_cached_data", "meta": { "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/20300", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The produceCachedData option is deprecated. Use\nscript.createCachedData() instead.

", "type": "module", "displayName": "DEP0110: `vm.Script` cached data" }, { "textRaw": "DEP0111: `process.binding()`", "name": "dep0111:_`process.binding()`", "meta": { "changes": [ { "version": "v11.12.0", "pr-url": "https://github.com/nodejs/node/pull/26500", "description": "Added support for `--pending-deprecation`." }, { "version": "v10.9.0", "pr-url": "https://github.com/nodejs/node/pull/22004", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

process.binding() is for use by Node.js internal code only.

", "type": "module", "displayName": "DEP0111: `process.binding()`" }, { "textRaw": "DEP0112: `dgram` private APIs", "name": "dep0112:_`dgram`_private_apis", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22011", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The dgram module previously contained several APIs that were never meant to\naccessed 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().

", "type": "module", "displayName": "DEP0112: `dgram` private APIs" }, { "textRaw": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`", "name": "dep0113:_`cipher.setauthtag()`,_`decipher.getauthtag()`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26249", "description": "End-of-Life." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22126", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Cipher.setAuthTag() and Decipher.getAuthTag() are no longer available. They\nwere never documented and would throw when called.

", "type": "module", "displayName": "DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`" }, { "textRaw": "DEP0114: `crypto._toBuf()`", "name": "dep0114:_`crypto._tobuf()`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25338", "description": "End-of-Life." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22501", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

The crypto._toBuf() function was not designed to be used by modules outside\nof Node.js core and was removed.

", "type": "module", "displayName": "DEP0114: `crypto._toBuf()`" }, { "textRaw": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`", "name": "dep0115:_`crypto.prng()`,_`crypto.pseudorandombytes()`,_`crypto.rng()`", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": [ "https://github.com/nodejs/node/pull/22519", "https://github.com/nodejs/node/pull/23017" ], "description": "Added documentation-only deprecation with `--pending-deprecation` support." } ] }, "desc": "\n\n

Type: Documentation-only (supports --pending-deprecation)

\n

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": "module", "displayName": "DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`" }, { "textRaw": "DEP0116: Legacy URL API", "name": "dep0116:_legacy_url_api", "meta": { "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Deprecation revoked

\n

The Legacy URL API is deprecated. This includes url.format(),\nurl.parse(), url.resolve(), and the legacy urlObject. Please\nuse the WHATWG URL API instead.

", "type": "module", "displayName": "DEP0116: Legacy URL API" }, { "textRaw": "DEP0117: Native crypto handles", "name": "dep0117:_native_crypto_handles", "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

\n

Previous 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": "module", "displayName": "DEP0117: Native crypto handles" }, { "textRaw": "DEP0118: `dns.lookup()` support for a falsy host name", "name": "dep0118:_`dns.lookup()`_support_for_a_falsy_host_name", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/23173", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Previous versions of Node.js supported dns.lookup() with a falsy host name\nlike dns.lookup(false) due to backward compatibility.\nThis behavior is undocumented and is thought to be unused in real world apps.\nIt will become an error in future versions of Node.js.

", "type": "module", "displayName": "DEP0118: `dns.lookup()` support for a falsy host name" }, { "textRaw": "DEP0119: `process.binding('uv').errname()` private API", "name": "dep0119:_`process.binding('uv').errname()`_private_api", "meta": { "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/23597", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

process.binding('uv').errname() is deprecated. Please use\nutil.getSystemErrorName() instead.

", "type": "module", "displayName": "DEP0119: `process.binding('uv').errname()` private API" }, { "textRaw": "DEP0120: Windows Performance Counter support", "name": "dep0120:_windows_performance_counter_support", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/24862", "description": "End-of-Life." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22485", "description": "Runtime deprecation." } ] }, "desc": "

Type: End-of-Life

\n

Windows 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": "module", "displayName": "DEP0120: Windows Performance Counter support" }, { "textRaw": "DEP0121: `net._setSimultaneousAccepts()`", "name": "dep0121:_`net._setsimultaneousaccepts()`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23760", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The undocumented net._setSimultaneousAccepts() function was originally\nintended for debugging and performance tuning when using the child_process\nand cluster modules on Windows. The function is not generally useful and\nis being removed. See discussion here:\nhttps://github.com/nodejs/node/issues/18391

", "type": "module", "displayName": "DEP0121: `net._setSimultaneousAccepts()`" }, { "textRaw": "DEP0122: `tls` `Server.prototype.setOptions()`", "name": "dep0122:_`tls`_`server.prototype.setoptions()`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23820", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Please use Server.prototype.setSecureContext() instead.

", "type": "module", "displayName": "DEP0122: `tls` `Server.prototype.setOptions()`" }, { "textRaw": "DEP0123: setting the TLS ServerName to an IP address", "name": "dep0123:_setting_the_tls_servername_to_an_ip_address", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23329", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Setting the TLS ServerName to an IP address is not permitted by\nRFC 6066. This will be ignored in a future version.

", "type": "module", "displayName": "DEP0123: setting the TLS ServerName to an IP address" }, { "textRaw": "DEP0124: using `REPLServer.rli`", "name": "dep0124:_using_`replserver.rli`", "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

\n

This property is a reference to the instance itself.

", "type": "module", "displayName": "DEP0124: using `REPLServer.rli`" }, { "textRaw": "DEP0125: `require('_stream_wrap')`", "name": "dep0125:_`require('_stream_wrap')`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26245", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The _stream_wrap module is deprecated.

", "type": "module", "displayName": "DEP0125: `require('_stream_wrap')`" }, { "textRaw": "DEP0126: `timers.active()`", "name": "dep0126:_`timers.active()`", "meta": { "changes": [ { "version": "v11.14.0", "pr-url": "https://github.com/nodejs/node/pull/26760", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The previously undocumented timers.active() is deprecated.\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": "module", "displayName": "DEP0126: `timers.active()`" }, { "textRaw": "DEP0127: `timers._unrefActive()`", "name": "dep0127:_`timers._unrefactive()`", "meta": { "changes": [ { "version": "v11.14.0", "pr-url": "https://github.com/nodejs/node/pull/26760", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The previously undocumented and \"private\" timers._unrefActive() is deprecated.\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": "module", "displayName": "DEP0127: `timers._unrefActive()`" }, { "textRaw": "DEP0128: modules with an invalid `main` entry and an `index.js` file", "name": "dep0128:_modules_with_an_invalid_`main`_entry_and_an_`index.js`_file", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37204", "description": "Runtime deprecation." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26823", "description": "Documentation-only." } ] }, "desc": "

Type: Runtime

\n

Modules 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": "module", "displayName": "DEP0128: modules with an invalid `main` entry and an `index.js` file" }, { "textRaw": "DEP0129: `ChildProcess._channel`", "name": "dep0129:_`childprocess._channel`", "meta": { "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27949", "description": "Runtime deprecation." }, { "version": "v11.14.0", "pr-url": "https://github.com/nodejs/node/pull/26982", "description": "Documentation-only." } ] }, "desc": "

Type: Runtime

\n

The _channel property of child process objects returned by spawn() and\nsimilar functions is not intended for public use. Use ChildProcess.channel\ninstead.

", "type": "module", "displayName": "DEP0129: `ChildProcess._channel`" }, { "textRaw": "DEP0130: `Module.createRequireFromPath()`", "name": "dep0130:_`module.createrequirefrompath()`", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37201", "description": "End-of-life." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27951", "description": "Runtime deprecation." }, { "version": "v12.2.0", "pr-url": "https://github.com/nodejs/node/pull/27405", "description": "Documentation-only." } ] }, "desc": "

Type: End-of-Life

\n

Use module.createRequire() instead.

", "type": "module", "displayName": "DEP0130: `Module.createRequireFromPath()`" }, { "textRaw": "DEP0131: Legacy HTTP parser", "name": "dep0131:_legacy_http_parser", "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

\n

The 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": "module", "displayName": "DEP0131: Legacy HTTP parser" }, { "textRaw": "DEP0132: `worker.terminate()` with callback", "name": "dep0132:_`worker.terminate()`_with_callback", "meta": { "changes": [ { "version": "v12.5.0", "pr-url": "https://github.com/nodejs/node/pull/28021", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Passing a callback to worker.terminate() is deprecated. Use the returned\nPromise instead, or a listener to the worker’s 'exit' event.

", "type": "module", "displayName": "DEP0132: `worker.terminate()` with callback" }, { "textRaw": "DEP0133: `http` `connection`", "name": "dep0133:_`http`_`connection`", "meta": { "changes": [ { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/29015", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

Prefer response.socket over response.connection and\nrequest.socket over request.connection.

", "type": "module", "displayName": "DEP0133: `http` `connection`" }, { "textRaw": "DEP0134: `process._tickCallback`", "name": "dep0134:_`process._tickcallback`", "meta": { "changes": [ { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/29781", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

The process._tickCallback property was never documented as\nan officially supported API.

", "type": "module", "displayName": "DEP0134: `process._tickCallback`" }, { "textRaw": "DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal", "name": "dep0135:_`writestream.open()`_and_`readstream.open()`_are_internal", "meta": { "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29061", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

WriteStream.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": "module", "displayName": "DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal" }, { "textRaw": "DEP0136: `http` `finished`", "name": "dep0136:_`http`_`finished`", "meta": { "changes": [ { "version": [ "v13.4.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/28679", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

response.finished indicates whether response.end() has been\ncalled, not whether 'finish' has been emitted and the underlying data\nis flushed.

\n

Use response.writableFinished or response.writableEnded\naccordingly instead to avoid the ambiguity.

\n

To maintain existing behavior response.finished should be replaced with\nresponse.writableEnded.

", "type": "module", "displayName": "DEP0136: `http` `finished`" }, { "textRaw": "DEP0137: Closing fs.FileHandle on garbage collection", "name": "dep0137:_closing_fs.filehandle_on_garbage_collection", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/28396", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

Allowing a fs.FileHandle 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.

\n

Please ensure that all fs.FileHandle objects are explicitly closed using\nFileHandle.prototype.close() when the fs.FileHandle is no longer needed:

\n
const fsPromises = require('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
", "type": "module", "displayName": "DEP0137: Closing fs.FileHandle on garbage collection" }, { "textRaw": "DEP0138: `process.mainModule`", "name": "dep0138:_`process.mainmodule`", "meta": { "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/32232", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

process.mainModule is a CommonJS-only feature while process global\nobject is shared with non-CommonJS environment. Its use within ECMAScript\nmodules is unsupported.

\n

It is deprecated in favor of require.main, because it serves the same\npurpose and is only available on CommonJS environment.

", "type": "module", "displayName": "DEP0138: `process.mainModule`" }, { "textRaw": "DEP0139: `process.umask()` with no arguments", "name": "dep0139:_`process.umask()`_with_no_arguments", "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

\n

Calling 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": "module", "displayName": "DEP0139: `process.umask()` with no arguments" }, { "textRaw": "DEP0140: Use `request.destroy()` instead of `request.abort()`", "name": "dep0140:_use_`request.destroy()`_instead_of_`request.abort()`", "meta": { "changes": [ { "version": [ "v14.1.0", "v13.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/32807", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

Use request.destroy() instead of request.abort().

", "type": "module", "displayName": "DEP0140: Use `request.destroy()` instead of `request.abort()`" }, { "textRaw": "DEP0141: `repl.inputStream` and `repl.outputStream`", "name": "dep0141:_`repl.inputstream`_and_`repl.outputstream`", "meta": { "changes": [ { "version": "v14.3.0", "pr-url": "https://github.com/nodejs/node/pull/33294", "description": "Documentation-only (supports [`--pending-deprecation`][])." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

The repl module exported the input and output stream twice. Use .input\ninstead of .inputStream and .output instead of .outputStream.

", "type": "module", "displayName": "DEP0141: `repl.inputStream` and `repl.outputStream`" }, { "textRaw": "DEP0142: `repl._builtinLibs`", "name": "dep0142:_`repl._builtinlibs`", "meta": { "changes": [ { "version": "v14.3.0", "pr-url": "https://github.com/nodejs/node/pull/33294", "description": "Documentation-only (supports [`--pending-deprecation`][])." } ] }, "desc": "

Type: Documentation-only

\n

The repl module exports a _builtinLibs property that contains an array with\nnative modules. It was incomplete so far and instead it's better to rely upon\nrequire('module').builtinModules.

", "type": "module", "displayName": "DEP0142: `repl._builtinLibs`" }, { "textRaw": "DEP0143: `Transform._transformState`", "name": "dep0143:_`transform._transformstate`", "meta": { "changes": [ { "version": "v14.5.0", "pr-url": "https://github.com/nodejs/node/pull/33126", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime\nTransform._transformState will be removed in future versions where it is\nno longer required due to simplification of the implementation.

", "type": "module", "displayName": "DEP0143: `Transform._transformState`" }, { "textRaw": "DEP0144: `module.parent`", "name": "dep0144:_`module.parent`", "meta": { "changes": [ { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/32217", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only (supports --pending-deprecation)

\n

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.

\n

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:

\n
if (require.main === module) {\n  // Code section that will run only if current file is the entry point.\n}\n
\n

When looking for the CommonJS modules that have required the current one,\nrequire.cache and module.children can be used:

\n
const moduleParents = Object.values(require.cache)\n  .filter((m) => m.children.includes(module));\n
", "type": "module", "displayName": "DEP0144: `module.parent`" }, { "textRaw": "DEP0145: `socket.bufferSize`", "name": "dep0145:_`socket.buffersize`", "meta": { "changes": [ { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34088", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

socket.bufferSize is just an alias for writable.writableLength.

", "type": "module", "displayName": "DEP0145: `socket.bufferSize`" }, { "textRaw": "DEP0146: `new crypto.Certificate()`", "name": "dep0146:_`new_crypto.certificate()`", "meta": { "changes": [ { "version": "v14.9.0", "pr-url": "https://github.com/nodejs/node/pull/34697", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only

\n

The crypto.Certificate() constructor is deprecated. Use\nstatic methods of crypto.Certificate() instead.

", "type": "module", "displayName": "DEP0146: `new crypto.Certificate()`" }, { "textRaw": "DEP0147: `fs.rmdir(path, { recursive: true })`", "name": "dep0147:_`fs.rmdir(path,_{_recursive:_true_})`", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37302", "description": "Runtime deprecation." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35562", "description": "Runtime deprecation for permissive behavior." }, { "version": "v14.14.0", "pr-url": "https://github.com/nodejs/node/pull/35579", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Runtime

\n

In future versions of Node.js, recursive option will be ignored for\nfs.rmdir, fs.rmdirSync, and fs.promises.rmdir.

\n

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.

", "type": "module", "displayName": "DEP0147: `fs.rmdir(path, { recursive: true })`" }, { "textRaw": "DEP0148: Folder mappings in `\"exports\"` (trailing `\"/\"`)", "name": "dep0148:_folder_mappings_in_`\"exports\"`_(trailing_`\"/\"`)", "meta": { "changes": [ { "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: Runtime

\n

Using a trailing \"/\" to define\nsubpath folder mappings in the subpath exports or\nsubpath imports fields is deprecated. Use subpath patterns instead.

", "type": "module", "displayName": "DEP0148: Folder mappings in `\"exports\"` (trailing `\"/\"`)" }, { "textRaw": "DEP0149: `http.IncomingMessage#connection`", "name": "dep0149:_`http.incomingmessage#connection`", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/33768", "description": "Documentation-only deprecation." } ] }, "desc": "

Type: Documentation-only.

\n

Prefer message.socket over message.connection.

", "type": "module", "displayName": "DEP0149: `http.IncomingMessage#connection`" }, { "textRaw": "DEP0150: Changing the value of `process.config`", "name": "dep0150:_changing_the_value_of_`process.config`", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36902", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The process.config property is intended to provide access to configuration\nsettings set when the Node.js binary was compiled. However, the property has\nbeen mutable by user code making it impossible to rely on. The ability to\nchange the value has been deprecated and will be disabled in the future.

", "type": "module", "displayName": "DEP0150: Changing the value of `process.config`" }, { "textRaw": "DEP0151: Main index lookup and extension searching", "name": "dep0151:_main_index_lookup_and_extension_searching", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37206", "description": "Runtime deprecation." }, { "version": "v15.8.0", "pr-url": "https://github.com/nodejs/node/pull/36918", "description": "Documentation-only deprecation with `--pending-deprecation` support." } ] }, "desc": "

Type: Runtime

\n

Previously, index.js and extension searching lookups would apply to\nimport 'pkg' main entry point resolution, even when resolving ES modules.

\n

With this deprecation, all ES module main entry point resolutions require\nan explicit \"exports\" or \"main\" entry with the exact file extension.

", "type": "module", "displayName": "DEP0151: Main index lookup and extension searching" }, { "textRaw": "DEP0152: Extension PerformanceEntry properties", "name": "dep0152:_extension_performanceentry_properties", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Runtime deprecation." } ] }, "desc": "

Type: Runtime

\n

The 'gc', 'http2', and 'http' <PerformanceEntry> object types 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 existing accessors have been\ndeprecated and should no longer be used.

", "type": "module", "displayName": "DEP0152: Extension PerformanceEntry properties" } ], "type": "misc", "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 four categories of\nerrors:

\n
    \n
  • Standard JavaScript errors such as <EvalError>, <SyntaxError>, <RangeError>,\n<ReferenceError>, <TypeError>, and <URIError>.
  • \n
  • System errors triggered by underlying operating system constraints such\nas attempting to open a file that does not exist or attempting to send data\nover a closed socket.
  • \n
  • User-specified errors triggered by application code.
  • \n
  • 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 assert module.
  • \n
\n

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.

", "miscs": [ { "textRaw": "Error propagation and interception", "name": "Error propagation and interception", "type": "misc", "desc": "

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.

\n

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.

\n
// 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
\n

Any use of the JavaScript throw mechanism will raise an exception that\nmust be handled using try…catch or the Node.js process will exit\nimmediately.

\n

With few exceptions, Synchronous APIs (any blocking method that does not\naccept a callback function, such as fs.readFileSync), will use throw\nto report errors.

\n

Errors that occur within Asynchronous APIs may be reported in multiple ways:

\n
    \n
  • Most 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.
  • \n
\n\n
const fs = require('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
\n
    \n
  • \n

    When an asynchronous method is called on an object that is an\nEventEmitter, errors can be routed to that object's 'error' event.

    \n
    const net = require('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
    \n
  • \n
  • \n

    A 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.

    \n
  • \n
\n

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).

\n

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: The domain module is\nused appropriately or a handler has been registered for the\n'uncaughtException' event.

\n
const EventEmitter = require('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
\n

Errors generated in this way cannot be intercepted using try…catch as\nthey are thrown after the calling code has already exited.

\n

Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.

", "miscs": [ { "textRaw": "Error-first callbacks", "name": "Error-first callbacks", "type": "misc", "desc": "

Most asynchronous methods exposed by the Node.js core API follow an idiomatic\npattern referred to as an error-first callback. With this pattern, a callback\nfunction is passed to the method as an argument. When the operation either\ncompletes or an error is raised, the callback function is called with the\nError object (if any) passed as the first argument. If no error was raised,\nthe first argument will be passed as null.

\n
const fs = require('fs');\n\nfunction errorFirstCallback(err, data) {\n  if (err) {\n    console.error('There was an error', err);\n    return;\n  }\n  console.log(data);\n}\n\nfs.readFile('/some/file/that/does-not-exist', errorFirstCallback);\nfs.readFile('/some/file/that/does-exist', errorFirstCallback);\n
\n

The JavaScript try…catch mechanism cannot be used to intercept errors\ngenerated by asynchronous APIs. A common mistake for beginners is to try to\nuse throw inside an error-first callback:

\n
// THIS WILL NOT WORK:\nconst fs = require('fs');\n\ntry {\n  fs.readFile('/some/file/that/does-not-exist', (err, data) => {\n    // Mistaken assumption: throwing here...\n    if (err) {\n      throw err;\n    }\n  });\n} catch (err) {\n  // This will not catch the throw!\n  console.error(err);\n}\n
\n

This will not work because the callback function passed to fs.readFile() is\ncalled asynchronously. By the time the callback has been called, the\nsurrounding code, including the try…catch block, will have already exited.\nThrowing an error inside the callback can crash the Node.js process in most\ncases. If domains are enabled, or a handler has been registered with\nprocess.on('uncaughtException'), such errors can be intercepted.

" } ] }, { "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.

\n

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.

" }, { "textRaw": "OpenSSL errors", "name": "openssl_errors", "desc": "

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.

", "properties": [ { "textRaw": "`error.opensslErrorStack`", "name": "opensslErrorStack", "desc": "

An array of errors that can give context to where in the OpenSSL library an\nerror originates from.

" }, { "textRaw": "`error.function`", "name": "function", "desc": "

The OpenSSL function the error originates in.

" }, { "textRaw": "`error.library`", "name": "library", "desc": "

The OpenSSL library the error originates in.

" }, { "textRaw": "`error.reason`", "name": "reason", "desc": "

A human-readable string describing the reason for the error.

\n

" } ], "type": "misc", "displayName": "OpenSSL errors" }, { "textRaw": "Node.js error codes", "name": "node.js_error_codes", "desc": "

", "modules": [ { "textRaw": "`ABORT_ERR`", "name": "`abort_err`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Used when an operation has been aborted (typically using an AbortController).

\n

APIs not using AbortSignals typically do not raise an error with this code.

\n

This code does not use the regular ERR_* convention Node.js errors use in\norder to be compatible with the web platform's AbortError.

\n

", "type": "module", "displayName": "`ABORT_ERR`" }, { "textRaw": "`ERR_AMBIGUOUS_ARGUMENT`", "name": "`err_ambiguous_argument`", "desc": "

A function argument is being used in a way that suggests that the function\nsignature may be misunderstood. This is thrown by the assert module when the\nmessage parameter in assert.throws(block, message) matches the error message\nthrown by block because that usage suggests that the user believes message\nis the expected message rather than the message the AssertionError will\ndisplay if block does not throw.

\n

", "type": "module", "displayName": "`ERR_AMBIGUOUS_ARGUMENT`" }, { "textRaw": "`ERR_ARG_NOT_ITERABLE`", "name": "`err_arg_not_iterable`", "desc": "

An iterable argument (i.e. a value that works with for...of loops) was\nrequired, but not provided to a Node.js API.

\n

", "type": "module", "displayName": "`ERR_ARG_NOT_ITERABLE`" }, { "textRaw": "`ERR_ASSERTION`", "name": "`err_assertion`", "desc": "

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 assert module.

\n

", "type": "module", "displayName": "`ERR_ASSERTION`" }, { "textRaw": "`ERR_ASYNC_CALLBACK`", "name": "`err_async_callback`", "desc": "

An attempt was made to register something that is not a function as an\nAsyncHooks callback.

\n

", "type": "module", "displayName": "`ERR_ASYNC_CALLBACK`" }, { "textRaw": "`ERR_ASYNC_TYPE`", "name": "`err_async_type`", "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

", "type": "module", "displayName": "`ERR_ASYNC_TYPE`" }, { "textRaw": "`ERR_BROTLI_COMPRESSION_FAILED`", "name": "`err_brotli_compression_failed`", "desc": "

Data passed to a Brotli stream was not successfully compressed.

\n

", "type": "module", "displayName": "`ERR_BROTLI_COMPRESSION_FAILED`" }, { "textRaw": "`ERR_BROTLI_INVALID_PARAM`", "name": "`err_brotli_invalid_param`", "desc": "

An invalid parameter key was passed during construction of a Brotli stream.

\n

", "type": "module", "displayName": "`ERR_BROTLI_INVALID_PARAM`" }, { "textRaw": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`", "name": "`err_buffer_context_not_available`", "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.

\n

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.

\n

", "type": "module", "displayName": "`ERR_BUFFER_CONTEXT_NOT_AVAILABLE`" }, { "textRaw": "`ERR_BUFFER_OUT_OF_BOUNDS`", "name": "`err_buffer_out_of_bounds`", "desc": "

An operation outside the bounds of a Buffer was attempted.

\n

", "type": "module", "displayName": "`ERR_BUFFER_OUT_OF_BOUNDS`" }, { "textRaw": "`ERR_BUFFER_TOO_LARGE`", "name": "`err_buffer_too_large`", "desc": "

An attempt has been made to create a Buffer larger than the maximum allowed\nsize.

\n

", "type": "module", "displayName": "`ERR_BUFFER_TOO_LARGE`" }, { "textRaw": "`ERR_CANNOT_WATCH_SIGINT`", "name": "`err_cannot_watch_sigint`", "desc": "

Node.js was unable to watch for the SIGINT signal.

\n

", "type": "module", "displayName": "`ERR_CANNOT_WATCH_SIGINT`" }, { "textRaw": "`ERR_CHILD_CLOSED_BEFORE_REPLY`", "name": "`err_child_closed_before_reply`", "desc": "

A child process was closed before the parent received a reply.

\n

", "type": "module", "displayName": "`ERR_CHILD_CLOSED_BEFORE_REPLY`" }, { "textRaw": "`ERR_CHILD_PROCESS_IPC_REQUIRED`", "name": "`err_child_process_ipc_required`", "desc": "

Used when a child process is being forked without specifying an IPC channel.

\n

", "type": "module", "displayName": "`ERR_CHILD_PROCESS_IPC_REQUIRED`" }, { "textRaw": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`", "name": "`err_child_process_stdio_maxbuffer`", "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.

\n

", "type": "module", "displayName": "`ERR_CHILD_PROCESS_STDIO_MAXBUFFER`" }, { "textRaw": "`ERR_CLOSED_MESSAGE_PORT`", "name": "`err_closed_message_port`", "desc": "\n

There was an attempt to use a MessagePort instance in a closed\nstate, usually after .close() has been called.

\n

", "type": "module", "displayName": "`ERR_CLOSED_MESSAGE_PORT`" }, { "textRaw": "`ERR_CONSOLE_WRITABLE_STREAM`", "name": "`err_console_writable_stream`", "desc": "

Console was instantiated without stdout stream, or Console has a\nnon-writable stdout or stderr stream.

\n

", "type": "module", "displayName": "`ERR_CONSOLE_WRITABLE_STREAM`" }, { "textRaw": "`ERR_CONSTRUCT_CALL_INVALID`", "name": "`err_construct_call_invalid`", "desc": "\n

A class constructor was called that is not callable.

\n

", "type": "module", "displayName": "`ERR_CONSTRUCT_CALL_INVALID`" }, { "textRaw": "`ERR_CONSTRUCT_CALL_REQUIRED`", "name": "`err_construct_call_required`", "desc": "

A constructor for a class was called without new.

\n

", "type": "module", "displayName": "`ERR_CONSTRUCT_CALL_REQUIRED`" }, { "textRaw": "`ERR_CONTEXT_NOT_INITIALIZED`", "name": "`err_context_not_initialized`", "desc": "

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

", "type": "module", "displayName": "`ERR_CONTEXT_NOT_INITIALIZED`" }, { "textRaw": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`", "name": "`err_crypto_custom_engine_not_supported`", "desc": "

A client certificate engine was requested that is not supported by the version\nof OpenSSL being used.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED`" }, { "textRaw": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`", "name": "`err_crypto_ecdh_invalid_format`", "desc": "

An invalid value for the format argument was passed to the crypto.ECDH()\nclass getPublicKey() method.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_ECDH_INVALID_FORMAT`" }, { "textRaw": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`", "name": "`err_crypto_ecdh_invalid_public_key`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY`" }, { "textRaw": "`ERR_CRYPTO_ENGINE_UNKNOWN`", "name": "`err_crypto_engine_unknown`", "desc": "

An invalid crypto engine identifier was passed to\nrequire('crypto').setEngine().

\n

", "type": "module", "displayName": "`ERR_CRYPTO_ENGINE_UNKNOWN`" }, { "textRaw": "`ERR_CRYPTO_FIPS_FORCED`", "name": "`err_crypto_fips_forced`", "desc": "

The --force-fips command-line argument was used but there was an attempt\nto enable or disable FIPS mode in the crypto module.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_FIPS_FORCED`" }, { "textRaw": "`ERR_CRYPTO_FIPS_UNAVAILABLE`", "name": "`err_crypto_fips_unavailable`", "desc": "

An attempt was made to enable or disable FIPS mode, but FIPS mode was not\navailable.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_FIPS_UNAVAILABLE`" }, { "textRaw": "`ERR_CRYPTO_HASH_FINALIZED`", "name": "`err_crypto_hash_finalized`", "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.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_HASH_FINALIZED`" }, { "textRaw": "`ERR_CRYPTO_HASH_UPDATE_FAILED`", "name": "`err_crypto_hash_update_failed`", "desc": "

hash.update() failed for any reason. This should rarely, if ever, happen.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_HASH_UPDATE_FAILED`" }, { "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY`", "name": "`err_crypto_incompatible_key`", "desc": "

The given crypto keys are incompatible with the attempted operation.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY`" }, { "textRaw": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`", "name": "`err_crypto_incompatible_key_options`", "desc": "

The selected public or private key encoding is incompatible with other options.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS`" }, { "textRaw": "`ERR_CRYPTO_INITIALIZATION_FAILED`", "name": "`err_crypto_initialization_failed`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Initialization of the crypto subsystem failed.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INITIALIZATION_FAILED`" }, { "textRaw": "`ERR_CRYPTO_INVALID_AUTH_TAG`", "name": "`err_crypto_invalid_auth_tag`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid authentication tag was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_AUTH_TAG`" }, { "textRaw": "`ERR_CRYPTO_INVALID_COUNTER`", "name": "`err_crypto_invalid_counter`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid counter was provided for a counter-mode cipher.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_COUNTER`" }, { "textRaw": "`ERR_CRYPTO_INVALID_CURVE`", "name": "`err_crypto_invalid_curve`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid elliptic-curve was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_CURVE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_DIGEST`", "name": "`err_crypto_invalid_digest`", "desc": "

An invalid crypto digest algorithm was specified.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_DIGEST`" }, { "textRaw": "`ERR_CRYPTO_INVALID_IV`", "name": "`err_crypto_invalid_iv`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid initialization vector was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_IV`" }, { "textRaw": "`ERR_CRYPTO_INVALID_JWK`", "name": "`err_crypto_invalid_jwk`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid JSON Web Key was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_JWK`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`", "name": "`err_crypto_invalid_key_object_type`", "desc": "

The given crypto key object's type is invalid for the attempted operation.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYLEN`", "name": "`err_crypto_invalid_keylen`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid key length was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_KEYLEN`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYPAIR`", "name": "`err_crypto_invalid_keypair`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid key pair was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_KEYPAIR`" }, { "textRaw": "`ERR_CRYPTO_INVALID_KEYTYPE`", "name": "`err_crypto_invalid_keytype`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid key type was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_KEYTYPE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_MESSAGELEN`", "name": "`err_crypto_invalid_messagelen`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid message length was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_MESSAGELEN`" }, { "textRaw": "`ERR_CRYPTO_INVALID_SCRYPT_PARAMS`", "name": "`err_crypto_invalid_scrypt_params`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Invalid scrypt algorithm parameters were provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_SCRYPT_PARAMS`" }, { "textRaw": "`ERR_CRYPTO_INVALID_STATE`", "name": "`err_crypto_invalid_state`", "desc": "

A crypto method was used on an object that was in an invalid state. For\ninstance, calling cipher.getAuthTag() before calling cipher.final().

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_STATE`" }, { "textRaw": "`ERR_CRYPTO_INVALID_TAG_LENGTH`", "name": "`err_crypto_invalid_tag_length`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid authentication tag length was provided.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_INVALID_TAG_LENGTH`" }, { "textRaw": "`ERR_CRYPTO_JOB_INIT_FAILED`", "name": "`err_crypto_job_init_failed`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Initialization of an asynchronous crypto operation failed.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_JOB_INIT_FAILED`" }, { "textRaw": "`ERR_CRYPTO_JWK_UNSUPPORTED_CURVE`", "name": "`err_crypto_jwk_unsupported_curve`", "desc": "

Key's Elliptic Curve is not registered for use in the\nJSON Web Key Elliptic Curve Registry.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_JWK_UNSUPPORTED_CURVE`" }, { "textRaw": "`ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE`", "name": "`err_crypto_jwk_unsupported_key_type`", "desc": "

Key's Asymmetric Key Type is not registered for use in the\nJSON Web Key Types Registry.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE`" }, { "textRaw": "`ERR_CRYPTO_OPERATION_FAILED`", "name": "`err_crypto_operation_failed`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

A crypto operation failed for an otherwise unspecified reason.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_OPERATION_FAILED`" }, { "textRaw": "`ERR_CRYPTO_PBKDF2_ERROR`", "name": "`err_crypto_pbkdf2_error`", "desc": "

The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide\nmore details and therefore neither does Node.js.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_PBKDF2_ERROR`" }, { "textRaw": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`", "name": "`err_crypto_scrypt_invalid_parameter`", "desc": "

One or more crypto.scrypt() or crypto.scryptSync() parameters are\noutside their legal range.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_SCRYPT_INVALID_PARAMETER`" }, { "textRaw": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`", "name": "`err_crypto_scrypt_not_supported`", "desc": "

Node.js was compiled without scrypt support. Not possible with the official\nrelease binaries but can happen with custom builds, including distro builds.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_SCRYPT_NOT_SUPPORTED`" }, { "textRaw": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`", "name": "`err_crypto_sign_key_required`", "desc": "

A signing key was not provided to the sign.sign() method.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_SIGN_KEY_REQUIRED`" }, { "textRaw": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`", "name": "`err_crypto_timing_safe_equal_length`", "desc": "

crypto.timingSafeEqual() was called with Buffer, TypedArray, or\nDataView arguments of different lengths.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH`" }, { "textRaw": "`ERR_CRYPTO_UNKNOWN_CIPHER`", "name": "`err_crypto_unknown_cipher`", "desc": "

An unknown cipher was specified.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_UNKNOWN_CIPHER`" }, { "textRaw": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`", "name": "`err_crypto_unknown_dh_group`", "desc": "

An unknown Diffie-Hellman group name was given. See\ncrypto.getDiffieHellman() for a list of valid group names.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_UNKNOWN_DH_GROUP`" }, { "textRaw": "`ERR_CRYPTO_UNSUPPORTED_OPERATION`", "name": "`err_crypto_unsupported_operation`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An attempt to invoke an unsupported crypto operation was made.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_UNSUPPORTED_OPERATION`" }, { "textRaw": "`ERR_DEBUGGER_ERROR`", "name": "`err_debugger_error`", "meta": { "added": [ "v16.4.0" ], "changes": [] }, "desc": "

An error occurred with the debugger.

\n

", "type": "module", "displayName": "`ERR_DEBUGGER_ERROR`" }, { "textRaw": "`ERR_DEBUGGER_STARTUP_ERROR`", "name": "`err_debugger_startup_error`", "meta": { "added": [ "v16.4.0" ], "changes": [] }, "desc": "

The debugger timed out waiting for the required host/port to be free.

\n

", "type": "module", "displayName": "`ERR_DEBUGGER_STARTUP_ERROR`" }, { "textRaw": "`ERR_DLOPEN_FAILED`", "name": "`err_dlopen_failed`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

A call to process.dlopen() failed.

\n

", "type": "module", "displayName": "`ERR_DLOPEN_FAILED`" }, { "textRaw": "`ERR_DIR_CLOSED`", "name": "`err_dir_closed`", "desc": "

The fs.Dir was previously closed.

\n

", "type": "module", "displayName": "`ERR_DIR_CLOSED`" }, { "textRaw": "`ERR_DIR_CONCURRENT_OPERATION`", "name": "`err_dir_concurrent_operation`", "meta": { "added": [ "v14.3.0" ], "changes": [] }, "desc": "

A synchronous read or close call was attempted on an fs.Dir which has\nongoing asynchronous operations.

\n

", "type": "module", "displayName": "`ERR_DIR_CONCURRENT_OPERATION`" }, { "textRaw": "`ERR_DNS_SET_SERVERS_FAILED`", "name": "`err_dns_set_servers_failed`", "desc": "

c-ares failed to set the DNS server.

\n

", "type": "module", "displayName": "`ERR_DNS_SET_SERVERS_FAILED`" }, { "textRaw": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`", "name": "`err_domain_callback_not_available`", "desc": "

The domain module was not usable since it could not establish the required\nerror handling hooks, because\nprocess.setUncaughtExceptionCaptureCallback() had been called at an\nearlier point in time.

\n

", "type": "module", "displayName": "`ERR_DOMAIN_CALLBACK_NOT_AVAILABLE`" }, { "textRaw": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`", "name": "`err_domain_cannot_set_uncaught_exception_capture`", "desc": "

process.setUncaughtExceptionCaptureCallback() could not be called\nbecause the domain module has been loaded at an earlier point in time.

\n

The stack trace is extended to include the point in time at which the\ndomain module had been loaded.

\n

", "type": "module", "displayName": "`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`" }, { "textRaw": "`ERR_ENCODING_INVALID_ENCODED_DATA`", "name": "`err_encoding_invalid_encoded_data`", "desc": "

Data provided to TextDecoder() API was invalid according to the encoding\nprovided.

\n

", "type": "module", "displayName": "`ERR_ENCODING_INVALID_ENCODED_DATA`" }, { "textRaw": "`ERR_ENCODING_NOT_SUPPORTED`", "name": "`err_encoding_not_supported`", "desc": "

Encoding provided to TextDecoder() API was not one of the\nWHATWG Supported Encodings.

\n

", "type": "module", "displayName": "`ERR_ENCODING_NOT_SUPPORTED`" }, { "textRaw": "`ERR_EVAL_ESM_CANNOT_PRINT`", "name": "`err_eval_esm_cannot_print`", "desc": "

--print cannot be used with ESM input.

\n

", "type": "module", "displayName": "`ERR_EVAL_ESM_CANNOT_PRINT`" }, { "textRaw": "`ERR_EVENT_RECURSION`", "name": "`err_event_recursion`", "desc": "

Thrown when an attempt is made to recursively dispatch an event on EventTarget.

\n

", "type": "module", "displayName": "`ERR_EVENT_RECURSION`" }, { "textRaw": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`", "name": "`err_execution_environment_not_available`", "desc": "

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

", "type": "module", "displayName": "`ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE`" }, { "textRaw": "`ERR_FALSY_VALUE_REJECTION`", "name": "`err_falsy_value_rejection`", "desc": "

A Promise that was callbackified via util.callbackify() was rejected with a\nfalsy value.

\n

", "type": "module", "displayName": "`ERR_FALSY_VALUE_REJECTION`" }, { "textRaw": "`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`", "name": "`err_feature_unavailable_on_platform`", "meta": { "added": [ "v14.0.0" ], "changes": [] }, "desc": "

Used when a feature that is not available\nto the current platform which is running Node.js is used.

\n

", "type": "module", "displayName": "`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`" }, { "textRaw": "`ERR_FS_CP_DIR_TO_NON_DIR`", "name": "`err_fs_cp_dir_to_non_dir`", "desc": "\n

An attempt was made to copy a directory to a non-directory (file, symlink,\netc.) using fs.cp().

\n

", "type": "module", "displayName": "`ERR_FS_CP_DIR_TO_NON_DIR`" }, { "textRaw": "`ERR_FS_CP_EEXIST`", "name": "`err_fs_cp_eexist`", "desc": "\n

An attempt was made to copy over a file that already existed with\nfs.cp(), with the force and errorOnExist set to true.

\n

", "type": "module", "displayName": "`ERR_FS_CP_EEXIST`" }, { "textRaw": "`ERR_FS_CP_EINVAL`", "name": "`err_fs_cp_einval`", "desc": "\n

When using fs.cp(), src or dest pointed to an invalid path.

\n

", "type": "module", "displayName": "`ERR_FS_CP_EINVAL`" }, { "textRaw": "`ERR_FS_CP_FIFO_PIPE`", "name": "`err_fs_cp_fifo_pipe`", "desc": "\n

An attempt was made to copy a named pipe with fs.cp().

\n

", "type": "module", "displayName": "`ERR_FS_CP_FIFO_PIPE`" }, { "textRaw": "`ERR_FS_CP_NON_DIR_TO_DIR`", "name": "`err_fs_cp_non_dir_to_dir`", "desc": "\n

An attempt was made to copy a non-directory (file, symlink, etc.) to a directory\nusing fs.cp().

\n

", "type": "module", "displayName": "`ERR_FS_CP_NON_DIR_TO_DIR`" }, { "textRaw": "`ERR_FS_CP_SOCKET`", "name": "`err_fs_cp_socket`", "desc": "\n

An attempt was made to copy to a socket with fs.cp().

\n

", "type": "module", "displayName": "`ERR_FS_CP_SOCKET`" }, { "textRaw": "`ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY`", "name": "`err_fs_cp_symlink_to_subdirectory`", "desc": "\n

When using fs.cp(), a symlink in dest pointed to a subdirectory\nof src.

\n

", "type": "module", "displayName": "`ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY`" }, { "textRaw": "`ERR_FS_CP_UNKNOWN`", "name": "`err_fs_cp_unknown`", "desc": "\n

An attempt was made to copy to an unknown file type with fs.cp().

\n

", "type": "module", "displayName": "`ERR_FS_CP_UNKNOWN`" }, { "textRaw": "`ERR_FS_EISDIR`", "name": "`err_fs_eisdir`", "desc": "

Path is a directory.

\n

", "type": "module", "displayName": "`ERR_FS_EISDIR`" }, { "textRaw": "`ERR_FS_FILE_TOO_LARGE`", "name": "`err_fs_file_too_large`", "desc": "

An attempt has been made to read a file whose size is larger than the maximum\nallowed size for a Buffer.

\n

", "type": "module", "displayName": "`ERR_FS_FILE_TOO_LARGE`" }, { "textRaw": "`ERR_FS_INVALID_SYMLINK_TYPE`", "name": "`err_fs_invalid_symlink_type`", "desc": "

An invalid symlink type was passed to the fs.symlink() or\nfs.symlinkSync() methods.

\n

", "type": "module", "displayName": "`ERR_FS_INVALID_SYMLINK_TYPE`" }, { "textRaw": "`ERR_HTTP_HEADERS_SENT`", "name": "`err_http_headers_sent`", "desc": "

An attempt was made to add more headers after the headers had already been sent.

\n

", "type": "module", "displayName": "`ERR_HTTP_HEADERS_SENT`" }, { "textRaw": "`ERR_HTTP_INVALID_HEADER_VALUE`", "name": "`err_http_invalid_header_value`", "desc": "

An invalid HTTP header value was specified.

\n

", "type": "module", "displayName": "`ERR_HTTP_INVALID_HEADER_VALUE`" }, { "textRaw": "`ERR_HTTP_INVALID_STATUS_CODE`", "name": "`err_http_invalid_status_code`", "desc": "

Status code was outside the regular status code range (100-999).

\n

", "type": "module", "displayName": "`ERR_HTTP_INVALID_STATUS_CODE`" }, { "textRaw": "`ERR_HTTP_REQUEST_TIMEOUT`", "name": "`err_http_request_timeout`", "desc": "

The client has not sent the entire request within the allowed time.

\n

", "type": "module", "displayName": "`ERR_HTTP_REQUEST_TIMEOUT`" }, { "textRaw": "`ERR_HTTP_SOCKET_ENCODING`", "name": "`err_http_socket_encoding`", "desc": "

Changing the socket encoding is not allowed per RFC 7230 Section 3.

\n

", "type": "module", "displayName": "`ERR_HTTP_SOCKET_ENCODING`" }, { "textRaw": "`ERR_HTTP_TRAILER_INVALID`", "name": "`err_http_trailer_invalid`", "desc": "

The Trailer header was set even though the transfer encoding does not support\nthat.

\n

", "type": "module", "displayName": "`ERR_HTTP_TRAILER_INVALID`" }, { "textRaw": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`", "name": "`err_http2_altsvc_invalid_origin`", "desc": "

HTTP/2 ALTSVC frames require a valid origin.

\n

", "type": "module", "displayName": "`ERR_HTTP2_ALTSVC_INVALID_ORIGIN`" }, { "textRaw": "`ERR_HTTP2_ALTSVC_LENGTH`", "name": "`err_http2_altsvc_length`", "desc": "

HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

\n

", "type": "module", "displayName": "`ERR_HTTP2_ALTSVC_LENGTH`" }, { "textRaw": "`ERR_HTTP2_CONNECT_AUTHORITY`", "name": "`err_http2_connect_authority`", "desc": "

For HTTP/2 requests using the CONNECT method, the :authority pseudo-header\nis required.

\n

", "type": "module", "displayName": "`ERR_HTTP2_CONNECT_AUTHORITY`" }, { "textRaw": "`ERR_HTTP2_CONNECT_PATH`", "name": "`err_http2_connect_path`", "desc": "

For HTTP/2 requests using the CONNECT method, the :path pseudo-header is\nforbidden.

\n

", "type": "module", "displayName": "`ERR_HTTP2_CONNECT_PATH`" }, { "textRaw": "`ERR_HTTP2_CONNECT_SCHEME`", "name": "`err_http2_connect_scheme`", "desc": "

For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is\nforbidden.

\n

", "type": "module", "displayName": "`ERR_HTTP2_CONNECT_SCHEME`" }, { "textRaw": "`ERR_HTTP2_ERROR`", "name": "`err_http2_error`", "desc": "

A non-specific HTTP/2 error has occurred.

\n

", "type": "module", "displayName": "`ERR_HTTP2_ERROR`" }, { "textRaw": "`ERR_HTTP2_GOAWAY_SESSION`", "name": "`err_http2_goaway_session`", "desc": "

New HTTP/2 Streams may not be opened after the Http2Session has received a\nGOAWAY frame from the connected peer.

\n

", "type": "module", "displayName": "`ERR_HTTP2_GOAWAY_SESSION`" }, { "textRaw": "`ERR_HTTP2_HEADER_SINGLE_VALUE`", "name": "`err_http2_header_single_value`", "desc": "

Multiple values were provided for an HTTP/2 header field that was required to\nhave only a single value.

\n

", "type": "module", "displayName": "`ERR_HTTP2_HEADER_SINGLE_VALUE`" }, { "textRaw": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`", "name": "`err_http2_headers_after_respond`", "desc": "

An additional headers was specified after an HTTP/2 response was initiated.

\n

", "type": "module", "displayName": "`ERR_HTTP2_HEADERS_AFTER_RESPOND`" }, { "textRaw": "`ERR_HTTP2_HEADERS_SENT`", "name": "`err_http2_headers_sent`", "desc": "

An attempt was made to send multiple response headers.

\n

", "type": "module", "displayName": "`ERR_HTTP2_HEADERS_SENT`" }, { "textRaw": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`", "name": "`err_http2_info_status_not_allowed`", "desc": "

Informational HTTP status codes (1xx) may not be set as the response status\ncode on HTTP/2 responses.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INFO_STATUS_NOT_ALLOWED`" }, { "textRaw": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`", "name": "`err_http2_invalid_connection_headers`", "desc": "

HTTP/1 connection specific headers are forbidden to be used in HTTP/2\nrequests and responses.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_CONNECTION_HEADERS`" }, { "textRaw": "`ERR_HTTP2_INVALID_HEADER_VALUE`", "name": "`err_http2_invalid_header_value`", "desc": "

An invalid HTTP/2 header value was specified.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_HEADER_VALUE`" }, { "textRaw": "`ERR_HTTP2_INVALID_INFO_STATUS`", "name": "`err_http2_invalid_info_status`", "desc": "

An invalid HTTP informational status code has been specified. Informational\nstatus codes must be an integer between 100 and 199 (inclusive).

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_INFO_STATUS`" }, { "textRaw": "`ERR_HTTP2_INVALID_ORIGIN`", "name": "`err_http2_invalid_origin`", "desc": "

HTTP/2 ORIGIN frames require a valid origin.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_ORIGIN`" }, { "textRaw": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`", "name": "`err_http2_invalid_packed_settings_length`", "desc": "

Input Buffer and Uint8Array instances passed to the\nhttp2.getUnpackedSettings() API must have a length that is a multiple of\nsix.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH`" }, { "textRaw": "`ERR_HTTP2_INVALID_PSEUDOHEADER`", "name": "`err_http2_invalid_pseudoheader`", "desc": "

Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme,\nand :method) may be used.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_PSEUDOHEADER`" }, { "textRaw": "`ERR_HTTP2_INVALID_SESSION`", "name": "`err_http2_invalid_session`", "desc": "

An action was performed on an Http2Session object that had already been\ndestroyed.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_SESSION`" }, { "textRaw": "`ERR_HTTP2_INVALID_SETTING_VALUE`", "name": "`err_http2_invalid_setting_value`", "desc": "

An invalid value has been specified for an HTTP/2 setting.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_SETTING_VALUE`" }, { "textRaw": "`ERR_HTTP2_INVALID_STREAM`", "name": "`err_http2_invalid_stream`", "desc": "

An operation was performed on a stream that had already been destroyed.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INVALID_STREAM`" }, { "textRaw": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`", "name": "`err_http2_max_pending_settings_ack`", "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.

\n

", "type": "module", "displayName": "`ERR_HTTP2_MAX_PENDING_SETTINGS_ACK`" }, { "textRaw": "`ERR_HTTP2_NESTED_PUSH`", "name": "`err_http2_nested_push`", "desc": "

An attempt was made to initiate a new push stream from within a push stream.\nNested push streams are not permitted.

\n

", "type": "module", "displayName": "`ERR_HTTP2_NESTED_PUSH`" }, { "textRaw": "`ERR_HTTP2_NO_MEM`", "name": "`err_http2_no_mem`", "desc": "

Out of memory when using the http2session.setLocalWindowSize(windowSize) API.

\n

", "type": "module", "displayName": "`ERR_HTTP2_NO_MEM`" }, { "textRaw": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`", "name": "`err_http2_no_socket_manipulation`", "desc": "

An attempt was made to directly manipulate (read, write, pause, resume, etc.) a\nsocket attached to an Http2Session.

\n

", "type": "module", "displayName": "`ERR_HTTP2_NO_SOCKET_MANIPULATION`" }, { "textRaw": "`ERR_HTTP2_ORIGIN_LENGTH`", "name": "`err_http2_origin_length`", "desc": "

HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

\n

", "type": "module", "displayName": "`ERR_HTTP2_ORIGIN_LENGTH`" }, { "textRaw": "`ERR_HTTP2_OUT_OF_STREAMS`", "name": "`err_http2_out_of_streams`", "desc": "

The number of streams created on a single HTTP/2 session reached the maximum\nlimit.

\n

", "type": "module", "displayName": "`ERR_HTTP2_OUT_OF_STREAMS`" }, { "textRaw": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`", "name": "`err_http2_payload_forbidden`", "desc": "

A message payload was specified for an HTTP response code for which a payload is\nforbidden.

\n

", "type": "module", "displayName": "`ERR_HTTP2_PAYLOAD_FORBIDDEN`" }, { "textRaw": "`ERR_HTTP2_PING_CANCEL`", "name": "`err_http2_ping_cancel`", "desc": "

An HTTP/2 ping was canceled.

\n

", "type": "module", "displayName": "`ERR_HTTP2_PING_CANCEL`" }, { "textRaw": "`ERR_HTTP2_PING_LENGTH`", "name": "`err_http2_ping_length`", "desc": "

HTTP/2 ping payloads must be exactly 8 bytes in length.

\n

", "type": "module", "displayName": "`ERR_HTTP2_PING_LENGTH`" }, { "textRaw": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`", "name": "`err_http2_pseudoheader_not_allowed`", "desc": "

An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header\nkey names that begin with the : prefix.

\n

", "type": "module", "displayName": "`ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED`" }, { "textRaw": "`ERR_HTTP2_PUSH_DISABLED`", "name": "`err_http2_push_disabled`", "desc": "

An attempt was made to create a push stream, which had been disabled by the\nclient.

\n

", "type": "module", "displayName": "`ERR_HTTP2_PUSH_DISABLED`" }, { "textRaw": "`ERR_HTTP2_SEND_FILE`", "name": "`err_http2_send_file`", "desc": "

An attempt was made to use the Http2Stream.prototype.responseWithFile() API to\nsend a directory.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SEND_FILE`" }, { "textRaw": "`ERR_HTTP2_SEND_FILE_NOSEEK`", "name": "`err_http2_send_file_noseek`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SEND_FILE_NOSEEK`" }, { "textRaw": "`ERR_HTTP2_SESSION_ERROR`", "name": "`err_http2_session_error`", "desc": "

The Http2Session closed with a non-zero error code.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SESSION_ERROR`" }, { "textRaw": "`ERR_HTTP2_SETTINGS_CANCEL`", "name": "`err_http2_settings_cancel`", "desc": "

The Http2Session settings canceled.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SETTINGS_CANCEL`" }, { "textRaw": "`ERR_HTTP2_SOCKET_BOUND`", "name": "`err_http2_socket_bound`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SOCKET_BOUND`" }, { "textRaw": "`ERR_HTTP2_SOCKET_UNBOUND`", "name": "`err_http2_socket_unbound`", "desc": "

An attempt was made to use the socket property of an Http2Session that\nhas already been closed.

\n

", "type": "module", "displayName": "`ERR_HTTP2_SOCKET_UNBOUND`" }, { "textRaw": "`ERR_HTTP2_STATUS_101`", "name": "`err_http2_status_101`", "desc": "

Use of the 101 Informational status code is forbidden in HTTP/2.

\n

", "type": "module", "displayName": "`ERR_HTTP2_STATUS_101`" }, { "textRaw": "`ERR_HTTP2_STATUS_INVALID`", "name": "`err_http2_status_invalid`", "desc": "

An invalid HTTP status code has been specified. Status codes must be an integer\nbetween 100 and 599 (inclusive).

\n

", "type": "module", "displayName": "`ERR_HTTP2_STATUS_INVALID`" }, { "textRaw": "`ERR_HTTP2_STREAM_CANCEL`", "name": "`err_http2_stream_cancel`", "desc": "

An Http2Stream was destroyed before any data was transmitted to the connected\npeer.

\n

", "type": "module", "displayName": "`ERR_HTTP2_STREAM_CANCEL`" }, { "textRaw": "`ERR_HTTP2_STREAM_ERROR`", "name": "`err_http2_stream_error`", "desc": "

A non-zero error code was been specified in an RST_STREAM frame.

\n

", "type": "module", "displayName": "`ERR_HTTP2_STREAM_ERROR`" }, { "textRaw": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`", "name": "`err_http2_stream_self_dependency`", "desc": "

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

", "type": "module", "displayName": "`ERR_HTTP2_STREAM_SELF_DEPENDENCY`" }, { "textRaw": "`ERR_HTTP2_TOO_MANY_INVALID_FRAMES`", "name": "`err_http2_too_many_invalid_frames`", "desc": "\n

The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,\nas specified through the maxSessionInvalidFrames option, has been exceeded.

\n

", "type": "module", "displayName": "`ERR_HTTP2_TOO_MANY_INVALID_FRAMES`" }, { "textRaw": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`", "name": "`err_http2_trailers_already_sent`", "desc": "

Trailing headers have already been sent on the Http2Stream.

\n

", "type": "module", "displayName": "`ERR_HTTP2_TRAILERS_ALREADY_SENT`" }, { "textRaw": "`ERR_HTTP2_TRAILERS_NOT_READY`", "name": "`err_http2_trailers_not_ready`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_HTTP2_TRAILERS_NOT_READY`" }, { "textRaw": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`", "name": "`err_http2_unsupported_protocol`", "desc": "

http2.connect() was passed a URL that uses any protocol other than http: or\nhttps:.

\n

", "type": "module", "displayName": "`ERR_HTTP2_UNSUPPORTED_PROTOCOL`" }, { "textRaw": "`ERR_ILLEGAL_CONSTRUCTOR`", "name": "`err_illegal_constructor`", "desc": "

An attempt was made to construct an object using a non-public constructor.

\n

", "type": "module", "displayName": "`ERR_ILLEGAL_CONSTRUCTOR`" }, { "textRaw": "`ERR_INCOMPATIBLE_OPTION_PAIR`", "name": "`err_incompatible_option_pair`", "desc": "

An option pair is incompatible with each other and cannot be used at the same\ntime.

\n

", "type": "module", "displayName": "`ERR_INCOMPATIBLE_OPTION_PAIR`" }, { "textRaw": "`ERR_INPUT_TYPE_NOT_ALLOWED`", "name": "`err_input_type_not_allowed`", "stability": 1, "stabilityText": "Experimental", "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.

\n

", "type": "module", "displayName": "`ERR_INPUT_TYPE_NOT_ALLOWED`" }, { "textRaw": "`ERR_INSPECTOR_ALREADY_ACTIVATED`", "name": "`err_inspector_already_activated`", "desc": "

While using the 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.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_ALREADY_ACTIVATED`" }, { "textRaw": "`ERR_INSPECTOR_ALREADY_CONNECTED`", "name": "`err_inspector_already_connected`", "desc": "

While using the inspector module, an attempt was made to connect when the\ninspector was already connected.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_ALREADY_CONNECTED`" }, { "textRaw": "`ERR_INSPECTOR_CLOSED`", "name": "`err_inspector_closed`", "desc": "

While using the inspector module, an attempt was made to use the inspector\nafter the session had already closed.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_CLOSED`" }, { "textRaw": "`ERR_INSPECTOR_COMMAND`", "name": "`err_inspector_command`", "desc": "

An error occurred while issuing a command via the inspector module.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_COMMAND`" }, { "textRaw": "`ERR_INSPECTOR_NOT_ACTIVE`", "name": "`err_inspector_not_active`", "desc": "

The inspector is not active when inspector.waitForDebugger() is called.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_NOT_ACTIVE`" }, { "textRaw": "`ERR_INSPECTOR_NOT_AVAILABLE`", "name": "`err_inspector_not_available`", "desc": "

The inspector module is not available for use.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_NOT_AVAILABLE`" }, { "textRaw": "`ERR_INSPECTOR_NOT_CONNECTED`", "name": "`err_inspector_not_connected`", "desc": "

While using the inspector module, an attempt was made to use the inspector\nbefore it was connected.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_NOT_CONNECTED`" }, { "textRaw": "`ERR_INSPECTOR_NOT_WORKER`", "name": "`err_inspector_not_worker`", "desc": "

An API was called on the main thread that can only be used from\nthe worker thread.

\n

", "type": "module", "displayName": "`ERR_INSPECTOR_NOT_WORKER`" }, { "textRaw": "`ERR_INTERNAL_ASSERTION`", "name": "`err_internal_assertion`", "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

", "type": "module", "displayName": "`ERR_INTERNAL_ASSERTION`" }, { "textRaw": "`ERR_INVALID_ADDRESS_FAMILY`", "name": "`err_invalid_address_family`", "desc": "

The provided address family is not understood by the Node.js API.

\n

", "type": "module", "displayName": "`ERR_INVALID_ADDRESS_FAMILY`" }, { "textRaw": "`ERR_INVALID_ARG_TYPE`", "name": "`err_invalid_arg_type`", "desc": "

An argument of the wrong type was passed to a Node.js API.

\n

", "type": "module", "displayName": "`ERR_INVALID_ARG_TYPE`" }, { "textRaw": "`ERR_INVALID_ARG_VALUE`", "name": "`err_invalid_arg_value`", "desc": "

An invalid or unsupported value was passed for a given argument.

\n

", "type": "module", "displayName": "`ERR_INVALID_ARG_VALUE`" }, { "textRaw": "`ERR_INVALID_ASYNC_ID`", "name": "`err_invalid_async_id`", "desc": "

An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id\nless than -1 should never happen.

\n

", "type": "module", "displayName": "`ERR_INVALID_ASYNC_ID`" }, { "textRaw": "`ERR_INVALID_BUFFER_SIZE`", "name": "`err_invalid_buffer_size`", "desc": "

A swap was performed on a Buffer but its size was not compatible with the\noperation.

\n

", "type": "module", "displayName": "`ERR_INVALID_BUFFER_SIZE`" }, { "textRaw": "`ERR_INVALID_CALLBACK`", "name": "`err_invalid_callback`", "desc": "

A callback function was required but was not been provided to a Node.js API.

\n

", "type": "module", "displayName": "`ERR_INVALID_CALLBACK`" }, { "textRaw": "`ERR_INVALID_CHAR`", "name": "`err_invalid_char`", "desc": "

Invalid characters were detected in headers.

\n

", "type": "module", "displayName": "`ERR_INVALID_CHAR`" }, { "textRaw": "`ERR_INVALID_CURSOR_POS`", "name": "`err_invalid_cursor_pos`", "desc": "

A cursor on a given stream cannot be moved to a specified row without a\nspecified column.

\n

", "type": "module", "displayName": "`ERR_INVALID_CURSOR_POS`" }, { "textRaw": "`ERR_INVALID_FD`", "name": "`err_invalid_fd`", "desc": "

A file descriptor ('fd') was not valid (e.g. it was a negative value).

\n

", "type": "module", "displayName": "`ERR_INVALID_FD`" }, { "textRaw": "`ERR_INVALID_FD_TYPE`", "name": "`err_invalid_fd_type`", "desc": "

A file descriptor ('fd') type was not valid.

\n

", "type": "module", "displayName": "`ERR_INVALID_FD_TYPE`" }, { "textRaw": "`ERR_INVALID_FILE_URL_HOST`", "name": "`err_invalid_file_url_host`", "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.

\n

", "type": "module", "displayName": "`ERR_INVALID_FILE_URL_HOST`" }, { "textRaw": "`ERR_INVALID_FILE_URL_PATH`", "name": "`err_invalid_file_url_path`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_INVALID_FILE_URL_PATH`" }, { "textRaw": "`ERR_INVALID_HANDLE_TYPE`", "name": "`err_invalid_handle_type`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_INVALID_HANDLE_TYPE`" }, { "textRaw": "`ERR_INVALID_HTTP_TOKEN`", "name": "`err_invalid_http_token`", "desc": "

An invalid HTTP token was supplied.

\n

", "type": "module", "displayName": "`ERR_INVALID_HTTP_TOKEN`" }, { "textRaw": "`ERR_INVALID_IP_ADDRESS`", "name": "`err_invalid_ip_address`", "desc": "

An IP address is not valid.

\n

", "type": "module", "displayName": "`ERR_INVALID_IP_ADDRESS`" }, { "textRaw": "`ERR_INVALID_MODULE`", "name": "`err_invalid_module`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An attempt was made to load a module that does not exist or was otherwise not\nvalid.

\n

", "type": "module", "displayName": "`ERR_INVALID_MODULE`" }, { "textRaw": "`ERR_INVALID_MODULE_SPECIFIER`", "name": "`err_invalid_module_specifier`", "desc": "

The imported module string is an invalid URL, package name, or package subpath\nspecifier.

\n

", "type": "module", "displayName": "`ERR_INVALID_MODULE_SPECIFIER`" }, { "textRaw": "`ERR_INVALID_PACKAGE_CONFIG`", "name": "`err_invalid_package_config`", "desc": "

An invalid package.json file failed parsing.

\n

", "type": "module", "displayName": "`ERR_INVALID_PACKAGE_CONFIG`" }, { "textRaw": "`ERR_INVALID_PACKAGE_TARGET`", "name": "`err_invalid_package_target`", "desc": "

The package.json \"exports\" field contains an invalid target mapping\nvalue for the attempted module resolution.

\n

", "type": "module", "displayName": "`ERR_INVALID_PACKAGE_TARGET`" }, { "textRaw": "`ERR_INVALID_PERFORMANCE_MARK`", "name": "`err_invalid_performance_mark`", "desc": "

While using the Performance Timing API (perf_hooks), a performance mark is\ninvalid.

\n

", "type": "module", "displayName": "`ERR_INVALID_PERFORMANCE_MARK`" }, { "textRaw": "`ERR_INVALID_PROTOCOL`", "name": "`err_invalid_protocol`", "desc": "

An invalid options.protocol was passed to http.request().

\n

", "type": "module", "displayName": "`ERR_INVALID_PROTOCOL`" }, { "textRaw": "`ERR_INVALID_REPL_EVAL_CONFIG`", "name": "`err_invalid_repl_eval_config`", "desc": "

Both breakEvalOnSigint and eval options were set in the REPL config,\nwhich is not supported.

\n

", "type": "module", "displayName": "`ERR_INVALID_REPL_EVAL_CONFIG`" }, { "textRaw": "`ERR_INVALID_REPL_INPUT`", "name": "`err_invalid_repl_input`", "desc": "

The input may not be used in the REPL. The conditions under which this\nerror is used are described in the REPL documentation.

\n

", "type": "module", "displayName": "`ERR_INVALID_REPL_INPUT`" }, { "textRaw": "`ERR_INVALID_RETURN_PROPERTY`", "name": "`err_invalid_return_property`", "desc": "

Thrown in case a function option does not provide a valid value for one of its\nreturned object properties on execution.

\n

", "type": "module", "displayName": "`ERR_INVALID_RETURN_PROPERTY`" }, { "textRaw": "`ERR_INVALID_RETURN_PROPERTY_VALUE`", "name": "`err_invalid_return_property_value`", "desc": "

Thrown in case a function option does not provide an expected value\ntype for one of its returned object properties on execution.

\n

", "type": "module", "displayName": "`ERR_INVALID_RETURN_PROPERTY_VALUE`" }, { "textRaw": "`ERR_INVALID_RETURN_VALUE`", "name": "`err_invalid_return_value`", "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

", "type": "module", "displayName": "`ERR_INVALID_RETURN_VALUE`" }, { "textRaw": "`ERR_INVALID_STATE`", "name": "`err_invalid_state`", "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

", "type": "module", "displayName": "`ERR_INVALID_STATE`" }, { "textRaw": "`ERR_INVALID_SYNC_FORK_INPUT`", "name": "`err_invalid_sync_fork_input`", "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.

\n

", "type": "module", "displayName": "`ERR_INVALID_SYNC_FORK_INPUT`" }, { "textRaw": "`ERR_INVALID_THIS`", "name": "`err_invalid_this`", "desc": "

A Node.js API function was called with an incompatible this value.

\n
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

", "type": "module", "displayName": "`ERR_INVALID_THIS`" }, { "textRaw": "`ERR_INVALID_TRANSFER_OBJECT`", "name": "`err_invalid_transfer_object`", "desc": "

An invalid transfer object was passed to postMessage().

\n

", "type": "module", "displayName": "`ERR_INVALID_TRANSFER_OBJECT`" }, { "textRaw": "`ERR_INVALID_TUPLE`", "name": "`err_invalid_tuple`", "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.

\n

", "type": "module", "displayName": "`ERR_INVALID_TUPLE`" }, { "textRaw": "`ERR_INVALID_URI`", "name": "`err_invalid_uri`", "desc": "

An invalid URI was passed.

\n

", "type": "module", "displayName": "`ERR_INVALID_URI`" }, { "textRaw": "`ERR_INVALID_URL`", "name": "`err_invalid_url`", "desc": "

An invalid URL was passed to the WHATWG\nURL constructor to be parsed. The thrown error object\ntypically has an additional property 'input' that contains the URL that failed\nto parse.

\n

", "type": "module", "displayName": "`ERR_INVALID_URL`" }, { "textRaw": "`ERR_INVALID_URL_SCHEME`", "name": "`err_invalid_url_scheme`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_INVALID_URL_SCHEME`" }, { "textRaw": "`ERR_IPC_CHANNEL_CLOSED`", "name": "`err_ipc_channel_closed`", "desc": "

An attempt was made to use an IPC communication channel that was already closed.

\n

", "type": "module", "displayName": "`ERR_IPC_CHANNEL_CLOSED`" }, { "textRaw": "`ERR_IPC_DISCONNECTED`", "name": "`err_ipc_disconnected`", "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.

\n

", "type": "module", "displayName": "`ERR_IPC_DISCONNECTED`" }, { "textRaw": "`ERR_IPC_ONE_PIPE`", "name": "`err_ipc_one_pipe`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_IPC_ONE_PIPE`" }, { "textRaw": "`ERR_IPC_SYNC_FORK`", "name": "`err_ipc_sync_fork`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_IPC_SYNC_FORK`" }, { "textRaw": "`ERR_MANIFEST_ASSERT_INTEGRITY`", "name": "`err_manifest_assert_integrity`", "desc": "

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

", "type": "module", "displayName": "`ERR_MANIFEST_ASSERT_INTEGRITY`" }, { "textRaw": "`ERR_MANIFEST_DEPENDENCY_MISSING`", "name": "`err_manifest_dependency_missing`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_DEPENDENCY_MISSING`" }, { "textRaw": "`ERR_MANIFEST_INTEGRITY_MISMATCH`", "name": "`err_manifest_integrity_mismatch`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_INTEGRITY_MISMATCH`" }, { "textRaw": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`", "name": "`err_manifest_invalid_resource_field`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_INVALID_RESOURCE_FIELD`" }, { "textRaw": "`ERR_MANIFEST_PARSE_POLICY`", "name": "`err_manifest_parse_policy`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_PARSE_POLICY`" }, { "textRaw": "`ERR_MANIFEST_TDZ`", "name": "`err_manifest_tdz`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_TDZ`" }, { "textRaw": "`ERR_MANIFEST_UNKNOWN_ONERROR`", "name": "`err_manifest_unknown_onerror`", "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

", "type": "module", "displayName": "`ERR_MANIFEST_UNKNOWN_ONERROR`" }, { "textRaw": "`ERR_MEMORY_ALLOCATION_FAILED`", "name": "`err_memory_allocation_failed`", "desc": "

An attempt was made to allocate memory (usually in the C++ layer) but it\nfailed.

\n

", "type": "module", "displayName": "`ERR_MEMORY_ALLOCATION_FAILED`" }, { "textRaw": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`", "name": "`err_message_target_context_unavailable`", "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.

\n

", "type": "module", "displayName": "`ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`" }, { "textRaw": "`ERR_METHOD_NOT_IMPLEMENTED`", "name": "`err_method_not_implemented`", "desc": "

A method is required but not implemented.

\n

", "type": "module", "displayName": "`ERR_METHOD_NOT_IMPLEMENTED`" }, { "textRaw": "`ERR_MISSING_ARGS`", "name": "`err_missing_args`", "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.

\n

", "type": "module", "displayName": "`ERR_MISSING_ARGS`" }, { "textRaw": "`ERR_MISSING_OPTION`", "name": "`err_missing_option`", "desc": "

For APIs that accept options objects, some options might be mandatory. This code\nis thrown if a required option is missing.

\n

", "type": "module", "displayName": "`ERR_MISSING_OPTION`" }, { "textRaw": "`ERR_MISSING_PASSPHRASE`", "name": "`err_missing_passphrase`", "desc": "

An attempt was made to read an encrypted key without specifying a passphrase.

\n

", "type": "module", "displayName": "`ERR_MISSING_PASSPHRASE`" }, { "textRaw": "`ERR_MISSING_PLATFORM_FOR_WORKER`", "name": "`err_missing_platform_for_worker`", "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

", "type": "module", "displayName": "`ERR_MISSING_PLATFORM_FOR_WORKER`" }, { "textRaw": "`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`", "name": "`err_missing_transferable_in_transfer_list`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

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.

\n

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.

\n

", "type": "module", "displayName": "`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`" }, { "textRaw": "`ERR_MODULE_NOT_FOUND`", "name": "`err_module_not_found`", "stability": 1, "stabilityText": "Experimental", "desc": "

An ES Module could not be resolved.

\n

", "type": "module", "displayName": "`ERR_MODULE_NOT_FOUND`" }, { "textRaw": "`ERR_MULTIPLE_CALLBACK`", "name": "`err_multiple_callback`", "desc": "

A callback was called more than once.

\n

A 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

", "type": "module", "displayName": "`ERR_MULTIPLE_CALLBACK`" }, { "textRaw": "`ERR_NAPI_CONS_FUNCTION`", "name": "`err_napi_cons_function`", "desc": "

While using Node-API, a constructor passed was not a function.

\n

", "type": "module", "displayName": "`ERR_NAPI_CONS_FUNCTION`" }, { "textRaw": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`", "name": "`err_napi_invalid_dataview_args`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_NAPI_INVALID_DATAVIEW_ARGS`" }, { "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`", "name": "`err_napi_invalid_typedarray_alignment`", "desc": "

While calling napi_create_typedarray(), the provided offset was not a\nmultiple of the element size.

\n

", "type": "module", "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT`" }, { "textRaw": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`", "name": "`err_napi_invalid_typedarray_length`", "desc": "

While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

\n

", "type": "module", "displayName": "`ERR_NAPI_INVALID_TYPEDARRAY_LENGTH`" }, { "textRaw": "`ERR_NAPI_TSFN_CALL_JS`", "name": "`err_napi_tsfn_call_js`", "desc": "

An error occurred while invoking the JavaScript portion of the thread-safe\nfunction.

\n

", "type": "module", "displayName": "`ERR_NAPI_TSFN_CALL_JS`" }, { "textRaw": "`ERR_NAPI_TSFN_GET_UNDEFINED`", "name": "`err_napi_tsfn_get_undefined`", "desc": "

An error occurred while attempting to retrieve the JavaScript undefined\nvalue.

\n

", "type": "module", "displayName": "`ERR_NAPI_TSFN_GET_UNDEFINED`" }, { "textRaw": "`ERR_NAPI_TSFN_START_IDLE_LOOP`", "name": "`err_napi_tsfn_start_idle_loop`", "desc": "

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

", "type": "module", "displayName": "`ERR_NAPI_TSFN_START_IDLE_LOOP`" }, { "textRaw": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`", "name": "`err_napi_tsfn_stop_idle_loop`", "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

", "type": "module", "displayName": "`ERR_NAPI_TSFN_STOP_IDLE_LOOP`" }, { "textRaw": "`ERR_NO_CRYPTO`", "name": "`err_no_crypto`", "desc": "

An attempt was made to use crypto features while Node.js was not compiled with\nOpenSSL crypto support.

\n

", "type": "module", "displayName": "`ERR_NO_CRYPTO`" }, { "textRaw": "`ERR_NO_ICU`", "name": "`err_no_icu`", "desc": "

An attempt was made to use features that require ICU, but Node.js was not\ncompiled with ICU support.

\n

", "type": "module", "displayName": "`ERR_NO_ICU`" }, { "textRaw": "`ERR_NON_CONTEXT_AWARE_DISABLED`", "name": "`err_non_context_aware_disabled`", "desc": "

A non-context-aware native addon was loaded in a process that disallows them.

\n

", "type": "module", "displayName": "`ERR_NON_CONTEXT_AWARE_DISABLED`" }, { "textRaw": "`ERR_OUT_OF_RANGE`", "name": "`err_out_of_range`", "desc": "

A given value is out of the accepted range.

\n

", "type": "module", "displayName": "`ERR_OUT_OF_RANGE`" }, { "textRaw": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`", "name": "`err_package_import_not_defined`", "desc": "

The package.json \"imports\" field does not define the given internal\npackage specifier mapping.

\n

", "type": "module", "displayName": "`ERR_PACKAGE_IMPORT_NOT_DEFINED`" }, { "textRaw": "`ERR_PACKAGE_PATH_NOT_EXPORTED`", "name": "`err_package_path_not_exported`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_PACKAGE_PATH_NOT_EXPORTED`" }, { "textRaw": "`ERR_PERFORMANCE_INVALID_TIMESTAMP`", "name": "`err_performance_invalid_timestamp`", "desc": "

An invalid timestamp value was provided for a performance mark or measure.

\n

", "type": "module", "displayName": "`ERR_PERFORMANCE_INVALID_TIMESTAMP`" }, { "textRaw": "`ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS`", "name": "`err_performance_measure_invalid_options`", "desc": "

Invalid options were provided for a performance measure.

\n

", "type": "module", "displayName": "`ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS`" }, { "textRaw": "`ERR_PROTO_ACCESS`", "name": "`err_proto_access`", "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.

\n

", "type": "module", "displayName": "`ERR_PROTO_ACCESS`" }, { "textRaw": "`ERR_REQUIRE_ESM`", "name": "`err_require_esm`", "stability": 1, "stabilityText": "Experimental", "desc": "

An attempt was made to require() an ES Module.

\n

", "type": "module", "displayName": "`ERR_REQUIRE_ESM`" }, { "textRaw": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`", "name": "`err_script_execution_interrupted`", "desc": "

Script execution was interrupted by SIGINT (For example,\nCtrl+C was pressed.)

\n

", "type": "module", "displayName": "`ERR_SCRIPT_EXECUTION_INTERRUPTED`" }, { "textRaw": "`ERR_SCRIPT_EXECUTION_TIMEOUT`", "name": "`err_script_execution_timeout`", "desc": "

Script execution timed out, possibly due to bugs in the script being executed.

\n

", "type": "module", "displayName": "`ERR_SCRIPT_EXECUTION_TIMEOUT`" }, { "textRaw": "`ERR_SERVER_ALREADY_LISTEN`", "name": "`err_server_already_listen`", "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.

\n

", "type": "module", "displayName": "`ERR_SERVER_ALREADY_LISTEN`" }, { "textRaw": "`ERR_SERVER_NOT_RUNNING`", "name": "`err_server_not_running`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_SERVER_NOT_RUNNING`" }, { "textRaw": "`ERR_SOCKET_ALREADY_BOUND`", "name": "`err_socket_already_bound`", "desc": "

An attempt was made to bind a socket that has already been bound.

\n

", "type": "module", "displayName": "`ERR_SOCKET_ALREADY_BOUND`" }, { "textRaw": "`ERR_SOCKET_BAD_BUFFER_SIZE`", "name": "`err_socket_bad_buffer_size`", "desc": "

An invalid (negative) size was passed for either the recvBufferSize or\nsendBufferSize options in dgram.createSocket().

\n

", "type": "module", "displayName": "`ERR_SOCKET_BAD_BUFFER_SIZE`" }, { "textRaw": "`ERR_SOCKET_BAD_PORT`", "name": "`err_socket_bad_port`", "desc": "

An API function expecting a port >= 0 and < 65536 received an invalid value.

\n

", "type": "module", "displayName": "`ERR_SOCKET_BAD_PORT`" }, { "textRaw": "`ERR_SOCKET_BAD_TYPE`", "name": "`err_socket_bad_type`", "desc": "

An API function expecting a socket type (udp4 or udp6) received an invalid\nvalue.

\n

", "type": "module", "displayName": "`ERR_SOCKET_BAD_TYPE`" }, { "textRaw": "`ERR_SOCKET_BUFFER_SIZE`", "name": "`err_socket_buffer_size`", "desc": "

While using dgram.createSocket(), the size of the receive or send Buffer\ncould not be determined.

\n

", "type": "module", "displayName": "`ERR_SOCKET_BUFFER_SIZE`" }, { "textRaw": "`ERR_SOCKET_CLOSED`", "name": "`err_socket_closed`", "desc": "

An attempt was made to operate on an already closed socket.

\n

", "type": "module", "displayName": "`ERR_SOCKET_CLOSED`" }, { "textRaw": "`ERR_SOCKET_DGRAM_IS_CONNECTED`", "name": "`err_socket_dgram_is_connected`", "desc": "

A dgram.connect() call was made on an already connected socket.

\n

", "type": "module", "displayName": "`ERR_SOCKET_DGRAM_IS_CONNECTED`" }, { "textRaw": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`", "name": "`err_socket_dgram_not_connected`", "desc": "

A dgram.disconnect() or dgram.remoteAddress() call was made on a\ndisconnected socket.

\n

", "type": "module", "displayName": "`ERR_SOCKET_DGRAM_NOT_CONNECTED`" }, { "textRaw": "`ERR_SOCKET_DGRAM_NOT_RUNNING`", "name": "`err_socket_dgram_not_running`", "desc": "

A call was made and the UDP subsystem was not running.

\n

", "type": "module", "displayName": "`ERR_SOCKET_DGRAM_NOT_RUNNING`" }, { "textRaw": "`ERR_SRI_PARSE`", "name": "`err_sri_parse`", "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

", "type": "module", "displayName": "`ERR_SRI_PARSE`" }, { "textRaw": "`ERR_STREAM_ALREADY_FINISHED`", "name": "`err_stream_already_finished`", "desc": "

A stream method was called that cannot complete because the stream was\nfinished.

\n

", "type": "module", "displayName": "`ERR_STREAM_ALREADY_FINISHED`" }, { "textRaw": "`ERR_STREAM_CANNOT_PIPE`", "name": "`err_stream_cannot_pipe`", "desc": "

An attempt was made to call stream.pipe() on a Writable stream.

\n

", "type": "module", "displayName": "`ERR_STREAM_CANNOT_PIPE`" }, { "textRaw": "`ERR_STREAM_DESTROYED`", "name": "`err_stream_destroyed`", "desc": "

A stream method was called that cannot complete because the stream was\ndestroyed using stream.destroy().

\n

", "type": "module", "displayName": "`ERR_STREAM_DESTROYED`" }, { "textRaw": "`ERR_STREAM_NULL_VALUES`", "name": "`err_stream_null_values`", "desc": "

An attempt was made to call stream.write() with a null chunk.

\n

", "type": "module", "displayName": "`ERR_STREAM_NULL_VALUES`" }, { "textRaw": "`ERR_STREAM_PREMATURE_CLOSE`", "name": "`err_stream_premature_close`", "desc": "

An error returned by stream.finished() and stream.pipeline(), when a stream\nor a pipeline ends non gracefully with no explicit error.

\n

", "type": "module", "displayName": "`ERR_STREAM_PREMATURE_CLOSE`" }, { "textRaw": "`ERR_STREAM_PUSH_AFTER_EOF`", "name": "`err_stream_push_after_eof`", "desc": "

An attempt was made to call stream.push() after a null(EOF) had been\npushed to the stream.

\n

", "type": "module", "displayName": "`ERR_STREAM_PUSH_AFTER_EOF`" }, { "textRaw": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`", "name": "`err_stream_unshift_after_end_event`", "desc": "

An attempt was made to call stream.unshift() after the 'end' event was\nemitted.

\n

", "type": "module", "displayName": "`ERR_STREAM_UNSHIFT_AFTER_END_EVENT`" }, { "textRaw": "`ERR_STREAM_WRAP`", "name": "`err_stream_wrap`", "desc": "

Prevents an abort if a string decoder was set on the Socket or if the decoder\nis in objectMode.

\n
const Socket = require('net').Socket;\nconst instance = new Socket();\n\ninstance.setEncoding('utf8');\n
\n

", "type": "module", "displayName": "`ERR_STREAM_WRAP`" }, { "textRaw": "`ERR_STREAM_WRITE_AFTER_END`", "name": "`err_stream_write_after_end`", "desc": "

An attempt was made to call stream.write() after stream.end() has been\ncalled.

\n

", "type": "module", "displayName": "`ERR_STREAM_WRITE_AFTER_END`" }, { "textRaw": "`ERR_STRING_TOO_LONG`", "name": "`err_string_too_long`", "desc": "

An attempt has been made to create a string longer than the maximum allowed\nlength.

\n

", "type": "module", "displayName": "`ERR_STRING_TOO_LONG`" }, { "textRaw": "`ERR_SYNTHETIC`", "name": "`err_synthetic`", "desc": "

An artificial error object used to capture the call stack for diagnostic\nreports.

\n

", "type": "module", "displayName": "`ERR_SYNTHETIC`" }, { "textRaw": "`ERR_SYSTEM_ERROR`", "name": "`err_system_error`", "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.

\n

", "type": "module", "displayName": "`ERR_SYSTEM_ERROR`" }, { "textRaw": "`ERR_TLS_CERT_ALTNAME_INVALID`", "name": "`err_tls_cert_altname_invalid`", "desc": "

While using TLS, the host name/IP of the peer did not match any of the\nsubjectAltNames in its certificate.

\n

", "type": "module", "displayName": "`ERR_TLS_CERT_ALTNAME_INVALID`" }, { "textRaw": "`ERR_TLS_DH_PARAM_SIZE`", "name": "`err_tls_dh_param_size`", "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_TLS_DH_PARAM_SIZE`" }, { "textRaw": "`ERR_TLS_HANDSHAKE_TIMEOUT`", "name": "`err_tls_handshake_timeout`", "desc": "

A TLS/SSL handshake timed out. In this case, the server must also abort the\nconnection.

\n

", "type": "module", "displayName": "`ERR_TLS_HANDSHAKE_TIMEOUT`" }, { "textRaw": "`ERR_TLS_INVALID_CONTEXT`", "name": "`err_tls_invalid_context`", "meta": { "added": [ "v13.3.0" ], "changes": [] }, "desc": "

The context must be a SecureContext.

\n

", "type": "module", "displayName": "`ERR_TLS_INVALID_CONTEXT`" }, { "textRaw": "`ERR_TLS_INVALID_PROTOCOL_METHOD`", "name": "`err_tls_invalid_protocol_method`", "desc": "

The specified secureProtocol method is invalid. It is either unknown, or\ndisabled because it is insecure.

\n

", "type": "module", "displayName": "`ERR_TLS_INVALID_PROTOCOL_METHOD`" }, { "textRaw": "`ERR_TLS_INVALID_PROTOCOL_VERSION`", "name": "`err_tls_invalid_protocol_version`", "desc": "

Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

\n

", "type": "module", "displayName": "`ERR_TLS_INVALID_PROTOCOL_VERSION`" }, { "textRaw": "`ERR_TLS_INVALID_STATE`", "name": "`err_tls_invalid_state`", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "desc": "

The TLS socket must be connected and securily established. Ensure the 'secure'\nevent is emitted before continuing.

\n

", "type": "module", "displayName": "`ERR_TLS_INVALID_STATE`" }, { "textRaw": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`", "name": "`err_tls_protocol_version_conflict`", "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.

\n

", "type": "module", "displayName": "`ERR_TLS_PROTOCOL_VERSION_CONFLICT`" }, { "textRaw": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`", "name": "`err_tls_psk_set_identiy_hint_failed`", "desc": "

Failed to set PSK identity hint. Hint may be too long.

\n

", "type": "module", "displayName": "`ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED`" }, { "textRaw": "`ERR_TLS_RENEGOTIATION_DISABLED`", "name": "`err_tls_renegotiation_disabled`", "desc": "

An attempt was made to renegotiate TLS on a socket instance with TLS disabled.

\n

", "type": "module", "displayName": "`ERR_TLS_RENEGOTIATION_DISABLED`" }, { "textRaw": "`ERR_TLS_REQUIRED_SERVER_NAME`", "name": "`err_tls_required_server_name`", "desc": "

While using TLS, the server.addContext() method was called without providing\na host name in the first parameter.

\n

", "type": "module", "displayName": "`ERR_TLS_REQUIRED_SERVER_NAME`" }, { "textRaw": "`ERR_TLS_SESSION_ATTACK`", "name": "`err_tls_session_attack`", "desc": "

An excessive amount of TLS renegotiations is detected, which is a potential\nvector for denial-of-service attacks.

\n

", "type": "module", "displayName": "`ERR_TLS_SESSION_ATTACK`" }, { "textRaw": "`ERR_TLS_SNI_FROM_SERVER`", "name": "`err_tls_sni_from_server`", "desc": "

An attempt was made to issue Server Name Indication from a TLS server-side\nsocket, which is only valid from a client.

\n

", "type": "module", "displayName": "`ERR_TLS_SNI_FROM_SERVER`" }, { "textRaw": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`", "name": "`err_trace_events_category_required`", "desc": "

The trace_events.createTracing() method requires at least one trace event\ncategory.

\n

", "type": "module", "displayName": "`ERR_TRACE_EVENTS_CATEGORY_REQUIRED`" }, { "textRaw": "`ERR_TRACE_EVENTS_UNAVAILABLE`", "name": "`err_trace_events_unavailable`", "desc": "

The trace_events module could not be loaded because Node.js was compiled with\nthe --without-v8-platform flag.

\n

", "type": "module", "displayName": "`ERR_TRACE_EVENTS_UNAVAILABLE`" }, { "textRaw": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`", "name": "`err_transform_already_transforming`", "desc": "

A Transform stream finished while it was still transforming.

\n

", "type": "module", "displayName": "`ERR_TRANSFORM_ALREADY_TRANSFORMING`" }, { "textRaw": "`ERR_TRANSFORM_WITH_LENGTH_0`", "name": "`err_transform_with_length_0`", "desc": "

A Transform stream finished with data still in the write buffer.

\n

", "type": "module", "displayName": "`ERR_TRANSFORM_WITH_LENGTH_0`" }, { "textRaw": "`ERR_TTY_INIT_FAILED`", "name": "`err_tty_init_failed`", "desc": "

The initialization of a TTY failed due to a system error.

\n

", "type": "module", "displayName": "`ERR_TTY_INIT_FAILED`" }, { "textRaw": "`ERR_UNAVAILABLE_DURING_EXIT`", "name": "`err_unavailable_during_exit`", "desc": "

Function was called within a process.on('exit') handler that shouldn't be\ncalled within process.on('exit') handler.

\n

", "type": "module", "displayName": "`ERR_UNAVAILABLE_DURING_EXIT`" }, { "textRaw": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`", "name": "`err_uncaught_exception_capture_already_set`", "desc": "

process.setUncaughtExceptionCaptureCallback() was called twice,\nwithout first resetting the callback to null.

\n

This error is designed to prevent accidentally overwriting a callback registered\nfrom another module.

\n

", "type": "module", "displayName": "`ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET`" }, { "textRaw": "`ERR_UNESCAPED_CHARACTERS`", "name": "`err_unescaped_characters`", "desc": "

A string that contained unescaped characters was received.

\n

", "type": "module", "displayName": "`ERR_UNESCAPED_CHARACTERS`" }, { "textRaw": "`ERR_UNHANDLED_ERROR`", "name": "`err_unhandled_error`", "desc": "

An unhandled error occurred (for instance, when an 'error' event is emitted\nby an EventEmitter but an 'error' handler is not registered).

\n

", "type": "module", "displayName": "`ERR_UNHANDLED_ERROR`" }, { "textRaw": "`ERR_UNKNOWN_BUILTIN_MODULE`", "name": "`err_unknown_builtin_module`", "desc": "

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

", "type": "module", "displayName": "`ERR_UNKNOWN_BUILTIN_MODULE`" }, { "textRaw": "`ERR_UNKNOWN_CREDENTIAL`", "name": "`err_unknown_credential`", "desc": "

A Unix group or user identifier that does not exist was passed.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_CREDENTIAL`" }, { "textRaw": "`ERR_UNKNOWN_ENCODING`", "name": "`err_unknown_encoding`", "desc": "

An invalid or unknown encoding option was passed to an API.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_ENCODING`" }, { "textRaw": "`ERR_UNKNOWN_FILE_EXTENSION`", "name": "`err_unknown_file_extension`", "stability": 1, "stabilityText": "Experimental", "desc": "

An attempt was made to load a module with an unknown or unsupported file\nextension.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_FILE_EXTENSION`" }, { "textRaw": "`ERR_UNKNOWN_MODULE_FORMAT`", "name": "`err_unknown_module_format`", "stability": 1, "stabilityText": "Experimental", "desc": "

An attempt was made to load a module with an unknown or unsupported format.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_MODULE_FORMAT`" }, { "textRaw": "`ERR_UNKNOWN_SIGNAL`", "name": "`err_unknown_signal`", "desc": "

An invalid or unknown process signal was passed to an API expecting a valid\nsignal (such as subprocess.kill()).

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_SIGNAL`" }, { "textRaw": "`ERR_UNSUPPORTED_DIR_IMPORT`", "name": "`err_unsupported_dir_import`", "desc": "

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.

\n\n
import './'; // unsupported\nimport './index.js'; // supported\nimport 'package-name'; // supported\n
\n

", "type": "module", "displayName": "`ERR_UNSUPPORTED_DIR_IMPORT`" }, { "textRaw": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`", "name": "`err_unsupported_esm_url_scheme`", "desc": "

import with URL schemes other than file and data is unsupported.

\n

", "type": "module", "displayName": "`ERR_UNSUPPORTED_ESM_URL_SCHEME`" }, { "textRaw": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`", "name": "`err_valid_performance_entry_type`", "desc": "

While using the Performance Timing API (perf_hooks), no valid performance\nentry types are found.

\n

", "type": "module", "displayName": "`ERR_VALID_PERFORMANCE_ENTRY_TYPE`" }, { "textRaw": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`", "name": "`err_vm_dynamic_import_callback_missing`", "desc": "

A dynamic import callback was not specified.

\n

", "type": "module", "displayName": "`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`" }, { "textRaw": "`ERR_VM_MODULE_ALREADY_LINKED`", "name": "`err_vm_module_already_linked`", "desc": "

The module attempted to be linked is not eligible for linking, because of one of\nthe following reasons:

\n
    \n
  • It has already been linked (linkingStatus is 'linked')
  • \n
  • It is being linked (linkingStatus is 'linking')
  • \n
  • Linking has failed for this module (linkingStatus is 'errored')
  • \n
\n

", "type": "module", "displayName": "`ERR_VM_MODULE_ALREADY_LINKED`" }, { "textRaw": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`", "name": "`err_vm_module_cached_data_rejected`", "desc": "

The cachedData option passed to a module constructor is invalid.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_CACHED_DATA_REJECTED`" }, { "textRaw": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`", "name": "`err_vm_module_cannot_create_cached_data`", "desc": "

Cached data cannot be created for modules which have already been evaluated.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA`" }, { "textRaw": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`", "name": "`err_vm_module_different_context`", "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

", "type": "module", "displayName": "`ERR_VM_MODULE_DIFFERENT_CONTEXT`" }, { "textRaw": "`ERR_VM_MODULE_LINKING_ERRORED`", "name": "`err_vm_module_linking_errored`", "desc": "

The linker function returned a module for which linking has failed.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_LINKING_ERRORED`" }, { "textRaw": "`ERR_VM_MODULE_LINK_FAILURE`", "name": "`err_vm_module_link_failure`", "desc": "

The module was unable to be linked due to a failure.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_LINK_FAILURE`" }, { "textRaw": "`ERR_VM_MODULE_NOT_MODULE`", "name": "`err_vm_module_not_module`", "desc": "

The fulfilled value of a linking promise is not a vm.Module object.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_NOT_MODULE`" }, { "textRaw": "`ERR_VM_MODULE_STATUS`", "name": "`err_vm_module_status`", "desc": "

The current module's status does not allow for this operation. The specific\nmeaning of the error depends on the specific function.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_STATUS`" }, { "textRaw": "`ERR_WASI_ALREADY_STARTED`", "name": "`err_wasi_already_started`", "desc": "

The WASI instance has already started.

\n

", "type": "module", "displayName": "`ERR_WASI_ALREADY_STARTED`" }, { "textRaw": "`ERR_WASI_NOT_STARTED`", "name": "`err_wasi_not_started`", "desc": "

The WASI instance has not been started.

\n

", "type": "module", "displayName": "`ERR_WASI_NOT_STARTED`" }, { "textRaw": "`ERR_WORKER_INIT_FAILED`", "name": "`err_worker_init_failed`", "desc": "

The Worker initialization failed.

\n

", "type": "module", "displayName": "`ERR_WORKER_INIT_FAILED`" }, { "textRaw": "`ERR_WORKER_INVALID_EXEC_ARGV`", "name": "`err_worker_invalid_exec_argv`", "desc": "

The execArgv option passed to the Worker constructor contains\ninvalid flags.

\n

", "type": "module", "displayName": "`ERR_WORKER_INVALID_EXEC_ARGV`" }, { "textRaw": "`ERR_WORKER_NOT_RUNNING`", "name": "`err_worker_not_running`", "desc": "

An operation failed because the Worker instance is not currently running.

\n

", "type": "module", "displayName": "`ERR_WORKER_NOT_RUNNING`" }, { "textRaw": "`ERR_WORKER_OUT_OF_MEMORY`", "name": "`err_worker_out_of_memory`", "desc": "

The Worker instance terminated because it reached its memory limit.

\n

", "type": "module", "displayName": "`ERR_WORKER_OUT_OF_MEMORY`" }, { "textRaw": "`ERR_WORKER_PATH`", "name": "`err_worker_path`", "desc": "

The path for the main script of a worker is neither an absolute path\nnor a relative path starting with ./ or ../.

\n

", "type": "module", "displayName": "`ERR_WORKER_PATH`" }, { "textRaw": "`ERR_WORKER_UNSERIALIZABLE_ERROR`", "name": "`err_worker_unserializable_error`", "desc": "

All attempts at serializing an uncaught exception from a worker thread failed.

\n

", "type": "module", "displayName": "`ERR_WORKER_UNSERIALIZABLE_ERROR`" }, { "textRaw": "`ERR_WORKER_UNSUPPORTED_EXTENSION`", "name": "`err_worker_unsupported_extension`", "desc": "

The pathname used for the main script of a worker has an\nunknown file extension.

\n

", "type": "module", "displayName": "`ERR_WORKER_UNSUPPORTED_EXTENSION`" }, { "textRaw": "`ERR_WORKER_UNSUPPORTED_OPERATION`", "name": "`err_worker_unsupported_operation`", "desc": "

The requested functionality is not supported in worker threads.

\n

", "type": "module", "displayName": "`ERR_WORKER_UNSUPPORTED_OPERATION`" }, { "textRaw": "`ERR_ZLIB_INITIALIZATION_FAILED`", "name": "`err_zlib_initialization_failed`", "desc": "

Creation of a zlib object failed due to incorrect configuration.

\n

", "type": "module", "displayName": "`ERR_ZLIB_INITIALIZATION_FAILED`" }, { "textRaw": "`HPE_HEADER_OVERFLOW`", "name": "`hpe_header_overflow`", "meta": { "changes": [ { "version": [ "v11.4.0", "v10.15.0" ], "commit": "186035243fad247e3955f", "pr-url": "https://github.com/nodejs-private/node-private/pull/143", "description": "Max header size in `http_parser` was set to 8 KB." } ] }, "desc": "

Too much HTTP header data was received. In order to protect against malicious or\nmalconfigured clients, if more than 8 KB 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.

\n

", "type": "module", "displayName": "`HPE_HEADER_OVERFLOW`" }, { "textRaw": "`HPE_UNEXPECTED_CONTENT_LENGTH`", "name": "`hpe_unexpected_content_length`", "desc": "

Server is sending both a Content-Length header and Transfer-Encoding: chunked.

\n

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.

\n

Use Content-Length or Transfer-Encoding: chunked.

\n

", "type": "module", "displayName": "`HPE_UNEXPECTED_CONTENT_LENGTH`" }, { "textRaw": "`MODULE_NOT_FOUND`", "name": "`module_not_found`", "meta": { "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25690", "description": "Added `requireStack` property." } ] }, "desc": "

A module file could not be resolved while attempting a require() or\nimport operation.

", "type": "module", "displayName": "`MODULE_NOT_FOUND`" } ], "type": "misc", "displayName": "Node.js error codes" }, { "textRaw": "Legacy Node.js error codes", "name": "legacy_node.js_error_codes", "stability": 0, "stabilityText": "Deprecated. These error codes are either inconsistent, or have\nbeen removed.", "desc": "

", "modules": [ { "textRaw": "`ERR_CANNOT_TRANSFER_OBJECT`", "name": "`err_cannot_transfer_object`", "desc": "\n

The value passed to postMessage() contained an object that is not supported\nfor transferring.

\n

", "type": "module", "displayName": "`ERR_CANNOT_TRANSFER_OBJECT`" }, { "textRaw": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`", "name": "`err_crypto_hash_digest_no_utf16`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v12.12.0" ], "changes": [] }, "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_CRYPTO_HASH_DIGEST_NO_UTF16`" }, { "textRaw": "`ERR_HTTP2_FRAME_ERROR`", "name": "`err_http2_frame_error`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when a failure occurs sending an individual frame on the HTTP/2\nsession.

\n

", "type": "module", "displayName": "`ERR_HTTP2_FRAME_ERROR`" }, { "textRaw": "`ERR_HTTP2_HEADERS_OBJECT`", "name": "`err_http2_headers_object`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when an HTTP/2 Headers Object is expected.

\n

", "type": "module", "displayName": "`ERR_HTTP2_HEADERS_OBJECT`" }, { "textRaw": "`ERR_HTTP2_HEADER_REQUIRED`", "name": "`err_http2_header_required`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when a required header is missing in an HTTP/2 message.

\n

", "type": "module", "displayName": "`ERR_HTTP2_HEADER_REQUIRED`" }, { "textRaw": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`", "name": "`err_http2_info_headers_after_respond`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

HTTP/2 informational headers must only be sent prior to calling the\nHttp2Stream.prototype.respond() method.

\n

", "type": "module", "displayName": "`ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`" }, { "textRaw": "`ERR_HTTP2_STREAM_CLOSED`", "name": "`err_http2_stream_closed`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when an action has been performed on an HTTP/2 Stream that has already\nbeen closed.

\n

", "type": "module", "displayName": "`ERR_HTTP2_STREAM_CLOSED`" }, { "textRaw": "`ERR_HTTP_INVALID_CHAR`", "name": "`err_http_invalid_char`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when an invalid character is found in an HTTP response status message\n(reason phrase).

\n

", "type": "module", "displayName": "`ERR_HTTP_INVALID_CHAR`" }, { "textRaw": "`ERR_INDEX_OUT_OF_RANGE`", "name": "`err_index_out_of_range`", "meta": { "added": [ "v10.0.0" ], "removed": [ "v11.0.0" ], "changes": [] }, "desc": "

A given index was out of the accepted range (e.g. negative offsets).

\n

", "type": "module", "displayName": "`ERR_INDEX_OUT_OF_RANGE`" }, { "textRaw": "`ERR_INVALID_OPT_VALUE`", "name": "`err_invalid_opt_value`", "meta": { "added": [ "v8.0.0" ], "removed": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid or unexpected value was passed in an options object.

\n

", "type": "module", "displayName": "`ERR_INVALID_OPT_VALUE`" }, { "textRaw": "`ERR_INVALID_OPT_VALUE_ENCODING`", "name": "`err_invalid_opt_value_encoding`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v15.0.0" ], "changes": [] }, "desc": "

An invalid or unknown file encoding was passed.

\n

", "type": "module", "displayName": "`ERR_INVALID_OPT_VALUE_ENCODING`" }, { "textRaw": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`", "name": "`err_missing_message_port_in_transfer_list`", "meta": { "removed": [ "v15.0.0" ], "changes": [] }, "desc": "

This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST\nin Node.js v15.0.0, because it is no longer accurate as other types of\ntransferable objects also exist now.

\n

", "type": "module", "displayName": "`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`" }, { "textRaw": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`", "name": "`err_napi_cons_prototype_object`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used by the Node-API when Constructor.prototype is not an object.

\n

", "type": "module", "displayName": "`ERR_NAPI_CONS_PROTOTYPE_OBJECT`" }, { "textRaw": "`ERR_NO_LONGER_SUPPORTED`", "name": "`err_no_longer_supported`", "desc": "

A Node.js API was called in an unsupported manner, such as\nBuffer.write(string, encoding, offset[, length]).

\n

", "type": "module", "displayName": "`ERR_NO_LONGER_SUPPORTED`" }, { "textRaw": "`ERR_OPERATION_FAILED`", "name": "`err_operation_failed`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An operation failed. This is typically used to signal the general failure\nof an asynchronous operation.

\n

", "type": "module", "displayName": "`ERR_OPERATION_FAILED`" }, { "textRaw": "`ERR_OUTOFMEMORY`", "name": "`err_outofmemory`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used generically to identify that an operation caused an out of memory\ncondition.

\n

", "type": "module", "displayName": "`ERR_OUTOFMEMORY`" }, { "textRaw": "`ERR_PARSE_HISTORY_DATA`", "name": "`err_parse_history_data`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

The repl module was unable to parse data from the REPL history file.

\n

", "type": "module", "displayName": "`ERR_PARSE_HISTORY_DATA`" }, { "textRaw": "`ERR_SOCKET_CANNOT_SEND`", "name": "`err_socket_cannot_send`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v14.0.0" ], "changes": [] }, "desc": "

Data could not be sent on a socket.

\n

", "type": "module", "displayName": "`ERR_SOCKET_CANNOT_SEND`" }, { "textRaw": "`ERR_STDERR_CLOSE`", "name": "`err_stderr_close`", "meta": { "removed": [ "v10.12.0" ], "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." } ] }, "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.

\n

", "type": "module", "displayName": "`ERR_STDERR_CLOSE`" }, { "textRaw": "`ERR_STDOUT_CLOSE`", "name": "`err_stdout_close`", "meta": { "removed": [ "v10.12.0" ], "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." } ] }, "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_STDOUT_CLOSE`" }, { "textRaw": "`ERR_STREAM_READ_NOT_IMPLEMENTED`", "name": "`err_stream_read_not_implemented`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when an attempt is made to use a readable stream that has not implemented\nreadable._read().

\n

", "type": "module", "displayName": "`ERR_STREAM_READ_NOT_IMPLEMENTED`" }, { "textRaw": "`ERR_TLS_RENEGOTIATION_FAILED`", "name": "`err_tls_renegotiation_failed`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when a TLS renegotiation request has failed in a non-specific way.

\n

", "type": "module", "displayName": "`ERR_TLS_RENEGOTIATION_FAILED`" }, { "textRaw": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`", "name": "`err_transferring_externalized_sharedarraybuffer`", "meta": { "added": [ "v10.5.0" ], "removed": [ "v14.0.0" ], "changes": [] }, "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.

\n

This can only happen when native addons create SharedArrayBuffers in\n\"externalized\" mode, or put existing SharedArrayBuffer into externalized mode.

\n

", "type": "module", "displayName": "`ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`" }, { "textRaw": "`ERR_UNKNOWN_STDIN_TYPE`", "name": "`err_unknown_stdin_type`", "meta": { "added": [ "v8.0.0" ], "removed": [ "v11.7.0" ], "changes": [] }, "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_STDIN_TYPE`" }, { "textRaw": "`ERR_UNKNOWN_STREAM_TYPE`", "name": "`err_unknown_stream_type`", "meta": { "added": [ "v8.0.0" ], "removed": [ "v11.7.0" ], "changes": [] }, "desc": "

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.

\n

", "type": "module", "displayName": "`ERR_UNKNOWN_STREAM_TYPE`" }, { "textRaw": "`ERR_V8BREAKITERATOR`", "name": "`err_v8breakiterator`", "desc": "

The V8 BreakIterator API was used but the full ICU data set is not installed.

\n

", "type": "module", "displayName": "`ERR_V8BREAKITERATOR`" }, { "textRaw": "`ERR_VALUE_OUT_OF_RANGE`", "name": "`err_value_out_of_range`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when a given value is out of the accepted range.

\n

", "type": "module", "displayName": "`ERR_VALUE_OUT_OF_RANGE`" }, { "textRaw": "`ERR_VM_MODULE_NOT_LINKED`", "name": "`err_vm_module_not_linked`", "desc": "

The module must be successfully linked before instantiation.

\n

", "type": "module", "displayName": "`ERR_VM_MODULE_NOT_LINKED`" }, { "textRaw": "`ERR_ZLIB_BINDING_CLOSED`", "name": "`err_zlib_binding_closed`", "meta": { "added": [ "v9.0.0" ], "removed": [ "v10.0.0" ], "changes": [] }, "desc": "

Used when an attempt is made to use a zlib object after it has already been\nclosed.

\n

", "type": "module", "displayName": "`ERR_ZLIB_BINDING_CLOSED`" }, { "textRaw": "`ERR_CPU_USAGE`", "name": "`err_cpu_usage`", "meta": { "removed": [ "v15.0.0" ], "changes": [] }, "desc": "

The native call from process.cpuUsage could not be processed.

", "type": "module", "displayName": "`ERR_CPU_USAGE`" } ], "type": "misc", "displayName": "Legacy Node.js error codes" } ], "classes": [ { "textRaw": "Class: `Error`", "type": "class", "name": "Error", "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.

\n

All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

", "methods": [ { "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", "type": "method", "name": "captureStackTrace", "signatures": [ { "params": [ { "textRaw": "`targetObject` {Object}", "name": "targetObject", "type": "Object" }, { "textRaw": "`constructorOpt` {Function}", "name": "constructorOpt", "type": "Function" } ] } ], "desc": "

Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
\n

The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

\n

The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

\n
function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
" } ], "properties": [ { "textRaw": "`stackTraceLimit` {number}", "type": "number", "name": "stackTraceLimit", "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)).

\n

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.

\n

If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

" }, { "textRaw": "`code` {string}", "type": "string", "name": "code", "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.

" }, { "textRaw": "`message` {string}", "type": "string", "name": "message", "desc": "

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).

\n
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
" }, { "textRaw": "`stack` {string}", "type": "string", "name": "stack", "desc": "

The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

\n
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
\n

The 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.

\n

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:

\n
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
\n

The location information will be one of:

\n
    \n
  • native, if the frame represents a call internal to V8 (as in [].forEach).
  • \n
  • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
  • \n
  • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
  • \n
\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

\n

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.

" } ], "signatures": [ { "params": [ { "textRaw": "`message` {string}", "name": "message", "type": "string" } ], "desc": "

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 message.toString(). 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.

" } ] }, { "textRaw": "Class: `AssertionError`", "type": "class", "name": "AssertionError", "desc": "\n

Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

" }, { "textRaw": "Class: `RangeError`", "type": "class", "name": "RangeError", "desc": "\n

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.

\n
require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

" }, { "textRaw": "Class: `ReferenceError`", "type": "class", "name": "ReferenceError", "desc": "\n

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.

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.

\n
doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
\n

Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

" }, { "textRaw": "Class: `SyntaxError`", "type": "class", "name": "SyntaxError", "desc": "\n

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.

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

" }, { "textRaw": "Class: `SystemError`", "type": "class", "name": "SystemError", "desc": "\n

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.

\n
    \n
  • address <string> If present, the address to which a network connection\nfailed
  • \n
  • code <string> The string error code
  • \n
  • dest <string> If present, the file path destination when reporting a file\nsystem error
  • \n
  • errno <number> The system-provided error number
  • \n
  • info <Object> If present, extra details about the error condition
  • \n
  • message <string> A system-provided human-readable description of the error
  • \n
  • path <string> If present, the file path when reporting a file system error
  • \n
  • port <number> If present, the network connection port that is not available
  • \n
  • syscall <string> The name of the system call that triggered the error
  • \n
", "properties": [ { "textRaw": "`address` {string}", "type": "string", "name": "address", "desc": "

If present, error.address is a string describing the address to which a\nnetwork connection failed.

" }, { "textRaw": "`code` {string}", "type": "string", "name": "code", "desc": "

The error.code property is a string representing the error code.

" }, { "textRaw": "`dest` {string}", "type": "string", "name": "dest", "desc": "

If present, error.dest is the file path destination when reporting a file\nsystem error.

" }, { "textRaw": "`errno` {number}", "type": "number", "name": "errno", "desc": "

The error.errno property is a negative number which corresponds\nto the error code defined in libuv Error handling.

\n

On Windows the error number provided by the system will be normalized by libuv.

\n

To get the string representation of the error code, use\nutil.getSystemErrorName(error.errno).

" }, { "textRaw": "`info` {Object}", "type": "Object", "name": "info", "desc": "

If present, error.info is an object with details about the error condition.

" }, { "textRaw": "`message` {string}", "type": "string", "name": "message", "desc": "

error.message is a system-provided human-readable description of the error.

" }, { "textRaw": "`path` {string}", "type": "string", "name": "path", "desc": "

If present, error.path is a string containing a relevant invalid pathname.

" }, { "textRaw": "`port` {number}", "type": "number", "name": "port", "desc": "

If present, error.port is the network connection port that is not available.

" }, { "textRaw": "`syscall` {string}", "type": "string", "name": "syscall", "desc": "

The error.syscall property is a string describing the syscall that failed.

" } ], "modules": [ { "textRaw": "Common system errors", "name": "common_system_errors", "desc": "

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.

\n
    \n
  • \n

    EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

    \n
  • \n
  • \n

    EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

    \n
  • \n
  • \n

    ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

    \n
  • \n
  • \n

    ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

    \n
  • \n
  • \n

    EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
", "type": "module", "displayName": "Common system errors" } ] }, { "textRaw": "Class: `TypeError`", "type": "class", "name": "TypeError", "desc": "\n

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.

\n
require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

" } ], "source": "doc/api/errors.md" }, { "textRaw": "Global objects", "name": "Global objects", "introduced_in": "v0.10.0", "type": "misc", "desc": "

These objects are available in all modules. The following variables may appear\nto be global but are not. They exist only in the scope of modules, see the\nmodule system documentation:

\n\n

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.

", "globals": [ { "textRaw": "Class: `AbortController`", "type": "global", "name": "AbortController", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "desc": "

A utility class used to signal cancelation in selected Promise-based APIs.\nThe API is based on the Web API AbortController.

\n
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()`", "type": "method", "name": "abort", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Triggers the abort signal, causing the abortController.signal to emit\nthe 'abort' event.

" } ], "properties": [ { "textRaw": "`signal` Type: {AbortSignal}", "type": "AbortSignal", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] } } ], "classes": [ { "textRaw": "Class: `AbortSignal`", "type": "class", "name": "AbortSignal", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "\n

The AbortSignal is used to notify observers when the\nabortController.abort() method is called.

", "classMethods": [ { "textRaw": "Static method: `AbortSignal.abort()`", "type": "classMethod", "name": "abort", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AbortSignal}", "name": "return", "type": "AbortSignal" }, "params": [] } ], "desc": "

Returns a new already aborted AbortSignal.

" } ], "events": [ { "textRaw": "Event: `'abort'`", "type": "event", "name": "abort", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "params": [], "desc": "

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':

\n
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
\n

The 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.

\n

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.

" } ], "properties": [ { "textRaw": "`aborted` Type: {boolean} True after the `AbortController` has been aborted.", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "True after the `AbortController` has been aborted." }, { "textRaw": "`onabort` Type: {Function}", "type": "Function", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An optional callback function that may be set by user code to be notified\nwhen the abortController.abort() function has been called.

" } ] } ] }, { "textRaw": "Class: `Buffer`", "type": "global", "name": "Buffer", "meta": { "added": [ "v0.1.103" ], "changes": [] }, "desc": "\n

Used to handle binary data. See the buffer section.

" }, { "textRaw": "`clearImmediate(immediateObject)`", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "desc": "

clearImmediate is described in the timers section.

" }, { "textRaw": "`clearInterval(intervalObject)`", "type": "global", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

clearInterval is described in the timers section.

" }, { "textRaw": "`clearTimeout(timeoutObject)`", "type": "global", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

clearTimeout is described in the timers section.

" }, { "textRaw": "`console`", "name": "`console`", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "type": "global", "desc": "\n

Used to print to stdout and stderr. See the console section.

" }, { "textRaw": "`Event`", "name": "`Event`", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "type": "global", "desc": "

A browser-compatible implementation of the Event class. See\nEventTarget and Event API for more details.

" }, { "textRaw": "`EventTarget`", "name": "`EventTarget`", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "type": "global", "desc": "

A browser-compatible implementation of the EventTarget class. See\nEventTarget and Event API for more details.

" }, { "textRaw": "`global`", "name": "`global`", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "type": "global", "desc": "
    \n
  • <Object> The global namespace object.
  • \n
\n

In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

" }, { "textRaw": "`MessageChannel`", "name": "`MessageChannel`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessageChannel class. See MessageChannel for more details.

" }, { "textRaw": "`MessageEvent`", "name": "`MessageEvent`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessageEvent class. See MessageEvent for more details.

" }, { "textRaw": "`MessagePort`", "name": "`MessagePort`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessagePort class. See MessagePort for more details.

" }, { "textRaw": "`process`", "name": "`process`", "meta": { "added": [ "v0.1.7" ], "changes": [] }, "type": "global", "desc": "\n

The process object. See the process object section.

" }, { "textRaw": "`queueMicrotask(callback)`", "type": "global", "name": "queueMicrotask", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "desc": "\n

The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

\n

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.

\n
// 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": "`setImmediate(callback[, ...args])`", "type": "global", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "desc": "

setImmediate is described in the timers section.

" }, { "textRaw": "`setInterval(callback, delay[, ...args])`", "type": "global", "name": "setInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

setInterval is described in the timers section.

" }, { "textRaw": "`setTimeout(callback, delay[, ...args])`", "type": "global", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

setTimeout is described in the timers section.

" }, { "textRaw": "`TextDecoder`", "name": "`TextDecoder`", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG TextDecoder class. See the TextDecoder section.

" }, { "textRaw": "`TextEncoder`", "name": "`TextEncoder`", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG TextEncoder class. See the TextEncoder section.

" }, { "textRaw": "`URL`", "name": "`URL`", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG URL class. See the URL section.

" }, { "textRaw": "`URLSearchParams`", "name": "`URLSearchParams`", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG URLSearchParams class. See the URLSearchParams section.

" }, { "textRaw": "`WebAssembly`", "name": "`WebAssembly`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "type": "global", "desc": "\n

The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

" } ], "miscs": [ { "textRaw": "`__dirname`", "name": "`__dirname`", "desc": "

This variable may appear to be global but is not. See __dirname.

", "type": "misc", "displayName": "`__dirname`" }, { "textRaw": "`__filename`", "name": "`__filename`", "desc": "

This variable may appear to be global but is not. See __filename.

", "type": "misc", "displayName": "`__filename`" }, { "textRaw": "`exports`", "name": "`exports`", "desc": "

This variable may appear to be global but is not. See exports.

", "type": "misc", "displayName": "`exports`" }, { "textRaw": "`module`", "name": "`module`", "desc": "

This variable may appear to be global but is not. See module.

", "type": "misc", "displayName": "`module`" }, { "textRaw": "`performance`", "name": "`performance`", "desc": "

The perf_hooks.performance object.

", "type": "misc", "displayName": "`performance`" } ], "methods": [ { "textRaw": "`atob(data)`", "type": "method", "name": "atob", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use `Buffer.from(data, 'base64')` instead.", "signatures": [ { "params": [] } ], "desc": "

Global alias for buffer.atob().

" }, { "textRaw": "`btoa(data)`", "type": "method", "name": "btoa", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use `buf.toString('base64')` instead.", "signatures": [ { "params": [] } ], "desc": "

Global alias for buffer.btoa().

" }, { "textRaw": "`require()`", "type": "method", "name": "require", "signatures": [ { "params": [] } ], "desc": "

This variable may appear to be global but is not. See require().

" } ], "source": "doc/api/globals.md" }, { "textRaw": "Internationalization support", "name": "Internationalization support", "introduced_in": "v8.2.0", "type": "misc", "desc": "

Node.js has many features that make it easier to write internationalized\nprograms. Some of them are:

\n\n

Node.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", "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.

\n
    \n
  • --with-intl=none/--without-intl
  • \n
  • --with-intl=system-icu
  • \n
  • --with-intl=small-icu
  • \n
  • --with-intl=full-icu (default)
  • \n
\n

An overview of available Node.js and JavaScript features for each configure\noption:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Featurenonesystem-icusmall-icufull-icu
String.prototype.normalize()none (function is no-op)fullfullfull
String.prototype.to*Case()fullfullfullfull
Intlnone (object does not exist)partial/full (depends on OS)partial (English-only)full
String.prototype.localeCompare()partial (not locale-aware)fullfullfull
String.prototype.toLocale*Case()partial (not locale-aware)fullfullfull
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 Parserpartial (no IDN support)fullfullfull
WHATWG URL Parserpartial (no IDN support)fullfullfull
require('buffer').transcode()none (function does not exist)fullfullfull
REPLpartial (inaccurate line editing)fullfullfull
require('util').TextDecoderpartial (basic encodings support)partial/full (depends on OS)partial (Unicode-only)full
RegExp Unicode Property Escapesnone (invalid RegExp error)fullfullfull
\n

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().

", "modules": [ { "textRaw": "Disable all internationalization features (`none`)", "name": "disable_all_internationalization_features_(`none`)", "desc": "

If this option is chosen, ICU is disabled and most internationalization\nfeatures mentioned above will be unavailable in the resulting node binary.

", "type": "module", "displayName": "Disable all internationalization features (`none`)" }, { "textRaw": "Build with a pre-installed ICU (`system-icu`)", "name": "build_with_a_pre-installed_icu_(`system-icu`)", "desc": "

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.

\n

Functionalities 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.

", "type": "module", "displayName": "Build with a pre-installed ICU (`system-icu`)" }, { "textRaw": "Embed a limited set of ICU data (`small-icu`)", "name": "embed_a_limited_set_of_icu_data_(`small-icu`)", "desc": "

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.

\n

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:

\n
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 \"M01\" on small-icu\n// Should print \"enero\"\n
\n

This mode provides a balance between features and binary size.

", "modules": [ { "textRaw": "Providing ICU data at runtime", "name": "providing_icu_data_at_runtime", "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 /some/directory, it can be made available to ICU\nthrough either:

\n
    \n
  • \n

    The NODE_ICU_DATA environment variable:

    \n
    env NODE_ICU_DATA=/some/directory node\n
    \n
  • \n
  • \n

    The --icu-data-dir CLI parameter:

    \n
    node --icu-data-dir=/some/directory\n
    \n
  • \n
\n

(If both are specified, the --icu-data-dir CLI parameter takes precedence.)

\n

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 icudt6X[bl].dat, where 6X denotes\nthe intended ICU version, and b or l indicates the system's endianness.\nCheck \"ICU Data\" article in the ICU User Guide for other supported formats\nand more details on ICU data in general.

\n

The 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.

", "type": "module", "displayName": "Providing ICU data at runtime" } ], "type": "module", "displayName": "Embed a limited set of ICU data (`small-icu`)" }, { "textRaw": "Embed the entire ICU (`full-icu`)", "name": "embed_the_entire_icu_(`full-icu`)", "desc": "

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.

", "type": "module", "displayName": "Embed the entire ICU (`full-icu`)" } ], "type": "misc", "displayName": "Options for building Node.js" }, { "textRaw": "Detecting internationalization support", "name": "detecting_internationalization_support", "desc": "

To verify that ICU is enabled at all (system-icu, small-icu, or\nfull-icu), simply checking the existence of Intl should suffice:

\n
const hasICU = typeof Intl === 'object';\n
\n

Alternatively, checking for process.versions.icu, a property defined only\nwhen ICU is enabled, works too:

\n
const hasICU = typeof process.versions.icu === 'string';\n
\n

To check for support for a non-English locale (i.e. full-icu or\nsystem-icu), Intl.DateTimeFormat can be a good distinguishing factor:

\n
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
\n

For more verbose tests for Intl support, the following resources may be found\nto be helpful:

\n
    \n
  • btest402: Generally used to check whether Node.js with Intl support is\nbuilt correctly.
  • \n
  • Test262: ECMAScript's official conformance test suite includes a section\ndedicated to ECMA-402.
  • \n
", "type": "misc", "displayName": "Detecting internationalization support" } ], "source": "doc/api/intl.md" }, { "textRaw": "Modules: ECMAScript modules", "name": "Modules: ECMAScript modules", "introduced_in": "v8.5.0", "type": "misc", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": [ "v15.3.0", "v12.22.0" ], "pr-url": "https://github.com/nodejs/node/pull/35781", "description": "Stabilize modules implementation." }, { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/35249", "description": "Support for detection of CommonJS named exports." }, { "version": "v14.8.0", "pr-url": "https://github.com/nodejs/node/pull/34558", "description": "Unflag Top-Level Await." }, { "version": [ "v14.0.0", "v13.14.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/31974", "description": "Remove experimental modules warning." }, { "version": [ "v13.2.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29866", "description": "Loading ECMAScript modules no longer requires a command-line flag." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "stability": 2, "stabilityText": "Stable", "miscs": [ { "textRaw": "Introduction", "name": "esm", "desc": "

ECMAScript modules are the official standard format to package JavaScript\ncode for reuse. Modules are defined using a variety of import and\nexport statements.

\n

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
\n

The following example of an ES module imports the function from addTwo.mjs:

\n
// app.mjs\nimport { addTwo } from './addTwo.mjs';\n\n// Prints: 6\nconsole.log(addTwo(4));\n
\n

Node.js fully supports ECMAScript modules as they are currently specified and\nprovides interoperability between them and its original module format,\nCommonJS.

\n\n

\n\n

", "type": "misc", "displayName": "esm" }, { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "

Node.js treats JavaScript code as CommonJS modules by default.\nAuthors can tell Node.js to treat JavaScript code as ECMAScript modules\nvia the .mjs file extension, the package.json \"type\" field, or the\n--input-type flag. See\nModules: Packages for more\ndetails.

\n\n

\n\n\n\n\n\n\n\n\n\n\n\n\n

" }, { "textRaw": "Packages", "name": "packages", "desc": "

This section was moved to Modules: Packages.

", "type": "misc", "displayName": "Packages" }, { "textRaw": "`import` Specifiers", "name": "`import`_specifiers", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "

The specifier of an import statement is the string after the from keyword,\ne.g. 'path' in import { sep } from 'path'. Specifiers are also used in\nexport from statements, and as the argument to an import() expression.

\n

There are three types of specifiers:

\n
    \n
  • \n

    Relative 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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    Absolute specifiers like 'file:///opt/nodejs/config.js'. They refer\ndirectly and explicitly to a full path.

    \n
  • \n
\n

Bare specifier resolutions are handled by the Node.js module resolution\nalgorithm. All other specifier resolutions are always only resolved with\nthe standard relative URL resolution semantics.

\n

Like 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\".

\n

For details on these package resolution rules that apply to bare specifiers in\nthe Node.js module resolution, see the packages documentation.

", "type": "module", "displayName": "Terminology" }, { "textRaw": "Mandatory file extensions", "name": "mandatory_file_extensions", "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.

\n

This behavior matches how import behaves in browser environments, assuming a\ntypically configured server.

", "type": "module", "displayName": "Mandatory file extensions" }, { "textRaw": "URLs", "name": "urls", "desc": "

ES modules are resolved and cached as URLs. This means that files containing\nspecial characters such as # and ? need to be escaped.

\n

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": [ { "textRaw": "`file:` URLs", "name": "`file:`_urls", "desc": "

Modules are loaded multiple times if the import specifier used to resolve\nthem has a different query or fragment.

\n
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
\n

The 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.

", "type": "module", "displayName": "`file:` URLs" }, { "textRaw": "`data:` Imports", "name": "`data:`_imports", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "

data: URLs are supported for importing with the following MIME types:

\n
    \n
  • text/javascript for ES Modules
  • \n
  • application/json for JSON
  • \n
  • application/wasm for Wasm
  • \n
\n

data: 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. An example of a data:\nURLs being used is:

\n
import 'data:text/javascript,console.log(\"hello!\");';\nimport _ from 'data:application/json,\"world!\"';\n
", "type": "module", "displayName": "`data:` Imports" }, { "textRaw": "`node:` Imports", "name": "`node:`_imports", "meta": { "added": [ "v14.13.1", "v12.20.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37246", "description": "Added `node:` import support to `require(...)`." } ] }, "desc": "

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.

\n
import fs from 'node:fs/promises';\n
", "type": "module", "displayName": "`node:` Imports" } ], "type": "module", "displayName": "URLs" } ], "type": "misc", "displayName": "`import` Specifiers" }, { "textRaw": "Builtin modules", "name": "builtin_modules", "desc": "

Core 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 builtin modules are updated only by calling\nmodule.syncBuiltinESMExports().

\n
import EventEmitter from 'events';\nconst e = new EventEmitter();\n
\n
import { readFile } from 'fs';\nreadFile('./foo.txt', (err, source) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(source);\n  }\n});\n
\n
import fs, { readFileSync } from 'fs';\nimport { syncBuiltinESMExports } from 'module';\nimport { Buffer } from 'buffer';\n\nfs.readFileSync = () => Buffer.from('Hello, ESM');\nsyncBuiltinESMExports();\n\nfs.readFileSync === readFileSync;\n
", "type": "misc", "displayName": "Builtin modules" }, { "textRaw": "`import()` expressions", "name": "`import()`_expressions", "desc": "

Dynamic import() is supported in both CommonJS and ES modules. In CommonJS\nmodules it can be used to load ES modules.

", "type": "misc", "displayName": "`import()` expressions" }, { "textRaw": "Interoperability with CommonJS", "name": "interoperability_with_commonjs", "modules": [ { "textRaw": "`import` statements", "name": "`import`_statements", "desc": "

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.

\n

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.

", "type": "module", "displayName": "`import` statements" }, { "textRaw": "`require`", "name": "`require`", "desc": "

The CommonJS module require always treats the files it references as CommonJS.

\n

Using require to load an ES module is not supported because ES modules have\nasynchronous execution. Instead, use import() to load an ES module\nfrom a CommonJS module.

", "type": "module", "displayName": "`require`" }, { "textRaw": "CommonJS Namespaces", "name": "commonjs_namespaces", "desc": "

CommonJS modules consist of a module.exports object which can be of any type.

\n

When importing a CommonJS module, it can be reliably imported using the ES\nmodule default import or its corresponding sugar syntax:

\n\n
import { default as cjs } from 'cjs';\n\n// The following import statement is \"syntax sugar\" (equivalent but sweeter)\n// for `{ default as cjsSugar }` in the above import statement:\nimport cjsSugar from 'cjs';\n\nconsole.log(cjs);\nconsole.log(cjs === cjsSugar);\n// Prints:\n//   <module.exports>\n//   true\n
\n

The ECMAScript Module Namespace representation of a CommonJS module is always\na namespace with a default export key pointing to the CommonJS\nmodule.exports value.

\n

This Module Namespace Exotic Object can be directly observed either when using\nimport * as m from 'cjs' or a dynamic import:

\n\n
import * as m from 'cjs';\nconsole.log(m);\nconsole.log(m === await import('cjs'));\n// Prints:\n//   [Module] { default: <module.exports> }\n//   true\n
\n

For 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.

\n

For example, consider a CommonJS module written:

\n
// cjs.cjs\nexports.name = 'exported';\n
\n

The preceding module supports named imports in ES modules:

\n\n
import { 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: [Module] { default: { name: 'exported' }, name: 'exported' }\n
\n

As 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.

\n

Live binding updates or new exports added to module.exports are not detected\nfor these named exports.

\n

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.

\n

Named exports detection covers many common export patterns, reexport patterns\nand build tool and transpiler outputs. See cjs-module-lexer for the exact\nsemantics implemented.

", "type": "module", "displayName": "CommonJS Namespaces" }, { "textRaw": "Differences between ES modules and CommonJS", "name": "differences_between_es_modules_and_commonjs", "modules": [ { "textRaw": "No `require`, `exports` or `module.exports`", "name": "no_`require`,_`exports`_or_`module.exports`", "desc": "

In most cases, the ES module import can be used to load CommonJS modules.

\n

If needed, a require function can be constructed within an ES module using\nmodule.createRequire().

", "type": "module", "displayName": "No `require`, `exports` or `module.exports`" }, { "textRaw": "No `__filename` or `__dirname`", "name": "no_`__filename`_or_`__dirname`", "desc": "

These CommonJS variables are not available in ES modules.

\n

__filename and __dirname use cases can be replicated via\nimport.meta.url.

", "type": "module", "displayName": "No `__filename` or `__dirname`" }, { "textRaw": "No JSON Module Loading", "name": "no_json_module_loading", "desc": "

JSON imports are still experimental and only supported via the\n--experimental-json-modules flag.

\n

Local JSON files can be loaded relative to import.meta.url with fs directly:

\n\n
import { readFile } from 'fs/promises';\nconst json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url)));\n
\n

Alternatively module.createRequire() can be used.

", "type": "module", "displayName": "No JSON Module Loading" }, { "textRaw": "No Native Module Loading", "name": "no_native_module_loading", "desc": "

Native modules are not currently supported with ES module imports.

\n

They can instead be loaded with module.createRequire() or\nprocess.dlopen.

", "type": "module", "displayName": "No Native Module Loading" }, { "textRaw": "No `require.resolve`", "name": "no_`require.resolve`", "desc": "

Relative resolution can be handled via new URL('./local', import.meta.url).

\n

For a complete require.resolve replacement, there is a flagged experimental\nimport.meta.resolve API.

\n

Alternatively module.createRequire() can be used.

", "type": "module", "displayName": "No `require.resolve`" }, { "textRaw": "No `NODE_PATH`", "name": "no_`node_path`", "desc": "

NODE_PATH is not part of resolving import specifiers. Please use symlinks\nif this behavior is desired.

", "type": "module", "displayName": "No `NODE_PATH`" }, { "textRaw": "No `require.extensions`", "name": "no_`require.extensions`", "desc": "

require.extensions is not used by import. The expectation is that loader\nhooks can provide this workflow in the future.

", "type": "module", "displayName": "No `require.extensions`" }, { "textRaw": "No `require.cache`", "name": "no_`require.cache`", "desc": "

require.cache is not used by import as the ES module loader has its own\nseparate cache.

\n

", "type": "module", "displayName": "No `require.cache`" } ], "type": "module", "displayName": "Differences between ES modules and CommonJS" } ], "type": "misc", "displayName": "Interoperability with CommonJS" }, { "textRaw": "JSON modules", "name": "json_modules", "stability": 1, "stabilityText": "Experimental", "desc": "

Currently importing JSON modules are only supported in the commonjs mode\nand are loaded using the CJS loader. WHATWG JSON modules specification are\nstill being standardized, and are experimentally supported by including the\nadditional flag --experimental-json-modules when running Node.js.

\n

When the --experimental-json-modules flag is included, both the\ncommonjs and module mode use the new experimental JSON\nloader. The imported JSON only exposes a default. There is no\nsupport for named exports. A cache entry is created in the CommonJS\ncache to avoid duplication. The same object is returned in\nCommonJS if the JSON module has already been imported from the\nsame path.

\n

Assuming an index.mjs with

\n\n
import packageConfig from './package.json';\n
\n

The --experimental-json-modules flag is needed for the module\nto work.

\n
node index.mjs # fails\nnode --experimental-json-modules index.mjs # works\n
\n

", "type": "misc", "displayName": "JSON modules" }, { "textRaw": "Wasm modules", "name": "wasm_modules", "stability": 1, "stabilityText": "Experimental", "desc": "

Importing Web Assembly modules is supported under the\n--experimental-wasm-modules flag, allowing any .wasm files to be\nimported as normal modules while also supporting their module imports.

\n

This integration is in line with the\nES Module Integration Proposal for Web Assembly.

\n

For example, an index.mjs containing:

\n
import * as M from './module.wasm';\nconsole.log(M);\n
\n

executed under:

\n
node --experimental-wasm-modules index.mjs\n
\n

would provide the exports interface for the instantiation of module.wasm.

\n

", "type": "misc", "displayName": "Wasm modules" }, { "textRaw": "Top-level `await`", "name": "top-level_`await`", "stability": 1, "stabilityText": "Experimental", "desc": "

The await keyword may be used in the top level (outside of async functions)\nwithin modules as per the ECMAScript Top-Level await proposal.

\n

Assuming an a.mjs with

\n\n
export const five = await Promise.resolve(5);\n
\n

And a b.mjs with

\n
import { five } from './a.mjs';\n\nconsole.log(five); // Logs `5`\n
\n
node b.mjs # works\n
\n

", "type": "misc", "displayName": "Top-level `await`" }, { "textRaw": "Loaders", "name": "Loaders", "stability": 1, "stabilityText": "Experimental", "type": "misc", "desc": "

Note: This API is currently being redesigned and will still change.

\n

To customize the default module resolution, loader hooks can optionally be\nprovided via a --experimental-loader ./loader-name.mjs argument to Node.js.

\n

When hooks are used they only apply to ES module loading and not to any\nCommonJS modules loaded.

", "miscs": [ { "textRaw": "Hooks", "name": "hooks", "methods": [ { "textRaw": "`resolve(specifier, context, defaultResolve)`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The resolve hook returns the resolved file URL for a given module specifier\nand parent URL. The module specifier is the string in an import statement or\nimport() expression, and the parent URL is the URL of the module that imported\nthis one, or undefined if this is the main entry point for the application.

\n

The conditions property on the context is an array of conditions for\nConditional exports that apply to this resolution request. They can be used\nfor looking up conditional mappings elsewhere or to modify the list when calling\nthe default resolution logic.

\n

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.

\n
/**\n * @param {string} specifier\n * @param {{\n *   conditions: !Array<string>,\n *   parentURL: !(string | undefined),\n * }} context\n * @param {Function} defaultResolve\n * @returns {Promise<{ url: string }>}\n */\nexport async function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all specifiers, do some custom logic for resolving.\n    // Always return an object of the form {url: <string>}.\n    return {\n      url: parentURL ?\n        new URL(specifier, parentURL).href :\n        new URL(specifier).href,\n    };\n  }\n  if (Math.random() < 0.5) { // Another condition.\n    // When calling `defaultResolve`, the arguments can be modified. In this\n    // case it's adding another value for matching conditional exports.\n    return defaultResolve(specifier, {\n      ...context,\n      conditions: [...context.conditions, 'another-condition'],\n    });\n  }\n  // Defer to Node.js for all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n
" }, { "textRaw": "`getFormat(url, context, defaultGetFormat)`", "type": "method", "name": "getFormat", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The getFormat hook provides a way to define a custom method of determining how\na URL should be interpreted. The format returned also affects what the\nacceptable forms of source values are for a module when parsing. This can be one\nof the following:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
formatDescriptionAcceptable Types For source Returned by getSource or transformSource
'builtin'Load a Node.js builtin moduleNot applicable
'commonjs'Load a Node.js CommonJS moduleNot applicable
'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
'module'Load an ES module{ string, ArrayBuffer, TypedArray }
'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }
\n

Note: These types all correspond to classes defined in ECMAScript.

\n\n

Note: If the source value of a text-based format (i.e., 'json', 'module') is\nnot a string, it is converted to a string using util.TextDecoder.

\n
/**\n * @param {string} url\n * @param {Object} context (currently empty)\n * @param {Function} defaultGetFormat\n * @returns {Promise<{ format: string }>}\n */\nexport async function getFormat(url, context, defaultGetFormat) {\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for determining format.\n    // Always return an object of the form {format: <string>}, where the\n    // format is one of the strings in the preceding table.\n    return {\n      format: 'module',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n
" }, { "textRaw": "`getSource(url, context, defaultGetSource)`", "type": "method", "name": "getSource", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The getSource hook provides a way to define a custom method for retrieving\nthe source code of an ES module specifier. This would allow a loader to\npotentially avoid reading files from disk.

\n
/**\n * @param {string} url\n * @param {{ format: string }} context\n * @param {Function} defaultGetSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function getSource(url, context, defaultGetSource) {\n  const { format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for retrieving the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
" }, { "textRaw": "`transformSource(source, context, defaultTransformSource)`", "type": "method", "name": "transformSource", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

The transformSource hook provides a way to modify the source code of a loaded\nES module file after the source string has been loaded but before Node.js has\ndone anything with it.

\n

If this hook is used to convert unknown-to-Node.js file types into executable\nJavaScript, a resolve hook is also necessary in order to register any\nunknown-to-Node.js file extensions. See the transpiler loader example below.

\n
/**\n * @param {!(string | SharedArrayBuffer | Uint8Array)} source\n * @param {{\n *   format: string,\n *   url: string,\n * }} context\n * @param {Function} defaultTransformSource\n * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}\n */\nexport async function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n  if (Math.random() > 0.5) { // Some condition.\n    // For some or all URLs, do some custom logic for modifying the source.\n    // Always return an object of the form {source: <string|buffer>}.\n    return {\n      source: '...',\n    };\n  }\n  // Defer to Node.js for all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
" }, { "textRaw": "`getGlobalPreloadCode()`", "type": "method", "name": "getGlobalPreloadCode", "signatures": [ { "params": [] } ], "desc": "
\n

Note: The loaders API is being redesigned. This hook may disappear or its\nsignature may change. Do not rely on the API described below.

\n
\n\n

Sometimes it might be necessary to run some code inside of the same global scope\nthat the application runs in. This hook allows the return of a string that is\nrun as sloppy-mode script on startup.

\n

Similar to how CommonJS wrappers work, the code runs in an implicit function\nscope. The only argument is a require-like function that can be used to load\nbuiltins like \"fs\": getBuiltin(request: string).

\n

If the code needs more advanced require features, it has to construct\nits own require using module.createRequire().

\n
/**\n * @returns {string} Code to run before application startup\n */\nexport function getGlobalPreloadCode() {\n  return `\\\nglobalThis.someInjectedProperty = 42;\nconsole.log('I just set some globals!');\n\nconst { createRequire } = getBuiltin('module');\nconst { cwd } = getBuiltin('process');\n\nconst require = createRequire(cwd() + '/<preload>');\n// [...]\n`;\n}\n
\n

Examples

\n

The various loader hooks can be used together to accomplish wide-ranging\ncustomizations of Node.js’ code loading and evaluation behaviors.

" } ], "modules": [ { "textRaw": "HTTPS loader", "name": "https_loader", "desc": "

In current Node.js, specifiers starting with https:// are unsupported. The\nloader below registers hooks to enable rudimentary support for such specifiers.\nWhile this may seem like a significant improvement to Node.js core\nfunctionality, there are substantial downsides to actually using this loader:\nperformance is much slower than loading files from disk, there is no caching,\nand there is no security.

\n
// https-loader.mjs\nimport { get } from 'https';\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = null } = context;\n\n  // Normally Node.js would error on specifiers starting with 'https://', so\n  // this hook intercepts them and converts them into absolute URLs to be\n  // passed along to the later hooks below.\n  if (specifier.startsWith('https://')) {\n    return {\n      url: specifier\n    };\n  } else if (parentURL && parentURL.startsWith('https://')) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // This loader assumes all network-provided JavaScript is ES module code.\n  if (url.startsWith('https://')) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function getSource(url, context, defaultGetSource) {\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.on('data', (chunk) => data += chunk);\n        res.on('end', () => resolve({ source: data }));\n      }).on('error', (err) => reject(err));\n    });\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetSource(url, context, defaultGetSource);\n}\n
\n
// main.mjs\nimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';\n\nconsole.log(VERSION);\n
\n

With the preceding loader, running\nnode --experimental-loader ./https-loader.mjs ./main.mjs\nprints the current version of CoffeeScript per the module at the URL in\nmain.mjs.

", "type": "module", "displayName": "HTTPS loader" }, { "textRaw": "Transpiler loader", "name": "transpiler_loader", "desc": "

Sources that are in formats Node.js doesn’t understand can be converted into\nJavaScript using the transformSource hook. Before that hook gets called,\nhowever, other hooks need to tell Node.js not to throw an error on unknown file\ntypes; and to tell Node.js how to load this new file type.

\n

This is less performant than transpiling source files before running\nNode.js; a transpiler loader should only be used for development and testing\npurposes.

\n
// coffeescript-loader.mjs\nimport { URL, pathToFileURL } from 'url';\nimport CoffeeScript from 'coffeescript';\nimport { cwd } from 'process';\n\nconst baseURL = pathToFileURL(`${cwd()}/`).href;\n\n// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.\nconst extensionsRegex = /\\.coffee$|\\.litcoffee$|\\.coffee\\.md$/;\n\nexport function resolve(specifier, context, defaultResolve) {\n  const { parentURL = baseURL } = context;\n\n  // Node.js normally errors on unknown file extensions, so return a URL for\n  // specifiers ending in the CoffeeScript file extensions.\n  if (extensionsRegex.test(specifier)) {\n    return {\n      url: new URL(specifier, parentURL).href\n    };\n  }\n\n  // Let Node.js handle all other specifiers.\n  return defaultResolve(specifier, context, defaultResolve);\n}\n\nexport function getFormat(url, context, defaultGetFormat) {\n  // Now that we patched resolve to let CoffeeScript URLs through, we need to\n  // tell Node.js what format such URLs should be interpreted as. For the\n  // purposes of this loader, all CoffeeScript URLs are ES modules.\n  if (extensionsRegex.test(url)) {\n    return {\n      format: 'module'\n    };\n  }\n\n  // Let Node.js handle all other URLs.\n  return defaultGetFormat(url, context, defaultGetFormat);\n}\n\nexport function transformSource(source, context, defaultTransformSource) {\n  const { url, format } = context;\n\n  if (extensionsRegex.test(url)) {\n    return {\n      source: CoffeeScript.compile(source, { bare: true })\n    };\n  }\n\n  // Let Node.js handle all other sources.\n  return defaultTransformSource(source, context, defaultTransformSource);\n}\n
\n
# main.coffee\nimport { scream } from './scream.coffee'\nconsole.log scream 'hello, world'\n\nimport { version } from 'process'\nconsole.log \"Brought to you by Node.js version #{version}\"\n
\n
# scream.coffee\nexport scream = (str) -> str.toUpperCase()\n
\n

With the preceding loader, running\nnode --experimental-loader ./coffeescript-loader.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.

", "type": "module", "displayName": "Transpiler loader" } ], "type": "misc", "displayName": "Hooks" } ] }, { "textRaw": "Resolution algorithm", "name": "resolution_algorithm", "modules": [ { "textRaw": "Features", "name": "features", "desc": "

The resolver has the following properties:

\n
    \n
  • FileURL-based resolution as is used by ES modules
  • \n
  • Support for builtin module loading
  • \n
  • Relative and absolute URL resolution
  • \n
  • No default extensions
  • \n
  • No folder mains
  • \n
  • Bare specifier package resolution lookup through node_modules
  • \n
", "type": "module", "displayName": "Features" }, { "textRaw": "Resolver algorithm", "name": "resolver_algorithm", "desc": "

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.

\n

The algorithm to determine the module format of a resolved URL is\nprovided by ESM_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.

\n

In the following algorithms, all subroutine errors are propagated as errors\nof these top-level routines unless stated otherwise.

\n

defaultConditions is the conditional environment name array,\n[\"node\", \"import\"].

\n

The resolver can throw the following errors:

\n
    \n
  • Invalid Module Specifier: Module specifier is an invalid URL, package name\nor package subpath specifier.
  • \n
  • Invalid Package Configuration: package.json configuration is invalid or\ncontains an invalid configuration.
  • \n
  • Invalid Package Target: Package exports or imports define a target module\nfor the package that is an invalid type or string target.
  • \n
  • Package Path Not Exported: Package exports do not define or permit a target\nsubpath in the package for the given module.
  • \n
  • Package Import Not Defined: Package imports do not define the specifier.
  • \n
  • Module Not Found: The package or module requested does not exist.
  • \n
  • Unsupported Directory Import: The resolved path corresponds to a directory,\nwhich is not a supported target for module imports.
  • \n
", "type": "module", "displayName": "Resolver algorithm" }, { "textRaw": "Resolver Algorithm Specification", "name": "resolver_algorithm_specification", "desc": "

ESM_RESOLVE(specifier, parentURL)

\n
\n
    \n
  1. Let resolved be undefined.
  2. \n
  3. If specifier is a valid URL, then\n
      \n
    1. Set resolved to the result of parsing and reserializing\nspecifier as a URL.
    2. \n
    \n
  4. \n
  5. Otherwise, if specifier starts with \"/\", \"./\" or \"../\", then\n
      \n
    1. Set resolved to the URL resolution of specifier relative to\nparentURL.
    2. \n
    \n
  6. \n
  7. Otherwise, if specifier starts with \"#\", then\n
      \n
    1. Set resolved to the destructured value of the result of\nPACKAGE_IMPORTS_RESOLVE(specifier, parentURL,\ndefaultConditions).
    2. \n
    \n
  8. \n
  9. Otherwise,\n
      \n
    1. Note: specifier is now a bare specifier.
    2. \n
    3. Set resolved the result of\nPACKAGE_RESOLVE(specifier, parentURL).
    4. \n
    \n
  10. \n
  11. If resolved contains any percent encodings of \"/\" or \"\\\" (\"%2f\"\nand \"%5C\" respectively), then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  12. \n
  13. If the file at resolved is a directory, then\n
      \n
    1. Throw an Unsupported Directory Import error.
    2. \n
    \n
  14. \n
  15. If the file at resolved does not exist, then\n
      \n
    1. Throw a Module Not Found error.
    2. \n
    \n
  16. \n
  17. Set resolved to the real path of resolved.
  18. \n
  19. Let format be the result of ESM_FORMAT(resolved).
  20. \n
  21. Load resolved as module format, format.
  22. \n
  23. Return resolved.
  24. \n
\n
\n

PACKAGE_RESOLVE(packageSpecifier, parentURL)

\n
\n
    \n
  1. Let packageName be undefined.
  2. \n
  3. If packageSpecifier is an empty string, then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  4. \n
  5. If packageSpecifier does not start with \"@\", then\n
      \n
    1. Set packageName to the substring of packageSpecifier until the first\n\"/\" separator or the end of the string.
    2. \n
    \n
  6. \n
  7. Otherwise,\n
      \n
    1. If packageSpecifier does not contain a \"/\" separator, then\n
        \n
      1. Throw an Invalid Module Specifier error.
      2. \n
      \n
    2. \n
    3. Set packageName to the substring of packageSpecifier\nuntil the second \"/\" separator or the end of the string.
    4. \n
    \n
  8. \n
  9. If packageName starts with \".\" or contains \"\\\" or \"%\", then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  10. \n
  11. Let packageSubpath be \".\" concatenated with the substring of\npackageSpecifier from the position at the length of packageName.
  12. \n
  13. Let selfUrl be the result of\nPACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL).
  14. \n
  15. If selfUrl is not undefined, return selfUrl.
  16. \n
  17. If packageSubpath is \".\" and packageName is a Node.js builtin\nmodule, then\n
      \n
    1. Return the string \"node:\" concatenated with packageSpecifier.
    2. \n
    \n
  18. \n
  19. While parentURL is not the file system root,\n
      \n
    1. Let packageURL be the URL resolution of \"node_modules/\"\nconcatenated with packageSpecifier, relative to parentURL.
    2. \n
    3. Set parentURL to the parent folder URL of parentURL.
    4. \n
    5. If the folder at packageURL does not exist, then\n
        \n
      1. Set parentURL to the parent URL path of parentURL.
      2. \n
      3. Continue the next loop iteration.
      4. \n
      \n
    6. \n
    7. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
    8. \n
    9. If pjson is not null and pjson.exports is not null or\nundefined, then\n
        \n
      1. Let exports be pjson.exports.
      2. \n
      3. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, packageSubpath,\npjson.exports, defaultConditions).
      4. \n
      \n
    10. \n
    11. Otherwise, if packageSubpath is equal to \".\", then\n
        \n
      1. Return the result applying the legacy LOAD_AS_DIRECTORY\nCommonJS resolver to packageURL, throwing a Module Not Found\nerror for no resolution.
      2. \n
      \n
    12. \n
    13. Otherwise,\n
        \n
      1. Return the URL resolution of packageSubpath in packageURL.
      2. \n
      \n
    14. \n
    \n
  20. \n
  21. Throw a Module Not Found error.
  22. \n
\n
\n

PACKAGE_SELF_RESOLVE(packageName, packageSubpath, parentURL)

\n
\n
    \n
  1. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  2. \n
  3. If packageURL is null, then\n
      \n
    1. Return undefined.
    2. \n
    \n
  4. \n
  5. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
  6. \n
  7. If pjson is null or if pjson.exports is null or\nundefined, then\n
      \n
    1. Return undefined.
    2. \n
    \n
  8. \n
  9. If pjson.name is equal to packageName, then\n
      \n
    1. Return the resolved destructured value of the result of\nPACKAGE_EXPORTS_RESOLVE(packageURL, subpath, pjson.exports,\ndefaultConditions).
    2. \n
    \n
  10. \n
  11. Otherwise, return undefined.
  12. \n
\n
\n

PACKAGE_EXPORTS_RESOLVE(packageURL, subpath, exports, conditions)

\n
\n
    \n
  1. If exports is an Object with both a key starting with \".\" and a key not\nstarting with \".\", throw an Invalid Package Configuration error.
  2. \n
  3. If subpath is equal to \".\", then\n
      \n
    1. Let mainExport be undefined.
    2. \n
    3. If exports is a String or Array, or an Object containing no keys\nstarting with \".\", then\n
        \n
      1. Set mainExport to exports.
      2. \n
      \n
    4. \n
    5. Otherwise if exports is an Object containing a \".\" property, then\n
        \n
      1. Set mainExport to exports[\".\"].
      2. \n
      \n
    6. \n
    7. If mainExport is not undefined, then\n
        \n
      1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, mainExport, \"\", false, false,\nconditions).
      2. \n
      3. If resolved is not null or undefined, then\n
          \n
        1. Return resolved.
        2. \n
        \n
      4. \n
      \n
    8. \n
    \n
  4. \n
  5. Otherwise, if exports is an Object and all keys of exports start with\n\".\", then\n
      \n
    1. Let matchKey be the string \"./\" concatenated with subpath.
    2. \n
    3. Let resolvedMatch be result of PACKAGE_IMPORTS_EXPORTS_RESOLVE(\nmatchKey, exports, packageURL, false, conditions).
    4. \n
    5. If resolvedMatch.resolve is not null or undefined, then\n
        \n
      1. Return resolvedMatch.
      2. \n
      \n
    6. \n
    \n
  6. \n
  7. Throw a Package Path Not Exported error.
  8. \n
\n
\n

PACKAGE_IMPORTS_RESOLVE(specifier, parentURL, conditions)

\n
\n
    \n
  1. Assert: specifier begins with \"#\".
  2. \n
  3. If specifier is exactly equal to \"#\" or starts with \"#/\", then\n
      \n
    1. Throw an Invalid Module Specifier error.
    2. \n
    \n
  4. \n
  5. Let packageURL be the result of READ_PACKAGE_SCOPE(parentURL).
  6. \n
  7. If packageURL is not null, then\n
      \n
    1. Let pjson be the result of READ_PACKAGE_JSON(packageURL).
    2. \n
    3. If pjson.imports is a non-null Object, then\n
        \n
      1. Let resolvedMatch be the result of\nPACKAGE_IMPORTS_EXPORTS_RESOLVE(specifier, pjson.imports,\npackageURL, true, conditions).
      2. \n
      3. If resolvedMatch.resolve is not null or undefined, then\n
          \n
        1. Return resolvedMatch.
        2. \n
        \n
      4. \n
      \n
    4. \n
    \n
  8. \n
  9. Throw a Package Import Not Defined error.
  10. \n
\n
\n

PACKAGE_IMPORTS_EXPORTS_RESOLVE(matchKey, matchObj, packageURL,\nisImports, conditions)

\n
\n
    \n
  1. If matchKey is a key of matchObj, and does not end in \"*\", then\n
      \n
    1. Let target be the value of matchObj[matchKey].
    2. \n
    3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, \"\", false, isImports, conditions).
    4. \n
    5. Return the object { resolved, exact: true }.
    6. \n
    \n
  2. \n
  3. Let expansionKeys be the list of keys of matchObj ending in \"/\"\nor \"*\", sorted by length descending.
  4. \n
  5. For each key expansionKey in expansionKeys, do\n
      \n
    1. If expansionKey ends in \"*\" and matchKey starts with but is\nnot equal to the substring of expansionKey excluding the last \"*\"\ncharacter, then\n
        \n
      1. Let target be the value of matchObj[expansionKey].
      2. \n
      3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey minus one.
      4. \n
      5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, true, isImports,\nconditions).
      6. \n
      7. Return the object { resolved, exact: true }.
      8. \n
      \n
    2. \n
    3. If matchKey starts with expansionKey, then\n
        \n
      1. Let target be the value of matchObj[expansionKey].
      2. \n
      3. Let subpath be the substring of matchKey starting at the\nindex of the length of expansionKey.
      4. \n
      5. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, target, subpath, false, isImports,\nconditions).
      6. \n
      7. Return the object { resolved, exact: false }.
      8. \n
      \n
    4. \n
    \n
  6. \n
  7. Return the object { resolved: null, exact: true }.
  8. \n
\n
\n

PACKAGE_TARGET_RESOLVE(packageURL, target, subpath, pattern,\ninternal, conditions)

\n
\n
    \n
  1. If target is a String, then\n
      \n
    1. If pattern is false, subpath has non-zero length and target\ndoes not end with \"/\", throw an Invalid Module Specifier error.
    2. \n
    3. If target does not start with \"./\", then\n
        \n
      1. If internal is true and target does not start with \"../\" or\n\"/\" and is not a valid URL, then\n
          \n
        1. If pattern is true, then\n
            \n
          1. Return PACKAGE_RESOLVE(target with every instance of\n\"*\" replaced by subpath, packageURL + \"/\")_.
          2. \n
          \n
        2. \n
        3. Return PACKAGE_RESOLVE(target + subpath,\npackageURL + \"/\")_.
        4. \n
        \n
      2. \n
      3. Otherwise, throw an Invalid Package Target error.
      4. \n
      \n
    4. \n
    5. If target split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments after the first segment, throw an\nInvalid Package Target error.
    6. \n
    7. Let resolvedTarget be the URL resolution of the concatenation of\npackageURL and target.
    8. \n
    9. Assert: resolvedTarget is contained in packageURL.
    10. \n
    11. If subpath split on \"/\" or \"\\\" contains any \".\", \"..\" or\n\"node_modules\" segments, throw an Invalid Module Specifier error.
    12. \n
    13. If pattern is true, then\n
        \n
      1. Return the URL resolution of resolvedTarget with every instance of\n\"*\" replaced with subpath.
      2. \n
      \n
    14. \n
    15. Otherwise,\n
        \n
      1. Return the URL resolution of the concatenation of subpath and\nresolvedTarget.
      2. \n
      \n
    16. \n
    \n
  2. \n
  3. Otherwise, if target is a non-null Object, then\n
      \n
    1. If exports contains any index property keys, as defined in ECMA-262\n6.1.7 Array Index, throw an Invalid Package Configuration error.
    2. \n
    3. For each property p of target, in object insertion order as,\n
        \n
      1. If p equals \"default\" or conditions contains an entry for p,\nthen\n
          \n
        1. Let targetValue be the value of the p property in target.
        2. \n
        3. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions).
        4. \n
        5. If resolved is equal to undefined, continue the loop.
        6. \n
        7. Return resolved.
        8. \n
        \n
      2. \n
      \n
    4. \n
    5. Return undefined.
    6. \n
    \n
  4. \n
  5. Otherwise, if target is an Array, then\n
      \n
    1. If _target.length is zero, return null.
    2. \n
    3. For each item targetValue in target, do\n
        \n
      1. Let resolved be the result of PACKAGE_TARGET_RESOLVE(\npackageURL, targetValue, subpath, pattern, internal,\nconditions), continuing the loop on any Invalid Package Target\nerror.
      2. \n
      3. If resolved is undefined, continue the loop.
      4. \n
      5. Return resolved.
      6. \n
      \n
    4. \n
    5. Return or throw the last fallback resolution null return or error.
    6. \n
    \n
  6. \n
  7. Otherwise, if target is null, return null.
  8. \n
  9. Otherwise throw an Invalid Package Target error.
  10. \n
\n
\n

ESM_FORMAT(url)

\n
\n
    \n
  1. Assert: url corresponds to an existing file.
  2. \n
  3. Let pjson be the result of READ_PACKAGE_SCOPE(url).
  4. \n
  5. If url ends in \".mjs\", then\n
      \n
    1. Return \"module\".
    2. \n
    \n
  6. \n
  7. If url ends in \".cjs\", then\n
      \n
    1. Return \"commonjs\".
    2. \n
    \n
  8. \n
  9. If pjson?.type exists and is \"module\", then\n
      \n
    1. If url ends in \".js\", then\n
        \n
      1. Return \"module\".
      2. \n
      \n
    2. \n
    3. Throw an Unsupported File Extension error.
    4. \n
    \n
  10. \n
  11. Otherwise,\n
      \n
    1. Throw an Unsupported File Extension error.
    2. \n
    \n
  12. \n
\n
\n

READ_PACKAGE_SCOPE(url)

\n
\n
    \n
  1. Let scopeURL be url.
  2. \n
  3. While scopeURL is not the file system root,\n
      \n
    1. Set scopeURL to the parent URL of scopeURL.
    2. \n
    3. If scopeURL ends in a \"node_modules\" path segment, return null.
    4. \n
    5. Let pjson be the result of READ_PACKAGE_JSON(scopeURL).
    6. \n
    7. If pjson is not null, then\n
        \n
      1. Return pjson.
      2. \n
      \n
    8. \n
    \n
  4. \n
  5. Return null.
  6. \n
\n
\n

READ_PACKAGE_JSON(packageURL)

\n
\n
    \n
  1. Let pjsonURL be the resolution of \"package.json\" within packageURL.
  2. \n
  3. If the file at pjsonURL does not exist, then\n
      \n
    1. Return null.
    2. \n
    \n
  4. \n
  5. If the file at packageURL does not parse as valid JSON, then\n
      \n
    1. Throw an Invalid Package Configuration error.
    2. \n
    \n
  6. \n
  7. Return the parsed JSON source of the file at pjsonURL.
  8. \n
\n
", "type": "module", "displayName": "Resolver Algorithm Specification" }, { "textRaw": "Customizing ESM specifier resolution algorithm", "name": "customizing_esm_specifier_resolution_algorithm", "stability": 1, "stabilityText": "Experimental", "desc": "

The current specifier resolution does not support all default behavior of\nthe CommonJS loader. One of the behavior differences is automatic resolution\nof file extensions and the ability to import directories that have an index\nfile.

\n

The --experimental-specifier-resolution=[mode] flag can be used to customize\nthe extension resolution algorithm. The default mode is explicit, which\nrequires the full path to a module be provided to the loader. To enable the\nautomatic extension resolution and importing from directories that include an\nindex file use the node mode.

\n
$ node index.mjs\nsuccess!\n$ node index # Failure!\nError: Cannot find module\n$ node --experimental-specifier-resolution=node index\nsuccess!\n
\n", "type": "module", "displayName": "Customizing ESM specifier resolution algorithm" } ], "type": "misc", "displayName": "Resolution algorithm" } ], "properties": [ { "textRaw": "`meta` {Object}", "type": "Object", "name": "meta", "desc": "

The import.meta meta property is an Object that contains the following\nproperties.

", "properties": [ { "textRaw": "`url` {string} The absolute `file:` URL of the module.", "type": "string", "name": "url", "desc": "

This is defined exactly the same as it is in browsers providing the URL of the\ncurrent module file.

\n

This enables useful patterns such as relative file loading:

\n
import { readFileSync } from 'fs';\nconst buffer = readFileSync(new URL('./data.proto', import.meta.url));\n
", "shortDesc": "The absolute `file:` URL of the module." } ], "methods": [ { "textRaw": "`import.meta.resolve(specifier[, parent])`", "type": "method", "name": "resolve", "signatures": [ { "params": [] } ], "desc": "\n
\n

Stability: 1 - Experimental

\n
\n

This feature is only available with the --experimental-import-meta-resolve\ncommand flag enabled.

\n
    \n
  • specifier <string> The module specifier to resolve relative to parent.
  • \n
  • parent <string> | <URL> The absolute parent module URL to resolve from. If none\nis specified, the value of import.meta.url is used as the default.
  • \n
  • Returns: <Promise>
  • \n
\n

Provides a module-relative resolution function scoped to each module, returning\nthe URL string.

\n\n
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');\n
\n

import.meta.resolve also accepts a second argument which is the parent module\nfrom which to resolve from:

\n\n
await import.meta.resolve('./dep', import.meta.url);\n
\n

This function is asynchronous because the ES module resolver in Node.js is\nallowed to be asynchronous.

" } ] } ], "source": "doc/api/esm.md" }, { "textRaw": "Modules: Packages", "name": "Modules: Packages", "introduced_in": "v12.20.0", "type": "misc", "meta": { "changes": [ { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/34117", "description": "Add package `\"imports\"` field." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Unflag conditional exports." }, { "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." }, { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28568", "description": "Introduce `\"exports\"` `package.json` field as a more powerful alternative to the classic `\"main\"` field." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26745", "description": "Add support for ES modules using `.js` file extension via `package.json` `\"type\"` field." } ] }, "miscs": [ { "textRaw": "Introduction", "name": "introduction", "desc": "

A 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.

\n

This page provides guidance for package authors writing package.json files\nalong with a reference for the package.json fields defined by Node.js.

", "type": "misc", "displayName": "Introduction" }, { "textRaw": "Determining module system", "name": "determining_module_system", "desc": "

Node.js will treat the following as ES modules when passed to node as the\ninitial input, or when referenced by import statements within ES module code:

\n
    \n
  • \n

    Files ending in .mjs.

    \n
  • \n
  • \n

    Files ending in .js when the nearest parent package.json file contains a\ntop-level \"type\" field with a value of \"module\".

    \n
  • \n
  • \n

    Strings passed in as an argument to --eval, or piped to node via STDIN,\nwith the flag --input-type=module.

    \n
  • \n
\n

Node.js will treat as CommonJS all other forms of input, such as .js files\nwhere the nearest parent package.json file contains no top-level \"type\"\nfield, or string input without the flag --input-type. This behavior is to\npreserve backward compatibility. However, now that Node.js supports both\nCommonJS and ES modules, it is best to be explicit whenever possible. Node.js\nwill treat the following as CommonJS when passed to node as the initial input,\nor when referenced by import statements within ES module code:

\n
    \n
  • \n

    Files ending in .cjs.

    \n
  • \n
  • \n

    Files ending in .js when the nearest parent package.json file contains a\ntop-level field \"type\" with a value of \"commonjs\".

    \n
  • \n
  • \n

    Strings passed in as an argument to --eval or --print, or piped to node\nvia STDIN, with the flag --input-type=commonjs.

    \n
  • \n
\n

Package authors should include the \"type\" field, even in packages where\nall sources are CommonJS. Being explicit about the type of the package will\nfuture-proof the package in case the default type of Node.js ever changes, and\nit will also make things easier for build tools and loaders to determine how the\nfiles in the package should be interpreted.

", "modules": [ { "textRaw": "`package.json` and file extensions", "name": "`package.json`_and_file_extensions", "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.

\n

A package.json \"type\" value of \"module\" tells Node.js to interpret .js\nfiles within that package as using ES module syntax.

\n

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.

\n
// 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
\n

Files ending with .mjs are always loaded as ES modules regardless of\nthe nearest parent package.json.

\n

Files ending with .cjs are always loaded as CommonJS regardless of the\nnearest parent package.json.

\n
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
\n

The .mjs and .cjs extensions can be used to mix types within the same\npackage:

\n
    \n
  • \n

    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).

    \n
  • \n
  • \n

    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).

    \n
  • \n
", "type": "module", "displayName": "`package.json` and file extensions" }, { "textRaw": "`--input-type` flag", "name": "`--input-type`_flag", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "desc": "

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.

\n
node --input-type=module --eval \"import { sep } from 'path'; console.log(sep);\"\n\necho \"import { sep } from 'path'; console.log(sep);\" | node --input-type=module\n
\n

For completeness there is also --input-type=commonjs, for explicitly running\nstring input as CommonJS. This is the default behavior if --input-type is\nunspecified.

", "type": "module", "displayName": "`--input-type` flag" } ], "type": "misc", "displayName": "Determining module system" }, { "textRaw": "Package entry points", "name": "package_entry_points", "desc": "

In a package’s package.json file, two fields can define entry points for a\npackage: \"main\" and \"exports\". The \"main\" field is supported\nin all versions of Node.js, but its capabilities are limited: it only defines\nthe main entry point of the package.

\n

The \"exports\" field provides an alternative to \"main\" where the\npackage main entry point can be defined while also encapsulating the package,\npreventing any other entry points besides those defined in \"exports\".\nThis encapsulation allows module authors to define a public interface for\ntheir package.

\n

If both \"exports\" and \"main\" are defined, the \"exports\" field\ntakes precedence over \"main\". \"exports\" are not specific to ES\nmodules or CommonJS; \"main\" is overridden by \"exports\" if it\nexists. As such \"main\" cannot be used as a fallback for CommonJS but it\ncan be used as a fallback for legacy versions of Node.js that do not support the\n\"exports\" field.

\n

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.

\n

Warning: Introducing the \"exports\" field prevents consumers of a\npackage 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.

\n

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 previous exported main, lib,\nfeature, and the package.json could use the following package.exports:

\n
{\n  \"name\": \"my-mod\",\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.js\": \"./feature/index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

Alternatively a project could choose to export entire folders:

\n
{\n  \"name\": \"my-mod\",\n  \"exports\": {\n    \".\": \"./lib/index.js\",\n    \"./lib\": \"./lib/index.js\",\n    \"./lib/*\": \"./lib/*.js\",\n    \"./feature\": \"./feature/index.js\",\n    \"./feature/*\": \"./feature/*.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n
\n

As a last resort, package encapsulation can be disabled entirely by creating an\nexport for the root of the package \"./*\": \"./*\". This exposes every file\nin the package at the cost of disabling the encapsulation and potential tooling\nbenefits this provides. As the ES Module loader in Node.js enforces the use of\nthe full specifier path, exporting the root rather than being explicit\nabout entry is less expressive than either of the prior examples. Not only\nis encapsulation lost but module consumers are unable to\nimport feature from 'my-mod/feature' as they need to provide the full\npath import feature from 'my-mod/feature/index.js.

", "modules": [ { "textRaw": "Main entry point export", "name": "main_entry_point_export", "desc": "

To set the main entry point for a package, it is advisable to define both\n\"exports\" and \"main\" in the package’s package.json file:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": \"./main.js\"\n}\n
\n

When 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.

\n

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.

", "type": "module", "displayName": "Main entry point export" }, { "textRaw": "Subpath exports", "name": "subpath_exports", "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
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./submodule\": \"./src/submodule.js\"\n  }\n}\n
\n

Now only the defined subpath in \"exports\" can be imported by a consumer:

\n
import submodule from 'es-module-package/submodule';\n// Loads ./node_modules/es-module-package/src/submodule.js\n
\n

While other subpaths will error:

\n
import submodule from 'es-module-package/private-module.js';\n// Throws ERR_PACKAGE_PATH_NOT_EXPORTED\n
", "type": "module", "displayName": "Subpath exports" }, { "textRaw": "Subpath imports", "name": "subpath_imports", "meta": { "added": [ "v14.6.0", "v12.19.0" ], "changes": [] }, "desc": "

In addition to the \"exports\" field, it is possible to define internal\npackage import maps that only apply to import specifiers from within the package\nitself.

\n

Entries in the imports field must always start with # to ensure they are\ndisambiguated from package specifiers.

\n

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
\n

where 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.

\n

Unlike the \"exports\" field, the \"imports\" field permits mapping to external\npackages.

\n

The resolution rules for the imports field are otherwise\nanalogous to the exports field.

", "type": "module", "displayName": "Subpath imports" }, { "textRaw": "Subpath patterns", "name": "subpath_patterns", "meta": { "added": [ "v14.13.0", "v12.20.0" ], "changes": [] }, "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.

\n

For these use cases, subpath export patterns can be used instead:

\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/*\": \"./src/features/*.js\"\n  },\n  \"imports\": {\n    \"#internal/*\": \"./src/internal/*.js\"\n  }\n}\n
\n

* maps expose nested subpaths as it is a string replacement syntax\nonly.

\n

The left hand matching pattern must always end in *. All instances of * on\nthe right hand side will then be replaced with this value, including if it\ncontains any / separators.

\n
import featureX from 'es-module-package/features/x';\n// Loads ./node_modules/es-module-package/src/features/x.js\n\nimport featureY from 'es-module-package/features/y/y';\n// Loads ./node_modules/es-module-package/src/features/y/y.js\n\nimport internalZ from '#internal/z';\n// Loads ./node_modules/es-module-package/src/internal/z.js\n
\n

This is a direct static replacement without any special handling for file\nextensions. In the previous example, pkg/features/x.json would be resolved to\n./src/features/x.json.js in the mapping.

\n

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.

\n

To exclude private subfolders from patterns, null targets can be used:

\n
// ./node_modules/es-module-package/package.json\n{\n  \"exports\": {\n    \"./features/*\": \"./src/features/*.js\",\n    \"./features/private-internal/*\": null\n  }\n}\n
\n
import featureInternal from 'es-module-package/features/private-internal/m';\n// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED\n\nimport featureX from 'es-module-package/features/x';\n// Loads ./node_modules/es-module-package/src/features/x.js\n
", "type": "module", "displayName": "Subpath patterns" }, { "textRaw": "Subpath folder mappings", "name": "subpath_folder_mappings", "meta": { "changes": [ { "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", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Documentation-only deprecation." } ] }, "stability": 0, "stabilityText": "Deprecated: Use subpath patterns instead.", "desc": "

Before subpath patterns were supported, a trailing \"/\" suffix was used to\nsupport folder mappings:

\n
{\n  \"exports\": {\n    \"./features/\": \"./features/\"\n  }\n}\n
\n

This feature will be removed in a future release.

\n

Instead, use direct subpath patterns:

\n
{\n  \"exports\": {\n    \"./features/*\": \"./features/*.js\"\n  }\n}\n
\n

The benefit of patterns over folder exports is that packages can always be\nimported by consumers without subpath file extensions being necessary.

", "type": "module", "displayName": "Subpath folder mappings" }, { "textRaw": "Exports sugar", "name": "exports_sugar", "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

If the \".\" export has a fallback array or string value, then the\n\"exports\" field can be set to this value directly.

\n
{\n  \"exports\": {\n    \".\": \"./main.js\"\n  }\n}\n
\n

can be written:

\n
{\n  \"exports\": \"./main.js\"\n}\n
", "type": "module", "displayName": "Exports sugar" }, { "textRaw": "Conditional exports", "name": "conditional_exports", "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.

\n

For example, a package that wants to provide different ES module exports for\nrequire() and import can be written:

\n
// package.json\n{\n  \"main\": \"./main-require.cjs\",\n  \"exports\": {\n    \"import\": \"./main-module.js\",\n    \"require\": \"./main-require.cjs\"\n  },\n  \"type\": \"module\"\n}\n
\n

Node.js implements the following conditions:

\n
    \n
  • \"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\".
  • \n
  • \"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, and native addons but not ES modules as\nrequire() doesn't support them. Always mutually exclusive with\n\"import\".
  • \n
  • \"node\" - matches for any Node.js environment. Can be a CommonJS or ES\nmodule file. This condition should always come after \"import\" or\n\"require\".
  • \n
  • \"default\" - the generic fallback that always matches. Can be a CommonJS\nor ES module file. This condition should always come last.
  • \n
\n

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.

\n

Using the \"import\" and \"require\" conditions can lead to some hazards,\nwhich are further explained in the dual CommonJS/ES module packages section.

\n

Conditional exports can also be extended to exports subpaths, for example:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \".\": \"./main.js\",\n    \"./feature\": {\n      \"node\": \"./feature-node.js\",\n      \"default\": \"./feature.js\"\n    }\n  }\n}\n
\n

Defines a package where require('pkg/feature') and import 'pkg/feature'\ncould provide different implementations between Node.js and other JS\nenvironments.

\n

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.

", "type": "module", "displayName": "Conditional exports" }, { "textRaw": "Nested conditions", "name": "nested_conditions", "desc": "

In addition to direct mappings, Node.js also supports nested condition objects.

\n

For example, to define a package that only has dual mode entry points for\nuse in Node.js but not the browser:

\n
{\n  \"main\": \"./main.js\",\n  \"exports\": {\n    \"node\": {\n      \"import\": \"./feature-node.mjs\",\n      \"require\": \"./feature-node.cjs\"\n    },\n    \"default\": \"./feature.mjs\",\n  }\n}\n
\n

Conditions continue to be matched in order as with flat conditions. If\na nested conditional 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.

", "type": "module", "displayName": "Nested conditions" }, { "textRaw": "Resolving user conditions", "name": "resolving_user_conditions", "meta": { "added": [ "v14.9.0", "v12.19.0" ], "changes": [] }, "desc": "

When running Node.js, custom user conditions can be added with the\n--conditions flag:

\n
node --conditions=development main.js\n
\n

which would then resolve the \"development\" condition in package imports and\nexports, while resolving the existing \"node\", \"default\", \"import\", and\n\"require\" conditions as appropriate.

\n

Any number of custom conditions can be set with repeat flags.

", "type": "module", "displayName": "Resolving user conditions" }, { "textRaw": "Conditions Definitions", "name": "conditions_definitions", "desc": "

The \"import\", \"require\", \"node\" and \"default\" conditions are defined\nand implemented in Node.js core,\nas specified above.

\n

Other condition strings are unknown to Node.js and thus ignored by default.\nRuntimes or tools other than Node.js can use them at their discretion.

\n

These user conditions can be enabled in Node.js via the --conditions\nflag.

\n

The following condition definitions are currently endorsed by Node.js:

\n
    \n
  • \"browser\" - any environment which implements a standard subset of global\nbrowser APIs available from JavaScript in web browsers, including the DOM\nAPIs.
  • \n
  • \"development\" - can be used to define a development-only environment\nentry point. Must always be mutually exclusive with \"production\".
  • \n
  • \"production\" - can be used to define a production environment entry\npoint. Must always be mutually exclusive with \"development\".
  • \n
\n

The above user conditions can be enabled in Node.js via the --conditions\nflag.

\n

Platform specific conditions such as \"deno\", \"electron\", or \"react-native\"\nmay be used, but while there remain no implementation or integration intent\nfrom these platforms, the above are not explicitly endorsed by Node.js.

\n

New 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
    \n
  • The definition should be clear and unambiguous for all implementers.
  • \n
  • The use case for why the condition is needed should be clearly justified.
  • \n
  • There should exist sufficient existing implementation usage.
  • \n
  • The condition name should not conflict with another condition definition or\ncondition in wide usage.
  • \n
  • The listing of the condition definition should provide a coordination\nbenefit to the ecosystem that wouldn't otherwise be possible. For example,\nthis would not necessarily be the case for company-specific or\napplication-specific conditions.
  • \n
\n

The above definitions may be moved to a dedicated conditions registry in due\ncourse.

", "type": "module", "displayName": "Conditions Definitions" }, { "textRaw": "Self-referencing a package using its name", "name": "self-referencing_a_package_using_its_name", "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:

\n
// package.json\n{\n  \"name\": \"a-package\",\n  \"exports\": {\n    \".\": \"./main.mjs\",\n    \"./foo\": \"./foo.js\"\n  }\n}\n
\n

Then 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 ./main.mjs.\n
\n

Self-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:

\n
// ./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
\n

Self-referencing is also available when using require, both in an ES module,\nand in a CommonJS one. For example, this code will also work:

\n
// ./a-module.js\nconst { something } = require('a-package/foo'); // Loads from ./foo.js.\n
", "type": "module", "displayName": "Self-referencing a package using its name" } ], "type": "misc", "displayName": "Package entry points" }, { "textRaw": "Dual CommonJS/ES module packages", "name": "dual_commonjs/es_module_packages", "desc": "

Prior to the introduction of support for ES modules in Node.js, it was a common\npattern for package authors to include both CommonJS and ES module JavaScript\nsources in their package, with package.json \"main\" specifying the\nCommonJS entry point and package.json \"module\" specifying the ES module\nentry point.\nThis enabled Node.js to run the CommonJS entry point while build tools such as\nbundlers used the ES module entry point, since Node.js ignored (and still\nignores) the top-level \"module\" field.

\n

Node.js can now run ES module entry points, and a package can contain both\nCommonJS and ES module entry points (either via separate specifiers such as\n'pkg' and 'pkg/es-module', or both at the same specifier via Conditional\nexports). Unlike in the scenario where \"module\" is only used by bundlers,\nor ES module files are transpiled into CommonJS on the fly before evaluation by\nNode.js, the files referenced by the ES module entry point are evaluated as ES\nmodules.

", "modules": [ { "textRaw": "Dual package hazard", "name": "dual_package_hazard", "desc": "

When an application is using a package that provides both CommonJS and ES module\nsources, there is a risk of certain bugs if both versions of the package get\nloaded. This potential comes from the fact that the pkgInstance created by\nconst pkgInstance = require('pkg') is not the same as the pkgInstance\ncreated by import pkgInstance from 'pkg' (or an alternative main path like\n'pkg/module'). This is the “dual package hazard,” where two versions of the\nsame package can be loaded within the same runtime environment. While it is\nunlikely that an application or package would intentionally load both versions\ndirectly, it is common for an application to load one version while a dependency\nof the application loads the other version. This hazard can happen because\nNode.js supports intermixing CommonJS and ES modules, and can lead to unexpected\nbehavior.

\n

If the package main export is a constructor, an instanceof comparison of\ninstances created by the two versions returns false, and if the export is an\nobject, properties added to one (like pkgInstance.foo = 3) are not present on\nthe other. This differs from how import and require statements work in\nall-CommonJS or all-ES module environments, respectively, and therefore is\nsurprising to users. It also differs from the behavior users are familiar with\nwhen using transpilation via tools like Babel or esm.

", "type": "module", "displayName": "Dual package hazard" }, { "textRaw": "Writing dual packages while avoiding or minimizing hazards", "name": "writing_dual_packages_while_avoiding_or_minimizing_hazards", "desc": "

First, the hazard described in the previous section occurs when a package\ncontains both CommonJS and ES module sources and both sources are provided for\nuse in Node.js, either via separate main entry points or exported paths. A\npackage might instead be written where any version of Node.js receives only\nCommonJS sources, and any separate ES module sources the package might contain\nare intended only for other environments such as browsers. Such a package\nwould be usable by any version of Node.js, since import can refer to CommonJS\nfiles; but it would not provide any of the advantages of using ES module syntax.

\n

A package might also switch from CommonJS to ES module syntax in a breaking\nchange version bump. This has the disadvantage that the\nnewest version of the package would only be usable in ES module-supporting\nversions of Node.js.

\n

Every pattern has tradeoffs, but there are two broad approaches that satisfy the\nfollowing conditions:

\n
    \n
  1. The package is usable via both require and import.
  2. \n
  3. The package is usable in both current Node.js and older versions of Node.js\nthat lack support for ES modules.
  4. \n
  5. The package main entry point, e.g. 'pkg' can be used by both require to\nresolve to a CommonJS file and by import to resolve to an ES module file.\n(And likewise for exported paths, e.g. 'pkg/feature'.)
  6. \n
  7. The package provides named exports, e.g. import { name } from 'pkg' rather\nthan import pkg from 'pkg'; pkg.name.
  8. \n
  9. The package is potentially usable in other ES module environments such as\nbrowsers.
  10. \n
  11. The hazards described in the previous section are avoided or minimized.
  12. \n
", "modules": [ { "textRaw": "Approach #1: Use an ES module wrapper", "name": "approach_#1:_use_an_es_module_wrapper", "desc": "

Write the package in CommonJS or transpile ES module sources into CommonJS, and\ncreate an ES module wrapper file that defines the named exports. Using\nConditional exports, the ES module wrapper is used for import and the\nCommonJS entry point for require.

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./wrapper.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
\n

The preceding example uses explicit extensions .mjs and .cjs.\nIf your files use the .js extension, \"type\": \"module\" will cause such files\nto be treated as ES modules, just as \"type\": \"commonjs\" would cause them\nto be treated as CommonJS.\nSee Enabling.

\n
// ./node_modules/pkg/index.cjs\nexports.name = 'value';\n
\n
// ./node_modules/pkg/wrapper.mjs\nimport cjsModule from './index.cjs';\nexport const name = cjsModule.name;\n
\n

In this example, the name from import { name } from 'pkg' is the same\nsingleton as the name from const { name } = require('pkg'). Therefore ===\nreturns true when comparing the two names and the divergent specifier hazard\nis avoided.

\n

If the module is not simply a list of named exports, but rather contains a\nunique function or object export like module.exports = function () { ... },\nor if support in the wrapper for the import pkg from 'pkg' pattern is desired,\nthen the wrapper would instead be written to export the default optionally\nalong with any named exports as well:

\n
import cjsModule from './index.cjs';\nexport const name = cjsModule.name;\nexport default cjsModule;\n
\n

This approach is appropriate for any of the following use cases:

\n
    \n
  • The package is currently written in CommonJS and the author would prefer not\nto refactor it into ES module syntax, but wishes to provide named exports for\nES module consumers.
  • \n
  • The package has other packages that depend on it, and the end user might\ninstall both this package and those other packages. For example a utilities\npackage is used directly in an application, and a utilities-plus package\nadds a few more functions to utilities. Because the wrapper exports\nunderlying CommonJS files, it doesn’t matter if utilities-plus is written in\nCommonJS or ES module syntax; it will work either way.
  • \n
  • The package stores internal state, and the package author would prefer not to\nrefactor the package to isolate its state management. See the next section.
  • \n
\n

A variant of this approach not requiring conditional exports for consumers could\nbe to add an export, e.g. \"./module\", to point to an all-ES module-syntax\nversion of the package. This could be used via import 'pkg/module' by users\nwho are certain that the CommonJS version will not be loaded anywhere in the\napplication, such as by dependencies; or if the CommonJS version can be loaded\nbut doesn’t affect the ES module version (for example, because the package is\nstateless):

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./wrapper.mjs\"\n  }\n}\n
", "type": "module", "displayName": "Approach #1: Use an ES module wrapper" }, { "textRaw": "Approach #2: Isolate state", "name": "approach_#2:_isolate_state", "desc": "

A package.json file can define the separate CommonJS and ES module entry\npoints directly:

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \"import\": \"./index.mjs\",\n    \"require\": \"./index.cjs\"\n  }\n}\n
\n

This can be done if both the CommonJS and ES module versions of the package are\nequivalent, for example because one is the transpiled output of the other; and\nthe package’s management of state is carefully isolated (or the package is\nstateless).

\n

The reason that state is an issue is because both the CommonJS and ES module\nversions of the package might get used within an application; for example, the\nuser’s application code could import the ES module version while a dependency\nrequires the CommonJS version. If that were to occur, two copies of the\npackage would be loaded in memory and therefore two separate states would be\npresent. This would likely cause hard-to-troubleshoot bugs.

\n

Aside from writing a stateless package (if JavaScript’s Math were a package,\nfor example, it would be stateless as all of its methods are static), there are\nsome ways to isolate state so that it’s shared between the potentially loaded\nCommonJS and ES module instances of the package:

\n
    \n
  1. \n

    If possible, contain all state within an instantiated object. JavaScript’s\nDate, for example, needs to be instantiated to contain state; if it were a\npackage, it would be used like this:

    \n
    import Date from 'date';\nconst someDate = new Date();\n// someDate contains state; Date does not\n
    \n

    The new keyword isn’t required; a package’s function can return a new\nobject, or modify a passed-in object, to keep the state external to the\npackage.

    \n
  2. \n
  3. \n

    Isolate the state in one or more CommonJS files that are shared between the\nCommonJS and ES module versions of the package. For example, if the CommonJS\nand ES module entry points are index.cjs and index.mjs, respectively:

    \n
    // ./node_modules/pkg/index.cjs\nconst state = require('./state.cjs');\nmodule.exports.state = state;\n
    \n
    // ./node_modules/pkg/index.mjs\nimport state from './state.cjs';\nexport {\n  state\n};\n
    \n

    Even if pkg is used via both require and import in an application (for\nexample, via import in application code and via require by a dependency)\neach reference of pkg will contain the same state; and modifying that\nstate from either module system will apply to both.

    \n
  4. \n
\n

Any plugins that attach to the package’s singleton would need to separately\nattach to both the CommonJS and ES module singletons.

\n

This approach is appropriate for any of the following use cases:

\n
    \n
  • The package is currently written in ES module syntax and the package author\nwants that version to be used wherever such syntax is supported.
  • \n
  • The package is stateless or its state can be isolated without too much\ndifficulty.
  • \n
  • The package is unlikely to have other public packages that depend on it, or if\nit does, the package is stateless or has state that need not be shared between\ndependencies or with the overall application.
  • \n
\n

Even with isolated state, there is still the cost of possible extra code\nexecution between the CommonJS and ES module versions of a package.

\n

As with the previous approach, a variant of this approach not requiring\nconditional exports for consumers could be to add an export, e.g.\n\"./module\", to point to an all-ES module-syntax version of the package:

\n
// ./node_modules/pkg/package.json\n{\n  \"type\": \"module\",\n  \"main\": \"./index.cjs\",\n  \"exports\": {\n    \".\": \"./index.cjs\",\n    \"./module\": \"./index.mjs\"\n  }\n}\n
", "type": "module", "displayName": "Approach #2: Isolate state" } ], "type": "module", "displayName": "Writing dual packages while avoiding or minimizing hazards" } ], "type": "misc", "displayName": "Dual CommonJS/ES module packages" }, { "textRaw": "Node.js `package.json` field definitions", "name": "node.js_`package.json`_field_definitions", "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.

\n

The following fields in package.json files are used in Node.js:

\n
    \n
  • \"name\" - Relevant when using named imports within a package. Also used\nby package managers as the name of the package.
  • \n
  • \"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.
  • \n
  • \"type\" - The package type determining whether to load .js files as\nCommonJS or ES modules.
  • \n
  • \"exports\" - Package exports and conditional exports. When present,\nlimits which submodules can be loaded from within the package.
  • \n
  • \"imports\" - Package imports, for use by modules within the package\nitself.
  • \n
", "modules": [ { "textRaw": "`\"name\"`", "name": "`\"name\"`", "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": "Remove the `--experimental-resolve-self` option." } ] }, "desc": "\n
{\n  \"name\": \"package-name\"\n}\n
\n

The \"name\" field defines your package’s name. Publishing to the\nnpm registry requires a name that satisfies\ncertain requirements.

\n

The \"name\" field can be used in addition to the \"exports\" field to\nself-reference a package using its name.

", "type": "module", "displayName": "`\"name\"`" }, { "textRaw": "`\"main\"`", "name": "`\"main\"`", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "\n
{\n  \"main\": \"./main.js\"\n}\n
\n

The \"main\" field defines the script that is used when the package directory\nis loaded via require(). Its value\nis a path.

\n
require('./path/to/directory'); // This resolves to ./path/to/directory/main.js.\n
\n

When a package has an \"exports\" field, this will take precedence over the\n\"main\" field when importing the package by name.

", "type": "module", "displayName": "`\"main\"`" }, { "textRaw": "`\"type\"`", "name": "`\"type\"`", "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": "\n

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.

\n

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\".

\n

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.

\n
// 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
\n

If 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.

\n

import statements of .js files are treated as ES modules if the nearest\nparent package.json contains \"type\": \"module\".

\n
// my-app.js, part of the same example as above\nimport './startup.js'; // Loaded as ES module because of package.json\n
\n

Regardless of the value of the \"type\" field, .mjs files are always treated\nas ES modules and .cjs files are always treated as CommonJS.

", "type": "module", "displayName": "`\"type\"`" }, { "textRaw": "`\"exports\"`", "name": "`\"exports\"`", "meta": { "added": [ "v12.7.0" ], "changes": [ { "version": [ "v14.13.0", "v12.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/34718", "description": "Add support for `\"exports\"` patterns." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31008", "description": "Implement logical conditional exports ordering." }, { "version": [ "v13.7.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/31001", "description": "Remove the `--experimental-conditional-exports` option." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29978", "description": "Implement conditional exports." } ] }, "desc": "\n
{\n  \"exports\": \"./index.js\"\n}\n
\n

The \"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.

\n

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.

\n

All paths defined in the \"exports\" must be relative file URLs starting with\n./.

", "type": "module", "displayName": "`\"exports\"`" }, { "textRaw": "`\"imports\"`", "name": "`\"imports\"`", "meta": { "added": [ "v14.6.0", "v12.19.0" ], "changes": [] }, "desc": "\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
\n

Entries in the imports field must be strings starting with #.

\n

Import maps permit mapping to external packages.

\n

This field defines subpath imports for the current package.

", "type": "module", "displayName": "`\"imports\"`" } ], "type": "misc", "displayName": "Node.js `package.json` field definitions" } ], "source": "doc/api/packages.md" }, { "textRaw": "Policies", "name": "policy", "introduced_in": "v11.8.0", "type": "misc", "stability": 1, "stabilityText": "Experimental", "desc": "

Node.js contains experimental support for creating policies on loading code.

\n

Policies are a security feature intended to allow guarantees\nabout what code Node.js is able to load. The use of policies assumes\nsafe practices for the policy files such as ensuring that policy\nfiles cannot be overwritten by the Node.js application by using\nfile permissions.

\n

A best practice would be to ensure that the policy manifest is read-only for\nthe running Node.js application and that the file cannot be changed\nby the running Node.js application in any way. A typical setup would be to\ncreate the policy file as a different user id than the one running Node.js\nand granting read permissions to the user id running Node.js.

", "miscs": [ { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "

The --experimental-policy flag can be used to enable features for policies\nwhen loading modules.

\n

Once this has been set, all modules must conform to a policy manifest file\npassed to the flag:

\n
node --experimental-policy=policy.json app.js\n
\n

The policy manifest will be used to enforce constraints on code loaded by\nNode.js.

\n

To mitigate tampering with policy files on disk, an integrity for\nthe policy file itself may be provided via --policy-integrity.\nThis allows running node and asserting the policy file contents\neven if the file is changed on disk.

\n
node --experimental-policy=policy.json --policy-integrity=\"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\" app.js\n
" }, { "textRaw": "Features", "name": "features", "modules": [ { "textRaw": "Error behavior", "name": "error_behavior", "desc": "

When a policy check fails, Node.js by default will throw an error.\nIt is possible to change the error behavior to one of a few possibilities\nby defining an \"onerror\" field in a policy manifest. The following values are\navailable to change the behavior:

\n
    \n
  • \"exit\": will exit the process immediately.\nNo cleanup code will be allowed to run.
  • \n
  • \"log\": will log the error at the site of the failure.
  • \n
  • \"throw\": will throw a JS error at the site of the failure. This is the\ndefault.
  • \n
\n
{\n  \"onerror\": \"log\",\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
", "type": "module", "displayName": "Error behavior" }, { "textRaw": "Integrity checks", "name": "integrity_checks", "desc": "

Policy files must use integrity checks with Subresource Integrity strings\ncompatible with the browser\nintegrity attribute\nassociated with absolute URLs.

\n

When using require() all resources involved in loading are checked for\nintegrity if a policy manifest has been specified. If a resource does not match\nthe integrity listed in the manifest, an error will be thrown.

\n

An example policy file that would allow loading a file checked.js:

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
\n

Each resource listed in the policy manifest can be of one the following\nformats to determine its location:

\n
    \n
  1. A relative-URL string to a resource from the manifest such as ./resource.js, ../resource.js, or /resource.js.
  2. \n
  3. A complete URL string to a resource such as file:///resource.js.
  4. \n
\n

When loading resources the entire URL must match including search parameters\nand hash fragment. ./a.js?b will not be used when attempting to load\n./a.js and vice versa.

\n

To generate integrity strings, a script such as\nprintf \"sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)\"\ncan be used.

\n

Integrity can be specified as the boolean value true to accept any\nbody for the resource which can be useful for local development. It is not\nrecommended in production since it would allow unexpected alteration of\nresources to be considered valid.

", "type": "module", "displayName": "Integrity checks" }, { "textRaw": "Dependency redirection", "name": "dependency_redirection", "desc": "

An application may need to ship patched versions of modules or to prevent\nmodules from allowing all modules access to all other modules. Redirection\ncan be used by intercepting attempts to load the modules wishing to be\nreplaced.

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"dependencies\": {\n        \"fs\": true,\n        \"os\": \"./app/node_modules/alt-os\",\n        \"http\": { \"import\": true }\n      }\n    }\n  }\n}\n
\n

The dependencies are keyed by the requested specifier string and have values\nof either true, null, a string pointing to a module to be resolved,\nor a conditions object.

\n

The specifier string does not perform any searching and must match exactly\nwhat is provided to the require() or import. Therefore, multiple specifiers\nmay be needed in the policy if it uses multiple different strings to point\nto the same module (such as excluding the extension).

\n

If the value of the redirection is true the default searching algorithms are\nused to find the module.

\n

If the value of the redirection is a string, it is resolved relative to\nthe manifest and then immediately used without searching.

\n

Any specifier string for which resolution is attempted and that is not listed in\nthe dependencies results in an error according to the policy.

\n

Redirection does not prevent access to APIs through means such as direct access\nto require.cache or through module.constructor which allow access to\nloading modules. Policy redirection only affects specifiers to require() and\nimport. Other means, such as to prevent undesired access to APIs through\nvariables, are necessary to lock down that path of loading modules.

\n

A boolean value of true for the dependencies map can be specified to allow a\nmodule to load any specifier without redirection. This can be useful for local\ndevelopment and may have some valid usage in production, but should be used\nonly with care after auditing a module to ensure its behavior is valid.

\n

Similar to \"exports\" in package.json, dependencies can also be specified to\nbe objects containing conditions which branch how dependencies are loaded. In\nthe preceding example, \"http\" is allowed when the \"import\" condition is\npart of loading it.

\n

A value of null for the resolved value causes the resolution to fail. This\ncan be used to ensure some kinds of dynamic access are explicitly prevented.

\n

Unknown values for the resolved module location cause failures but are\nnot guaranteed to be forward compatible.

\n

Example: Patched dependency

\n

Redirected dependencies can provide attenuated or modified functionality as fits\nthe application. For example, log data about timing of function durations by\nwrapping the original:

\n
const original = require('fn');\nmodule.exports = function fn(...args) {\n  console.time();\n  try {\n    return new.target ?\n      Reflect.construct(original, args) :\n      Reflect.apply(original, this, args);\n  } finally {\n    console.timeEnd();\n  }\n};\n
", "type": "module", "displayName": "Dependency redirection" }, { "textRaw": "Scopes", "name": "scopes", "desc": "

Use the \"scopes\" field of a manifest to set configuration for many resources\nat once. The \"scopes\" field works by matching resources by their segments.\nIf a scope or resource includes \"cascade\": true, unknown specifiers will\nbe searched for in their containing scope. The containing scope for cascading\nis found by recursively reducing the resource URL by removing segments for\nspecial schemes, keeping trailing \"/\" suffixes, and removing the query and\nhash fragment. This leads to the eventual reduction of the URL to its origin.\nIf the URL is non-special the scope will be located by the URL's origin. If no\nscope is found for the origin or in the case of opaque origins, a protocol\nstring can be used as a scope.

\n

Note, blob: URLs adopt their origin from the path they contain, and so a scope\nof \"blob:https://nodejs.org\" will have no effect since no URL can have an\norigin of blob:https://nodejs.org; URLs starting with\nblob:https://nodejs.org/ will use https://nodejs.org for its origin and\nthus https: for its protocol scope. For opaque origin blob: URLs they will\nhave blob: for their protocol scope since they do not adopt origins.

", "modules": [ { "textRaw": "Integrity using scopes", "name": "integrity_using_scopes", "desc": "

Setting an integrity to true on a scope will set the integrity for any\nresource not found in the manifest to true.

\n

Setting an integrity to null on a scope will set the integrity for any\nresource not found in the manifest to fail matching.

\n

Not including an integrity is the same as setting the integrity to null.

\n

\"cascade\" for integrity checks will be ignored if \"integrity\" is explicitly\nset.

\n

The following example allows loading any file:

\n
{\n  \"scopes\": {\n    \"file:\": {\n      \"integrity\": true\n    }\n  }\n}\n
", "type": "module", "displayName": "Integrity using scopes" }, { "textRaw": "Dependency redirection using scopes", "name": "dependency_redirection_using_scopes", "desc": "

The following example, would allow access to fs for all resources within\n./app/:

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"cascade\": true,\n      \"integrity\": true\n    }\n  },\n  \"scopes\": {\n    \"./app/\": {\n      \"dependencies\": {\n        \"fs\": true\n      }\n    }\n  }\n}\n
\n

The following example, would allow access to fs for all data: resources:

\n
{\n  \"resources\": {\n    \"data:text/javascript,import('fs');\": {\n      \"cascade\": true,\n      \"integrity\": true\n    }\n  },\n  \"scopes\": {\n    \"data:\": {\n      \"dependencies\": {\n        \"fs\": true\n      }\n    }\n  }\n}\n
", "type": "module", "displayName": "Dependency redirection using scopes" } ], "type": "module", "displayName": "Scopes" } ], "type": "misc", "displayName": "Features" } ], "source": "doc/api/policy.md" }, { "textRaw": "Diagnostic report", "name": "report", "introduced_in": "v11.8.0", "type": "misc", "stability": 2, "stabilityText": "Stable", "desc": "

Delivers a JSON-formatted diagnostic summary, written to a file.

\n

The 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.

\n

A complete example report that was generated on an uncaught exception\nis provided below for reference.

\n
{\n  \"header\": {\n    \"reportVersion\": 1,\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\": 6127616,\n    \"totalCommittedMemory\": 4357352,\n    \"usedMemory\": 3221136,\n    \"availableMemory\": 1521370240,\n    \"memoryLimit\": 1526909922,\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    \"userCpuSeconds\": 0.069595,\n    \"kernelCpuSeconds\": 0.019163,\n    \"cpuConsumptionPercent\": 0.000000,\n    \"maxRss\": 18079744,\n    \"pageFaults\": {\n      \"IORequired\": 0,\n      \"IONotRequired\": 4610\n    },\n    \"fsActivity\": {\n      \"reads\": 0,\n      \"writes\": 0\n    }\n  },\n  \"uvthreadResourceUsage\": {\n    \"userCpuSeconds\": 0.068457,\n    \"kernelCpuSeconds\": 0.019127,\n    \"cpuConsumptionPercent\": 0.000000,\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  \"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_kbytes\": {\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_kbytes\": {\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_kbytes\": {\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", "desc": "
node --report-uncaught-exception --report-on-signal \\\n--report-on-fatalerror app.js\n
\n
    \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.

    \n
  • \n
  • \n

    --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.

    \n
  • \n
\n

Signal based report generation is not supported in Windows.

\n

Under 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.

\n
    \n
  • \n

    --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.

    \n
  • \n
  • \n

    --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.

    \n
  • \n
  • \n

    --report-directory Location at which the report will be\ngenerated.

    \n
  • \n
  • \n

    --report-filename Name of the file to which the report will be\nwritten.

    \n
  • \n
  • \n

    --report-signal Sets or resets the signal for report generation\n(not supported on Windows). Default signal is SIGUSR2.

    \n
  • \n
\n

A report can also be triggered via an API call from a JavaScript application:

\n
process.report.writeReport();\n
\n

This function takes an optional additional argument filename, which is\nthe name of a file into which the report is written.

\n
process.report.writeReport('./foo.json');\n
\n

This 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.

\n
try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(err);\n}\n// Any other code\n
\n

If both filename and error object are passed to writeReport() the\nerror object must be the second parameter.

\n
try {\n  process.chdir('/non-existent-path');\n} catch (err) {\n  process.report.writeReport(filename, err);\n}\n// Any other code\n
\n

The content of the diagnostic report can be returned as a JavaScript Object\nvia an API call from a JavaScript application:

\n
const 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
\n

This 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.

\n
const report = process.report.getReport(new Error('custom error'));\nconsole.log(typeof report === 'object'); // true\n
\n

The 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.

\n

The 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:

\n
$ node\n> process.report.writeReport();\nWriting Node.js report to file: report.20181126.091102.8480.0.001.json\nNode.js report completed\n>\n
\n

When 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.

", "type": "misc", "displayName": "Usage" }, { "textRaw": "Configuration", "name": "configuration", "desc": "

Additional runtime configuration of report generation is available via\nthe following properties of process.report:

\n

reportOnFatalError triggers diagnostic reporting on fatal errors when true.\nDefaults to false.

\n

reportOnSignal triggers diagnostic reporting on signal when true. This is\nnot supported on Windows. Defaults to false.

\n

reportOnUncaughtException triggers diagnostic reporting on uncaught exception\nwhen true. Defaults to false.

\n

signal specifies the POSIX signal identifier that will be used\nto intercept external triggers for report generation. Defaults to\n'SIGUSR2'.

\n

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.

\n

directory specifies the filesystem directory where the report will be written.\nURLs are not supported. Defaults to the current working directory of the\nNode.js process.

\n
// 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

Configuration on module initialization is also available via\nenvironment variables:

\n
NODE_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
\n

Specific API documentation can be found under\nprocess API documentation section.

", "type": "misc", "displayName": "Configuration" }, { "textRaw": "Interaction with workers", "name": "interaction_with_workers", "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": "

Worker threads can create reports in the same way that the main thread\ndoes.

\n

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.

\n

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.

", "type": "misc", "displayName": "Interaction with workers" } ], "source": "doc/api/report.md" } ], "modules": [ { "textRaw": "Usage and example", "name": "usage_and_example", "introduced_in": "v0.10.0", "miscs": [ { "textRaw": "Usage", "name": "Usage", "introduced_in": "v0.10.0", "type": "misc", "desc": "

node [options] [V8 options] [script.js | -e \"script\" | - ] [arguments]

\n

Please see the Command-line options document for more information.

\n

Example

\n

An example of a web server written with Node.js which responds with\n'Hello, World!':

\n

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.

\n

Lines that don’t start with $ or > character show the output of the previous\ncommand.

\n

First, make sure to have downloaded and installed Node.js. See\nInstalling Node.js via package manager for further install information.

\n

Now, create an empty project folder called projects, then navigate into it.

\n

Linux and Mac:

\n
$ mkdir ~/projects\n$ cd ~/projects\n
\n

Windows CMD:

\n
> mkdir %USERPROFILE%\\projects\n> cd %USERPROFILE%\\projects\n
\n

Windows PowerShell:

\n
> mkdir $env:USERPROFILE\\projects\n> cd $env:USERPROFILE\\projects\n
\n

Next, create a new source file in the projects\nfolder and call it hello-world.js.

\n

Open hello-world.js in any preferred text editor and\npaste in the following content:

\n
const http = require('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
\n

Save the file, go back to the terminal window, and enter the following command:

\n
$ node hello-world.js\n
\n

Output like this should appear in the terminal:

\n
Server running at http://127.0.0.1:3000/\n
\n

Now, open any preferred web browser and visit http://127.0.0.1:3000.

\n

If the browser displays the string Hello, World!, that indicates\nthe server is working.

" } ], "type": "module", "displayName": "Usage and example", "source": "doc/api/synopsis.md" }, { "textRaw": "Assert", "name": "assert", "introduced_in": "v0.1.21", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/assert.js

\n

The assert module provides a set of assertion functions for verifying\ninvariants.

", "modules": [ { "textRaw": "Strict assertion mode", "name": "strict_assertion_mode", "meta": { "added": [ "v9.9.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/34001", "description": "Exposed as `require('assert/strict')`." }, { "version": [ "v13.9.0", "v12.16.2" ], "pr-url": "https://github.com/nodejs/node/pull/31635", "description": "Changed \"strict mode\" to \"strict assertion mode\" and \"legacy mode\" to \"legacy assertion mode\" to avoid confusion with the more usual meaning of \"strict mode\"." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17615", "description": "Added error diffs to the strict assertion mode." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17002", "description": "Added strict assertion mode to the assert module." } ] }, "desc": "

In strict assertion mode, non-strict methods behave like their corresponding\nstrict methods. For example, assert.deepEqual() will behave like\nassert.deepStrictEqual().

\n

In strict assertion mode, error messages for objects display a diff. In legacy\nassertion mode, error messages for objects display the objects, often truncated.

\n

To use strict assertion mode:

\n
import { strict as assert } from 'assert';\n
\n
const assert = require('assert').strict;\n
\n
import assert from 'assert/strict';\n
\n
const assert = require('assert/strict');\n
\n

Example error diff:

\n
import { strict as assert } from '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
\n
const assert = require('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
\n

To 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.

", "type": "module", "displayName": "Strict assertion mode" }, { "textRaw": "Legacy assertion mode", "name": "legacy_assertion_mode", "desc": "

Legacy assertion mode uses the Abstract Equality Comparison in:

\n\n

To use legacy assertion mode:

\n
import assert from 'assert';\n
\n
const assert = require('assert');\n
\n

Whenever possible, use the strict assertion mode instead. Otherwise, the\nAbstract Equality Comparison may cause surprising results. This is\nespecially true for assert.deepEqual(), where the comparison rules are\nlax:

\n
// WARNING: This does not throw an AssertionError!\nassert.deepEqual(/a/gi, new Date());\n
", "type": "module", "displayName": "Legacy assertion mode" } ], "classes": [ { "textRaw": "Class: assert.AssertionError", "type": "class", "name": "assert.AssertionError", "desc": "\n

Indicates the failure of an assertion. All errors thrown by the assert module\nwill be instances of the AssertionError class.

", "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`message` {string} If provided, the error message is set to this value.", "name": "message", "type": "string", "desc": "If provided, the error message is set to this value." }, { "textRaw": "`actual` {any} The `actual` property on the error instance.", "name": "actual", "type": "any", "desc": "The `actual` property on the error instance." }, { "textRaw": "`expected` {any} The `expected` property on the error instance.", "name": "expected", "type": "any", "desc": "The `expected` property on the error instance." }, { "textRaw": "`operator` {string} The `operator` property on the error instance.", "name": "operator", "type": "string", "desc": "The `operator` property on the error instance." }, { "textRaw": "`stackStartFn` {Function} If provided, the generated stack trace omits frames before this function.", "name": "stackStartFn", "type": "Function", "desc": "If provided, the generated stack trace omits frames before this function." } ] } ], "desc": "

A subclass of Error that indicates the failure of an assertion.

\n

All instances contain the built-in Error properties (message and name)\nand:

\n
    \n
  • actual <any> Set to the actual argument for methods such as\nassert.strictEqual().
  • \n
  • expected <any> Set to the expected value for methods such as\nassert.strictEqual().
  • \n
  • generatedMessage <boolean> Indicates if the message was auto-generated\n(true) or not.
  • \n
  • code <string> Value is always ERR_ASSERTION to show that the error is an\nassertion error.
  • \n
  • operator <string> Set to the passed in operator value.
  • \n
\n
import assert from '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
\n
const assert = require('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.CallTracker`", "type": "class", "name": "assert.CallTracker", "meta": { "added": [ "v14.2.0", "v12.19.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

This feature is currently experimental and behavior might still change.

", "methods": [ { "textRaw": "`tracker.calls([fn][, exact])`", "type": "method", "name": "calls", "meta": { "added": [ "v14.2.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function} that wraps `fn`.", "name": "return", "type": "Function", "desc": "that wraps `fn`." }, "params": [ { "textRaw": "`fn` {Function} **Default:** A no-op function.", "name": "fn", "type": "Function", "default": "A no-op function" }, { "textRaw": "`exact` {number} **Default:** `1`.", "name": "exact", "type": "number", "default": "`1`" } ] } ], "desc": "

The wrapper function is expected to be called exactly exact times. If the\nfunction has not been called exactly exact times when\ntracker.verify() is called, then tracker.verify() will throw an\nerror.

\n
import assert from 'assert';\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func);\n
\n
const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func);\n
" }, { "textRaw": "`tracker.report()`", "type": "method", "name": "report", "meta": { "added": [ "v14.2.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} of objects containing information about the wrapper functions returned by [`tracker.calls()`][].", "name": "return", "type": "Array", "desc": "of objects containing information about the wrapper functions returned by [`tracker.calls()`][]." }, "params": [ { "textRaw": "Object {Object}", "name": "Object", "type": "Object", "options": [ { "textRaw": "`message` {string}", "name": "message", "type": "string" }, { "textRaw": "`actual` {number} The actual number of times the function was called.", "name": "actual", "type": "number", "desc": "The actual number of times the function was called." }, { "textRaw": "`expected` {number} The number of times the function was expected to be called.", "name": "expected", "type": "number", "desc": "The number of times the function was expected to be called." }, { "textRaw": "`operator` {string} The name of the function that is wrapped.", "name": "operator", "type": "string", "desc": "The name of the function that is wrapped." }, { "textRaw": "`stack` {Object} A stack trace of the function.", "name": "stack", "type": "Object", "desc": "A stack trace of the function." } ] } ] } ], "desc": "

The arrays contains information about the expected and actual number of calls of\nthe functions that have not been called the expected number of times.

\n
import assert from 'assert';\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\nfunction foo() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\n// Returns an array containing information on callsfunc()\ntracker.report();\n// [\n//  {\n//    message: 'Expected the func function to be executed 2 time(s) but was\n//    executed 0 time(s).',\n//    actual: 0,\n//    expected: 2,\n//    operator: 'func',\n//    stack: stack trace\n//  }\n// ]\n
\n
const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\nfunction foo() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\n// Returns an array containing information on callsfunc()\ntracker.report();\n// [\n//  {\n//    message: 'Expected the func function to be executed 2 time(s) but was\n//    executed 0 time(s).',\n//    actual: 0,\n//    expected: 2,\n//    operator: 'func',\n//    stack: stack trace\n//  }\n// ]\n
" }, { "textRaw": "`tracker.verify()`", "type": "method", "name": "verify", "meta": { "added": [ "v14.2.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Iterates through the list of functions passed to\ntracker.calls() and will throw an error for functions that\nhave not been called the expected number of times.

\n
import assert from 'assert';\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\ncallsfunc();\n\n// Will throw an error since callsfunc() was only called once.\ntracker.verify();\n
\n
const assert = require('assert');\n\n// Creates call tracker.\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// Returns a function that wraps func() that must be called exact times\n// before tracker.verify().\nconst callsfunc = tracker.calls(func, 2);\n\ncallsfunc();\n\n// Will throw an error since callsfunc() was only called once.\ntracker.verify();\n
" } ], "signatures": [ { "params": [], "desc": "

Creates a new CallTracker object which can be used to track if functions\nwere called a specific number of times. The tracker.verify() must be called\nfor the verification to take place. The usual pattern would be to call it in a\nprocess.on('exit') handler.

\n
import assert from 'assert';\nimport process from 'process';\n\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// callsfunc() must be called exactly 1 time before tracker.verify().\nconst callsfunc = tracker.calls(func, 1);\n\ncallsfunc();\n\n// Calls tracker.verify() and verifies if all tracker.calls() functions have\n// been called exact times.\nprocess.on('exit', () => {\n  tracker.verify();\n});\n
\n
const assert = require('assert');\n\nconst tracker = new assert.CallTracker();\n\nfunction func() {}\n\n// callsfunc() must be called exactly 1 time before tracker.verify().\nconst callsfunc = tracker.calls(func, 1);\n\ncallsfunc();\n\n// Calls tracker.verify() and verifies if all tracker.calls() functions have\n// been called exact times.\nprocess.on('exit', () => {\n  tracker.verify();\n});\n
" } ] } ], "methods": [ { "textRaw": "`assert(value[, message])`", "type": "method", "name": "assert", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} The input that is checked for being truthy.", "name": "value", "type": "any", "desc": "The input that is checked for being truthy." }, { "textRaw": "`message` {string|Error}", "name": "message", "type": "string|Error" } ] } ], "desc": "

An alias of assert.ok().

" }, { "textRaw": "`assert.deepEqual(actual, expected[, message])`", "type": "method", "name": "deepEqual", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v16.0.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 in case both sides are NaN." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25008", "description": "The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15001", "description": "The `Error` names and messages are now properly compared." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12142", "description": "The `Set` and `Map` content is also compared." }, { "version": [ "v6.4.0", "v4.7.1" ], "pr-url": "https://github.com/nodejs/node/pull/8002", "description": "Typed array slices are handled correctly now." }, { "version": [ "v6.1.0", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6432", "description": "Objects with circular references can be used as inputs now." }, { "version": [ "v5.10.1", "v4.4.3" ], "pr-url": "https://github.com/nodejs/node/pull/5910", "description": "Handle non-`Uint8Array` typed arrays correctly." } ] }, "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" } ] } ], "desc": "

Strict assertion mode

\n

An alias of assert.deepStrictEqual().

\n

Legacy assertion mode

\n
\n

Stability: 3 - Legacy: Use assert.deepStrictEqual() instead.

\n
\n

Tests for deep equality between the actual and expected parameters. Consider\nusing assert.deepStrictEqual() instead. assert.deepEqual() can have\nsurprising results.

\n

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", "desc": "
    \n
  • Primitive values are compared with the Abstract Equality Comparison\n( == ) with the exception of NaN. It is treated as being identical in case\nboth sides are NaN.
  • \n
  • Type tags of objects should be the same.
  • \n
  • Only enumerable \"own\" properties are considered.
  • \n
  • Error names and messages are always compared, even if these are not\nenumerable properties.
  • \n
  • Object wrappers are compared both as objects and unwrapped values.
  • \n
  • Object properties are compared unordered.
  • \n
  • Map keys and Set items are compared unordered.
  • \n
  • Recursion stops when both sides differ or both sides encounter a circular\nreference.
  • \n
  • Implementation does not test the [[Prototype]] of\nobjects.
  • \n
  • Symbol properties are not compared.
  • \n
  • WeakMap and WeakSet comparison does not rely on their values.
  • \n
\n

The following example does not throw an AssertionError because the\nprimitives are considered equal by the Abstract Equality Comparison\n( == ).

\n
import assert from 'assert';\n// WARNING: This does not throw an AssertionError!\n\nassert.deepEqual('+00000000', false);\n
\n
const assert = require('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:

\n
import assert from '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 = Object.create(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
\n
const assert = require('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 = Object.create(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
\n

If 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\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

", "type": "module", "displayName": "Comparison details" } ] }, { "textRaw": "`assert.deepStrictEqual(actual, expected[, message])`", "type": "method", "name": "deepStrictEqual", "meta": { "added": [ "v1.2.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15169", "description": "Enumerable symbol properties are now compared." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15036", "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." }, { "version": "v8.5.0", "pr-url": "https://github.com/nodejs/node/pull/15001", "description": "The `Error` names and messages are now properly compared." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12142", "description": "The `Set` and `Map` content is also compared." }, { "version": [ "v6.4.0", "v4.7.1" ], "pr-url": "https://github.com/nodejs/node/pull/8002", "description": "Typed array slices are handled correctly now." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6432", "description": "Objects with circular references can be used as inputs now." }, { "version": [ "v5.10.1", "v4.4.3" ], "pr-url": "https://github.com/nodejs/node/pull/5910", "description": "Handle non-`Uint8Array` typed arrays correctly." } ] }, "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" } ] } ], "desc": "

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.

", "modules": [ { "textRaw": "Comparison details", "name": "comparison_details", "desc": "\n
import assert from 'assert/strict';\n\n// This fails because 1 !== '1'.\ndeepStrictEqual({ 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 of the SameValue comparison\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 using the SameValue Comparison:\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 weakMap3 = new WeakMap();\nweakMap3.unequal = true;\n\nassert.deepStrictEqual(weakMap1, weakMap2);\n// OK, because it is impossible to compare the entries\n\n// Fails because weakMap3 has a property that weakMap1 does not contain:\nassert.deepStrictEqual(weakMap1, weakMap3);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   WeakMap {\n// +   [items unknown]\n// -   [items unknown],\n// -   unequal: true\n//   }\n
\n
const assert = require('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 of the SameValue comparison\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 using the SameValue Comparison:\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 weakMap3 = new WeakMap();\nweakMap3.unequal = true;\n\nassert.deepStrictEqual(weakMap1, weakMap2);\n// OK, because it is impossible to compare the entries\n\n// Fails because weakMap3 has a property that weakMap1 does not contain:\nassert.deepStrictEqual(weakMap1, weakMap3);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n//   WeakMap {\n// +   [items unknown]\n// -   [items unknown],\n// -   unequal: true\n//   }\n
\n

If 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\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

", "type": "module", "displayName": "Comparison details" } ] }, { "textRaw": "`assert.doesNotMatch(string, regexp[, message])`", "type": "method", "name": "doesNotMatch", "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" } ] } ], "desc": "

Expects the string input not to match the regular expression.

\n
import assert from '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
\n
const assert = require('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
\n

If 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 an Error then it will be thrown instead of the\nAssertionError.

" }, { "textRaw": "`assert.doesNotReject(asyncFn[, error][, message])`", "type": "method", "name": "doesNotReject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`asyncFn` {Function|Promise}", "name": "asyncFn", "type": "Function|Promise" }, { "textRaw": "`error` {RegExp|Function}", "name": "error", "type": "RegExp|Function" }, { "textRaw": "`message` {string}", "name": "message", "type": "string" } ] } ], "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 not rejected.

\n

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.

\n

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.

\n

If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

\n

Besides the async nature to await the completion behaves identically to\nassert.doesNotThrow().

\n\n
import assert from 'assert/strict';\n\nawait assert.doesNotReject(\n  async () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);\n
\n
const assert = require('assert/strict');\n\n(async () => {\n  await assert.doesNotReject(\n    async () => {\n      throw new TypeError('Wrong value');\n    },\n    SyntaxError\n  );\n})();\n
\n\n
import assert from 'assert/strict';\n\nassert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n  .then(() => {\n    // ...\n  });\n
\n\n
const assert = require('assert/strict');\n\nassert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n  .then(() => {\n    // ...\n  });\n
" }, { "textRaw": "`assert.doesNotThrow(fn[, error][, message])`", "type": "method", "name": "doesNotThrow", "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" }, { "textRaw": "`message` {string}", "name": "message", "type": "string" } ] } ], "desc": "

Asserts that the function fn does not throw an error.

\n

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.

\n

When assert.doesNotThrow() is called, it will immediately call the fn\nfunction.

\n

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.

\n

If specified, error can be a Class, RegExp or a validation\nfunction. See assert.throws() for more details.

\n

The following, for instance, will throw the TypeError because there is no\nmatching error type in the assertion:

\n\n
import assert from 'assert/strict';\n\nassert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);\n
\n\n
const assert = require('assert/strict');\n\nassert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);\n
\n

However, the following will result in an AssertionError with the message\n'Got unwanted exception...':

\n\n
import assert from 'assert/strict';\n\nassert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  TypeError\n);\n
\n\n
const assert = require('assert/strict');\n\nassert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  TypeError\n);\n
\n

If an AssertionError is thrown and a value is provided for the message\nparameter, the value of message will be appended to the AssertionError\nmessage:

\n\n
import assert from '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
\n\n
const assert = require('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])`", "type": "method", "name": "equal", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v16.0.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 in case both sides are NaN." } ] }, "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" } ] } ], "desc": "

Strict assertion mode

\n

An alias of assert.strictEqual().

\n

Legacy assertion mode

\n
\n

Stability: 3 - Legacy: Use assert.strictEqual() instead.

\n
\n

Tests shallow, coercive equality between the actual and expected parameters\nusing the Abstract Equality Comparison ( == ). NaN is special handled\nand treated as being identical in case both sides are NaN.

\n
import assert from '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
\n
const assert = require('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
\n

If 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\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

" }, { "textRaw": "`assert.fail([message])`", "type": "method", "name": "fail", "meta": { "added": [ "v0.1.21" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {string|Error} **Default:** `'Failed'`", "name": "message", "type": "string|Error", "default": "`'Failed'`" } ] } ], "desc": "

Throws an AssertionError with the provided error message or a default\nerror message. If the message parameter is an instance of an Error then\nit will be thrown instead of the AssertionError.

\n
import assert from '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
\n
const assert = require('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
\n

Using assert.fail() with more than two arguments is possible but deprecated.\nSee below for further details.

" }, { "textRaw": "`assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`", "type": "method", "name": "fail", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18418", "description": "Calling `assert.fail()` with more than one argument is deprecated and emits a warning." } ] }, "stability": 0, "stabilityText": "Deprecated: Use `assert.fail([message])` or other assert\nfunctions 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" }, { "textRaw": "`operator` {string} **Default:** `'!='`", "name": "operator", "type": "string", "default": "`'!='`" }, { "textRaw": "`stackStartFn` {Function} **Default:** `assert.fail`", "name": "stackStartFn", "type": "Function", "default": "`assert.fail`" } ] } ], "desc": "

If message is falsy, the error message is set as the values of actual and\nexpected separated by the provided operator. If just the two actual and\nexpected arguments are provided, operator will default to '!='. If\nmessage is provided as third argument it will be used as the error message and\nthe other arguments will be stored as properties on the thrown object. If\nstackStartFn is provided, all stack frames above that function will be\nremoved from stacktrace (see Error.captureStackTrace). If no arguments are\ngiven, the default message Failed will be used.

\n
import assert from 'assert/strict';\n\nassert.fail('a', 'b');\n// AssertionError [ERR_ASSERTION]: 'a' != 'b'\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError [ERR_ASSERTION]: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError [ERR_ASSERTION]: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError [ERR_ASSERTION]: whoops\n\nassert.fail(1, 2, new TypeError('need array'));\n// TypeError: need array\n
\n
const assert = require('assert/strict');\n\nassert.fail('a', 'b');\n// AssertionError [ERR_ASSERTION]: 'a' != 'b'\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError [ERR_ASSERTION]: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError [ERR_ASSERTION]: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError [ERR_ASSERTION]: whoops\n\nassert.fail(1, 2, new TypeError('need array'));\n// TypeError: need array\n
\n

In the last three cases actual, expected, and operator have no\ninfluence on the error message.

\n

Example use of stackStartFn for truncating the exception's stacktrace:

\n
import assert from 'assert/strict';\n\nfunction suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError [ERR_ASSERTION]: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
\n
const assert = require('assert/strict');\n\nfunction suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError [ERR_ASSERTION]: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
" }, { "textRaw": "`assert.ifError(value)`", "type": "method", "name": "ifError", "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.

\n
import assert from '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
\n
const assert = require('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])`", "type": "method", "name": "match", "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" } ] } ], "desc": "

Expects the string input to match the regular expression.

\n
import assert from '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
\n
const assert = require('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
\n

If 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 an Error then it will be thrown instead of the\nAssertionError.

" }, { "textRaw": "`assert.notDeepEqual(actual, expected[, message])`", "type": "method", "name": "notDeepEqual", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v16.0.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 in case both sides are NaN." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15001", "description": "The `Error` names and messages are now properly compared." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12142", "description": "The `Set` and `Map` content is also compared." }, { "version": [ "v6.4.0", "v4.7.1" ], "pr-url": "https://github.com/nodejs/node/pull/8002", "description": "Typed array slices are handled correctly now." }, { "version": [ "v6.1.0", "v4.5.0" ], "pr-url": "https://github.com/nodejs/node/pull/6432", "description": "Objects with circular references can be used as inputs now." }, { "version": [ "v5.10.1", "v4.4.3" ], "pr-url": "https://github.com/nodejs/node/pull/5910", "description": "Handle non-`Uint8Array` typed arrays correctly." } ] }, "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" } ] } ], "desc": "

Strict assertion mode

\n

An alias of assert.notDeepStrictEqual().

\n

Legacy assertion mode

\n
\n

Stability: 3 - Legacy: Use assert.notDeepStrictEqual() instead.

\n
\n

Tests for any deep inequality. Opposite of assert.deepEqual().

\n
import assert from '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 = Object.create(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
\n
const assert = require('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 = Object.create(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
\n

If 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 an Error then it will be thrown\ninstead of the AssertionError.

" }, { "textRaw": "`assert.notDeepStrictEqual(actual, expected[, message])`", "type": "method", "name": "notDeepStrictEqual", "meta": { "added": [ "v1.2.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15398", "description": "The `-0` and `+0` are not considered equal anymore." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15036", "description": "The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15001", "description": "The `Error` names and messages are now properly compared." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12142", "description": "The `Set` and `Map` content is also compared." }, { "version": [ "v6.4.0", "v4.7.1" ], "pr-url": "https://github.com/nodejs/node/pull/8002", "description": "Typed array slices are handled correctly now." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6432", "description": "Objects with circular references can be used as inputs now." }, { "version": [ "v5.10.1", "v4.4.3" ], "pr-url": "https://github.com/nodejs/node/pull/5910", "description": "Handle non-`Uint8Array` typed arrays correctly." } ] }, "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" } ] } ], "desc": "

Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

\n
import assert from 'assert/strict';\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n
\n
const assert = require('assert/strict');\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n
\n

If 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 an Error then it will be thrown\ninstead of the AssertionError.

" }, { "textRaw": "`assert.notEqual(actual, expected[, message])`", "type": "method", "name": "notEqual", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v16.0.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 in case both sides are NaN." } ] }, "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" } ] } ], "desc": "

Strict assertion mode

\n

An alias of assert.notStrictEqual().

\n

Legacy assertion mode

\n
\n

Stability: 3 - Legacy: Use assert.notStrictEqual() instead.

\n
\n

Tests shallow, coercive inequality with the Abstract Equality Comparison\n(!= ). NaN is special handled and treated as being identical in case both\nsides are NaN.

\n
import assert from '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
\n
const assert = require('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
\n

If 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\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.

" }, { "textRaw": "`assert.notStrictEqual(actual, expected[, message])`", "type": "method", "name": "notStrictEqual", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17003", "description": "Used comparison changed from Strict Equality to `Object.is()`." } ] }, "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" } ] } ], "desc": "

Tests strict inequality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

\n
import assert from '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
\n
const assert = require('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
\n

If 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 an Error then it will be thrown\ninstead of the AssertionError.

" }, { "textRaw": "`assert.ok(value[, message])`", "type": "method", "name": "ok", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18319", "description": "The `assert.ok()` (no arguments) will now use a predefined error message." } ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`message` {string|Error}", "name": "message", "type": "string|Error" } ] } ], "desc": "

Tests if value is truthy. It is equivalent to\nassert.equal(!!value, true, message).

\n

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\nparameter is an instance of an Error then it will be thrown instead of the\nAssertionError.\nIf no arguments are passed in at all message will be set to the string:\n'No value argument passed to `assert.ok()`'.

\n

Be aware that in the repl the error message will be different to the one\nthrown in a file! See below for further details.

\n
import assert from '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
\n
const assert = require('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
\n
import assert from 'assert/strict';\n\n// Using `assert()` works the same:\nassert(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert(0)\n
\n
const assert = require('assert');\n\n// Using `assert()` works the same:\nassert(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n//   assert(0)\n
" }, { "textRaw": "`assert.rejects(asyncFn[, error][, message])`", "type": "method", "name": "rejects", "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" }, { "textRaw": "`message` {string}", "name": "message", "type": "string" } ] } ], "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.

\n

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.

\n

Besides the async nature to await the completion behaves identically to\nassert.throws().

\n

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.

\n

If specified, message will be the message provided by the AssertionError\nif the asyncFn fails to reject.

\n
import assert from '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
\n
const assert = require('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
\n
import assert from '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
\n
const assert = require('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
\n
import assert from 'assert/strict';\n\nassert.rejects(\n  Promise.reject(new Error('Wrong value')),\n  Error\n).then(() => {\n  // ...\n});\n
\n
const assert = require('assert/strict');\n\nassert.rejects(\n  Promise.reject(new Error('Wrong value')),\n  Error\n).then(() => {\n  // ...\n});\n
\n

error 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.

" }, { "textRaw": "`assert.strictEqual(actual, expected[, message])`", "type": "method", "name": "strictEqual", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17003", "description": "Used comparison changed from Strict Equality to `Object.is()`." } ] }, "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" } ] } ], "desc": "

Tests strict equality between the actual and expected parameters as\ndetermined by the SameValue Comparison.

\n
import assert from '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
\n
const assert = require('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
\n

If 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 an Error then it will be thrown\ninstead of the AssertionError.

" }, { "textRaw": "`assert.throws(fn[, error][, message])`", "type": "method", "name": "throws", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20485", "description": "The `error` parameter can be an object containing regular expressions now." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17584", "description": "The `error` parameter can now be an object as well." }, { "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|Object|Error}", "name": "error", "type": "RegExp|Function|Object|Error" }, { "textRaw": "`message` {string}", "name": "message", "type": "string" } ] } ], "desc": "

Expects the function fn to throw an error.

\n

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.

\n

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.

\n

Custom validation object/error instance:

\n
import assert from '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:\nthrows(\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:\nthrows(\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
\n
const assert = require('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:\nthrows(\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:\nthrows(\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
\n

Validate instanceof using constructor:

\n
import assert from 'assert/strict';\n\nassert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  Error\n);\n
\n
const assert = require('assert/strict');\n\nassert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  Error\n);\n
\n

Validate error message using RegExp:

\n

Using a regular expression runs .toString on the error object, and will\ntherefore also include the error name.

\n
import assert from 'assert/strict';\n\nassert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  /^Error: Wrong value$/\n);\n
\n
const assert = require('assert/strict');\n\nassert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  /^Error: Wrong value$/\n);\n
\n

Custom error validation:

\n

The function must return true to indicate all internal validations passed.\nIt will otherwise fail with an AssertionError.

\n
import assert from '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
\n
const assert = require('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
\n

error 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:

\n\n
import assert from '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
\n\n
const assert = require('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
\n

Due to the confusing error-prone notation, avoid a string as the second\nargument.

" } ], "type": "module", "displayName": "Assert", "source": "doc/api/assert.md" }, { "textRaw": "Asynchronous Context Tracking", "name": "asynchronous_context_tracking", "introduced_in": "v16.4.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/async_hooks.js

", "modules": [ { "textRaw": "Introduction", "name": "introduction", "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.

\n

The AsyncLocalStorage and AsyncResource classes are part of the\nasync_hooks module:

\n
import async_hooks from 'async_hooks';\n
\n
const async_hooks = require('async_hooks');\n
", "type": "module", "displayName": "Introduction" } ], "classes": [ { "textRaw": "Class: `AsyncLocalStorage`", "type": "class", "name": "AsyncLocalStorage", "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.

\n

While you can create your own implementation on top of the async_hooks module,\nAsyncLocalStorage should be preferred as it is a performant and memory safe\nimplementation that involves significant optimizations that are non-obvious to\nimplement.

\n

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.

\n
import http from 'http';\nimport { AsyncLocalStorage } from '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//   1: start\n//   0: finish\n//   1: finish\n
\n
const http = require('http');\nconst { AsyncLocalStorage } = require('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//   1: start\n//   0: finish\n//   1: finish\n
\n

Each instance of AsyncLocalStorage maintains an independent storage context.\nMultiple instances can safely exist simultaneously without risk of interfering\nwith each other data.

", "methods": [ { "textRaw": "`asyncLocalStorage.disable()`", "type": "method", "name": "disable", "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.

\n

When calling asyncLocalStorage.disable(), all current contexts linked to the\ninstance will be exited.

\n

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.

\n

Use this method when the asyncLocalStorage is not in use anymore\nin the current process.

" }, { "textRaw": "`asyncLocalStorage.getStore()`", "type": "method", "name": "getStore", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [] } ], "desc": "

Returns the current store.\nIf called outside of an asynchronous context initialized by\ncalling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it\nreturns undefined.

" }, { "textRaw": "`asyncLocalStorage.enterWith(store)`", "type": "method", "name": "enterWith", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`store` {any}", "name": "store", "type": "any" } ] } ], "desc": "

Transitions into the context for the remainder of the current\nsynchronous execution and then persists the store through any following\nasynchronous calls.

\n

Example:

\n
const 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
\n

This 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.

\n
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])`", "type": "method", "name": "run", "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" } ] } ], "desc": "

Runs a function synchronously within a context and returns its\nreturn value. The store is not accessible outside of the callback function or\nthe asynchronous operations created within the callback.

\n

The optional args are passed to the callback function.

\n

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.

\n

Example:

\n
const store = { id: 2 };\ntry {\n  asyncLocalStorage.run(store, () => {\n    asyncLocalStorage.getStore(); // Returns the store object\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])`", "type": "method", "name": "exit", "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" } ] } ], "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.

\n

The optional args are passed to the callback function.

\n

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.

\n

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
" } ], "modules": [ { "textRaw": "Usage with `async/await`", "name": "usage_with_`async/await`", "desc": "

If, within an async function, only one await call is to run within a context,\nthe following pattern should be used:

\n
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
\n

In 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.

", "type": "module", "displayName": "Usage with `async/await`" }, { "textRaw": "Troubleshooting: Context loss", "name": "troubleshooting:_context_loss", "desc": "

In most cases your application or library code should have no issues with\nAsyncLocalStorage. But in rare cases you may face situations when the\ncurrent store is lost in one of the asynchronous operations. In those cases,\nconsider the following options.

\n

If your code is callback-based, it is enough to promisify it with\nutil.promisify(), so it starts working with native promises.

\n

If you need to keep using 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. To\ndo so, you will need to identify the function call responsible for the\ncontext loss. You can do that by logging the content of\nasyncLocalStorage.getStore() after the calls you suspect are responsible for\nthe loss. When the code logs undefined, the last callback called is probably\nresponsible for the context loss.

", "type": "module", "displayName": "Troubleshooting: Context loss" } ], "signatures": [ { "params": [], "desc": "

Creates a new instance of AsyncLocalStorage. Store is only provided within a\nrun() call or after an enterWith() call.

" } ] }, { "textRaw": "Class: `AsyncResource`", "type": "class", "name": "AsyncResource", "meta": { "changes": [ { "version": "v16.4.0", "pr-url": "https://github.com/nodejs/node/pull/37675", "description": "AsyncResource is now Stable. Previously, it had been Experimental." } ] }, "desc": "

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.

\n

The init hook will trigger when an AsyncResource is instantiated.

\n

The following is an overview of the AsyncResource API.

\n
import { AsyncResource, executionAsyncId } from '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
\n
const { AsyncResource, executionAsyncId } = require('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
", "classMethods": [ { "textRaw": "Static method: `AsyncResource.bind(fn[, type, [thisArg]])`", "type": "classMethod", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "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`." }, { "textRaw": "`thisArg` {any}", "name": "thisArg", "type": "any" } ] } ], "desc": "

Binds the given function to the current execution context.

\n

The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

" } ], "methods": [ { "textRaw": "`asyncResource.bind(fn[, thisArg])`", "type": "method", "name": "bind", "meta": { "added": [ "v14.8.0", "v12.19.0" ], "changes": [ { "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" } ] } ], "desc": "

Binds the given function to execute to this AsyncResource's scope.

\n

The returned function will have an asyncResource property referencing\nthe AsyncResource to which the function is bound.

" }, { "textRaw": "`asyncResource.runInAsyncScope(fn[, thisArg, ...args])`", "type": "method", "name": "runInAsyncScope", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function} The function to call in the execution context of this async resource.", "name": "fn", "type": "Function", "desc": "The function to call in the execution context of this async resource." }, { "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." }, { "textRaw": "`...args` {any} Optional arguments to pass to the function.", "name": "...args", "type": "any", "desc": "Optional arguments to pass to the function." } ] } ], "desc": "

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()`", "type": "method", "name": "emitDestroy", "signatures": [ { "return": { "textRaw": "Returns: {AsyncResource} A reference to `asyncResource`.", "name": "return", "type": "AsyncResource", "desc": "A reference to `asyncResource`." }, "params": [] } ], "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.

" }, { "textRaw": "`asyncResource.asyncId()`", "type": "method", "name": "asyncId", "signatures": [ { "return": { "textRaw": "Returns: {number} The unique `asyncId` assigned to the resource.", "name": "return", "type": "number", "desc": "The unique `asyncId` assigned to the resource." }, "params": [] } ] }, { "textRaw": "`asyncResource.triggerAsyncId()`", "type": "method", "name": "triggerAsyncId", "signatures": [ { "return": { "textRaw": "Returns: {number} The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.", "name": "return", "type": "number", "desc": "The same `triggerAsyncId` that is passed to the `AsyncResource` constructor." }, "params": [] } ], "desc": "

" } ], "modules": [ { "textRaw": "Using `AsyncResource` for a `Worker` thread pool", "name": "using_`asyncresource`_for_a_`worker`_thread_pool", "desc": "

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.

\n

Assuming that the task is adding two numbers, using a file named\ntask_processor.js with the following content:

\n
import { parentPort } from 'worker_threads';\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
\n
const { parentPort } = require('worker_threads');\nparentPort.on('message', (task) => {\n  parentPort.postMessage(task.a + task.b);\n});\n
\n

a Worker pool around it could use the following structure:

\n
import { AsyncResource } from 'async_hooks';\nimport { EventEmitter } from 'events';\nimport path from 'path';\nimport { Worker } from '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_processer.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
\n
const { AsyncResource } = require('async_hooks');\nconst { EventEmitter } = require('events');\nconst path = require('path');\nconst { Worker } = require('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
\n

Without 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.

\n

This pool could be used as follows:

\n
import WorkerPool from './worker_pool.js';\nimport os from 'os';\n\nconst pool = new WorkerPool(os.cpus().length);\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
\n
const WorkerPool = require('./worker_pool.js');\nconst os = require('os');\n\nconst pool = new WorkerPool(os.cpus().length);\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
", "type": "module", "displayName": "Using `AsyncResource` for a `Worker` thread pool" }, { "textRaw": "Integrating `AsyncResource` with `EventEmitter`", "name": "integrating_`asyncresource`_with_`eventemitter`", "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.

\n

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.

\n
import { createServer } from 'http';\nimport { AsyncResource, executionAsyncId } from '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
\n
const { createServer } = require('http');\nconst { AsyncResource, executionAsyncId } = require('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
", "type": "module", "displayName": "Integrating `AsyncResource` with `EventEmitter`" } ], "signatures": [ { "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." } ] } ], "desc": "

Example usage:

\n
class 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
" } ] } ], "type": "module", "displayName": "Asynchronous Context Tracking", "source": "doc/api/async_context.md" }, { "textRaw": "Async hooks", "name": "async_hooks", "introduced_in": "v8.1.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Source Code: lib/async_hooks.js

\n

The async_hooks module provides an API to track asynchronous resources. It\ncan be accessed using:

\n
import async_hooks from 'async_hooks';\n
\n
const async_hooks = require('async_hooks');\n
", "modules": [ { "textRaw": "Terminology", "name": "terminology", "desc": "

An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, for example, 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.

\n

If Workers are used, each thread has an independent async_hooks\ninterface, and each thread will use a new set of async IDs.

", "type": "module", "displayName": "Terminology" }, { "textRaw": "Overview", "name": "overview", "desc": "

Following is a simple overview of the public API.

\n
import async_hooks from '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
\n
const async_hooks = require('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
", "type": "module", "displayName": "Overview" }, { "textRaw": "Promise execution tracking", "name": "promise_execution_tracking", "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.

\n
import { executionAsyncId, triggerAsyncId } from 'async_hooks';\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n
\n
const { executionAsyncId, triggerAsyncId } = require('async_hooks');\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n
\n

Observe 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.

\n

Installing async hooks via async_hooks.createHook enables promise execution\ntracking:

\n
import { createHook, executionAsyncId, triggerAsyncId } from '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
\n
const { createHook, exectionAsyncId, triggerAsyncId } = require('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
\n

In 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.

\n

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.

", "type": "module", "displayName": "Promise execution tracking" }, { "textRaw": "JavaScript embedder API", "name": "javascript_embedder_api", "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.

", "classes": [ { "textRaw": "Class: `AsyncResource`", "type": "class", "name": "AsyncResource", "desc": "

The documentation for this class has moved AsyncResource.

" } ], "type": "module", "displayName": "JavaScript embedder API" } ], "methods": [ { "textRaw": "`async_hooks.createHook(callbacks)`", "type": "method", "name": "createHook", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AsyncHook} Instance used for disabling and enabling hooks", "name": "return", "type": "AsyncHook", "desc": "Instance used for disabling and enabling hooks" }, "params": [ { "textRaw": "`callbacks` {Object} The [Hook Callbacks][] to register", "name": "callbacks", "type": "Object", "desc": "The [Hook Callbacks][] to register", "options": [ { "textRaw": "`init` {Function} The [`init` callback][].", "name": "init", "type": "Function", "desc": "The [`init` callback][]." }, { "textRaw": "`before` {Function} The [`before` callback][].", "name": "before", "type": "Function", "desc": "The [`before` callback][]." }, { "textRaw": "`after` {Function} The [`after` callback][].", "name": "after", "type": "Function", "desc": "The [`after` callback][]." }, { "textRaw": "`destroy` {Function} The [`destroy` callback][].", "name": "destroy", "type": "Function", "desc": "The [`destroy` callback][]." }, { "textRaw": "`promiseResolve` {Function} The [`promiseResolve` callback][].", "name": "promiseResolve", "type": "Function", "desc": "The [`promiseResolve` callback][]." } ] } ] } ], "desc": "

Registers functions to be called for different lifetime events of each async\noperation.

\n

The callbacks init()/before()/after()/destroy() are called for the\nrespective asynchronous event during a resource's lifetime.

\n

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.

\n
import { createHook } from 'async_hooks';\n\nconst asyncHook = createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { }\n});\n
\n
const async_hooks = require('async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { }\n});\n
\n

The callbacks will be inherited via the prototype chain:

\n
class 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
\n

Because 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.

", "modules": [ { "textRaw": "Error handling", "name": "error_handling", "desc": "

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.

\n

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.

", "type": "module", "displayName": "Error handling" }, { "textRaw": "Printing in AsyncHooks callbacks", "name": "printing_in_asynchooks_callbacks", "desc": "

Because printing to the console is an asynchronous operation, console.log()\nwill cause the AsyncHooks callbacks to be called. Using console.log() or\nsimilar asynchronous operations inside an AsyncHooks callback function will thus\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 AsyncHooks recursively because\nit is synchronous.

\n
import { writeFileSync } from 'fs';\nimport { format } from 'util';\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHooks callback\n  writeFileSync('log.out', `${format(...args)}\\n`, { flag: 'a' });\n}\n
\n
const fs = require('fs');\nconst util = require('util');\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHooks callback\n  fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}\n
\n

If an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by AsyncHooks itself. The logging should then be skipped when\nit was the logging itself that caused AsyncHooks callback to call. By\ndoing this the otherwise infinite recursion is broken.

", "type": "module", "displayName": "Printing in AsyncHooks callbacks" } ] } ], "classes": [ { "textRaw": "Class: `AsyncHook`", "type": "class", "name": "AsyncHook", "desc": "

The class AsyncHook exposes an interface for tracking lifetime events\nof asynchronous operations.

", "methods": [ { "textRaw": "`asyncHook.enable()`", "type": "method", "name": "enable", "signatures": [ { "return": { "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", "name": "return", "type": "AsyncHook", "desc": "A reference to `asyncHook`." }, "params": [] } ], "desc": "

Enable the callbacks for a given AsyncHook instance. If no callbacks are\nprovided, enabling is a no-op.

\n

The AsyncHook instance is disabled by default. If the AsyncHook instance\nshould be enabled immediately after creation, the following pattern can be used.

\n
import { createHook } from 'async_hooks';\n\nconst hook = createHook(callbacks).enable();\n
\n
const async_hooks = require('async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n
" }, { "textRaw": "`asyncHook.disable()`", "type": "method", "name": "disable", "signatures": [ { "return": { "textRaw": "Returns: {AsyncHook} A reference to `asyncHook`.", "name": "return", "type": "AsyncHook", "desc": "A reference to `asyncHook`." }, "params": [] } ], "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.

\n

For API consistency disable() also returns the AsyncHook instance.

" }, { "textRaw": "`async_hooks.executionAsyncResource()`", "type": "method", "name": "executionAsyncResource", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} The resource representing the current execution. Useful to store data within the resource.", "name": "return", "type": "Object", "desc": "The resource representing the current execution. Useful to store data within the resource." }, "params": [] } ], "desc": "

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.

\n

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.

\n
import { open } from 'fs';\nimport { executionAsyncId, executionAsyncResource } from '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
\n
const { open } = require('fs');\nconst { executionAsyncId, executionAsyncResource } = require('async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(__filename, 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});\n
\n

This can be used to implement continuation local storage without the\nuse of a tracking Map to store the metadata:

\n
import { createServer } from 'http';\nimport {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook\n} from '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
\n
const { createServer } = require('http');\nconst {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook\n} = require('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()`", "type": "method", "name": "executionAsyncId", "meta": { "added": [ "v8.1.0" ], "changes": [ { "version": "v8.2.0", "pr-url": "https://github.com/nodejs/node/pull/13490", "description": "Renamed from `currentId`." } ] }, "signatures": [ { "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." }, "params": [] } ], "desc": "
import { executionAsyncId } from 'async_hooks';\n\nconsole.log(executionAsyncId());  // 1 - bootstrap\nfs.open(path, 'r', (err, fd) => {\n  console.log(executionAsyncId());  // 6 - open()\n});\n
\n
const async_hooks = require('async_hooks');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});\n
\n

The ID returned from executionAsyncId() is related to execution timing, not\ncausality (which is covered by triggerAsyncId()):

\n
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
\n

Promise contexts may not get precise executionAsyncIds by default.\nSee the section on promise execution tracking.

" }, { "textRaw": "`async_hooks.triggerAsyncId()`", "type": "method", "name": "triggerAsyncId", "signatures": [ { "return": { "textRaw": "Returns: {number} The ID of the resource responsible for calling the callback that is currently being executed.", "name": "return", "type": "number", "desc": "The ID of the resource responsible for calling the callback that is currently being executed." }, "params": [] } ], "desc": "
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
\n

Promise contexts may not get valid triggerAsyncIds by default. See\nthe section on promise execution tracking.

" } ], "modules": [ { "textRaw": "Hook callbacks", "name": "hook_callbacks", "desc": "

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)`", "type": "method", "name": "init", "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.

\n

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.

\n
import { createServer } from 'net';\n\ncreateServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n
\n
require('net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n
\n

Every new resource is assigned an ID that is unique within the scope of the\ncurrent Node.js instance.

", "modules": [ { "textRaw": "`type`", "name": "`type`", "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.

\n
FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,\nHTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,\nSHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,\nTTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,\nRANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject\n
\n

There is also the PROMISE resource type, which is used to track Promise\ninstances and asynchronous work scheduled by them.

\n

Users are able to define their own type when using the public embedder API.

\n

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.

", "type": "module", "displayName": "`type`" }, { "textRaw": "`triggerAsyncId`", "name": "`triggerasyncid`", "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.

\n

The following is a simple demonstration of triggerAsyncId:

\n
import { createHook, executionASyncId } from 'async_hooks';\nimport { stdout } from 'process';\nimport net from 'net';\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
\n
const { createHook, executionAsyncId } = require('async_hooks');\nconst { stdout } = require('process');\nconst net = require('net');\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
\n

Output when hitting the server with nc localhost 8080:

\n
TCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0\n
\n

The TCPSERVERWRAP is the server which receives the connections.

\n

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.

", "type": "module", "displayName": "`triggerAsyncId`" }, { "textRaw": "`resource`", "name": "`resource`", "desc": "

resource is an object that represents the actual async resource that has\nbeen initialized. This can contain useful information that can vary based on\nthe value of type. For instance, for the GETADDRINFOREQWRAP resource type,\nresource provides the host name used when looking up the IP address for the\nhost in net.Server.listen(). The API for accessing this information is\nnot supported, but using the Embedder API, users can provide\nand document their own resource objects. For example, such a resource object\ncould contain the SQL query being executed.

\n

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.

", "type": "module", "displayName": "`resource`" }, { "textRaw": "Asynchronous context example", "name": "asynchronous_context_example", "desc": "

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.

\n
const { 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
\n

Output from only starting the server:

\n
TCPSERVERWRAP(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
\n

As 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.

\n

Only using execution to graph resource allocation results in the following:

\n
  root(1)\n     ^\n     |\nTickObject(6)\n     ^\n     |\n Timeout(7)\n
\n

The 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.

\n

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:

\n
 bootstrap(1)\n     |\n     ˅\nTCPSERVERWRAP(5)\n     |\n     ˅\n TickObject(6)\n     |\n     ˅\n  Timeout(7)\n
", "type": "module", "displayName": "Asynchronous context example" } ] }, { "textRaw": "`before(asyncId)`", "type": "method", "name": "before", "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.

\n

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.

" }, { "textRaw": "`after(asyncId)`", "type": "method", "name": "after", "signatures": [ { "params": [ { "textRaw": "`asyncId` {number}", "name": "asyncId", "type": "number" } ] } ], "desc": "

Called immediately after the callback specified in before is completed.

\n

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.

" }, { "textRaw": "`destroy(asyncId)`", "type": "method", "name": "destroy", "signatures": [ { "params": [ { "textRaw": "`asyncId` {number}", "name": "asyncId", "type": "number" } ] } ], "desc": "

Called after the resource corresponding to asyncId is destroyed. It is also\ncalled asynchronously from the embedder API emitDestroy().

\n

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.

" }, { "textRaw": "`promiseResolve(asyncId)`", "type": "method", "name": "promiseResolve", "meta": { "added": [ "v8.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`asyncId` {number}", "name": "asyncId", "type": "number" } ] } ], "desc": "

Called when the resolve function passed to the Promise constructor is\ninvoked (either directly or through other means of resolving a promise).

\n

resolve() does not do any observable synchronous work.

\n

The Promise is not necessarily fulfilled or rejected at this point if the\nPromise was resolved by assuming the state of another Promise.

\n
new Promise((resolve) => resolve(true)).then((a) => {});\n
\n

calls the following callbacks:

\n
init 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
" } ], "type": "module", "displayName": "Hook callbacks" } ] }, { "textRaw": "Class: `AsyncLocalStorage`", "type": "class", "name": "AsyncLocalStorage", "desc": "

The documentation for this class has moved AsyncLocalStorage.

" } ], "type": "module", "displayName": "Async hooks", "source": "doc/api/async_hooks.md" }, { "textRaw": "Buffer", "name": "buffer", "introduced_in": "v0.1.90", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/buffer.js

\n

Buffer objects are used to represent a fixed-length sequence of bytes. Many\nNode.js APIs support Buffers.

\n

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 Uint8Arrays wherever Buffers are supported as well.

\n

While the Buffer class is available within the global scope, it is still\nrecommended to explicitly reference it via an import or require statement.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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", "meta": { "changes": [ { "version": "v15.7.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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

Node.js buffers accept all case variations of encoding strings that they\nreceive. For example, UTF-8 can be specified as 'utf8', 'UTF8' or 'uTf8'.

\n

The character encodings currently supported by Node.js are the following:

\n
    \n
  • \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.

    \n
  • \n
  • \n

    '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.

    \n
  • \n
  • \n

    '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.

    \n
  • \n
\n

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.

\n

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.

\n
    \n
  • \n

    '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.

    \n
  • \n
  • \n

    '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.

    \n
  • \n
  • \n

    'hex': Encode each byte as two hexadecimal characters. Data truncation\nmay occur when decoding strings that do exclusively contain valid hexadecimal\ncharacters. See below for an example.

    \n
  • \n
\n

The following legacy character encodings are also supported:

\n
    \n
  • \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.

    \n
  • \n
  • \n

    'binary': Alias for 'latin1'. See binary strings for more background\non this topic. The 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.

    \n
  • \n
  • \n

    '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.

    \n
  • \n
\n
import { Buffer } from 'buffer';\n\nBuffer.from('1ag', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7g', '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
\n
const { Buffer } = require('buffer');\n\nBuffer.from('1ag', 'hex');\n// Prints <Buffer 1a>, data truncated when first non-hexadecimal value\n// ('g') encountered.\n\nBuffer.from('1a7g', '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
\n

Modern 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.

", "type": "module", "displayName": "Buffers and character encodings" }, { "textRaw": "Buffers and TypedArrays", "name": "buffers_and_typedarrays", "meta": { "changes": [ { "version": "v3.0.0", "pr-url": "https://github.com/nodejs/node/pull/2002", "description": "The `Buffer`s class now inherits from `Uint8Array`." } ] }, "desc": "

Buffer instances are also JavaScript Uint8Array and TypedArray\ninstances. All TypedArray methods are available on Buffers. There are,\nhowever, subtle incompatibilities between the Buffer API and the\nTypedArray API.

\n

In particular:

\n\n

There are two ways to create new TypedArray instances from a Buffer:

\n
    \n
  • Passing a Buffer to a TypedArray constructor will copy the Buffers\ncontents, interpreted as an array of integers, and not as a byte sequence\nof the target type.
  • \n
\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n
    \n
  • Passing the Buffers underlying ArrayBuffer will create a\nTypedArray that shares its memory with the Buffer.
  • \n
\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

It 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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

When creating a Buffer using a TypedArray's .buffer, it is\npossible to use only a portion of the underlying ArrayBuffer by passing in\nbyteOffset and length parameters.

\n
import { Buffer } from 'buffer';\n\nconst arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n
\n
const { Buffer } = require('buffer');\n\nconst arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\nconsole.log(buf.length);\n// Prints: 16\n
\n

The 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:

\n
    \n
  • TypedArray.from(source[, mapFn[, thisArg]])
  • \n
\n

The Buffer.from() method, however, does not support the use of a mapping\nfunction:

\n", "type": "module", "displayName": "Buffers and TypedArrays" }, { "textRaw": "Buffers and iteration", "name": "buffers_and_iteration", "desc": "

Buffer instances can be iterated over using for..of syntax:

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

Additionally, the buf.values(), buf.keys(), and\nbuf.entries() methods can be used to create iterators.

", "type": "module", "displayName": "Buffers and iteration" }, { "textRaw": "`buffer` module APIs", "name": "`buffer`_module_apis", "desc": "

While, the Buffer object is available as a global, there are additional\nBuffer-related APIs that are available only via the buffer module\naccessed using require('buffer').

", "methods": [ { "textRaw": "`buffer.atob(data)`", "type": "method", "name": "atob", "meta": { "added": [ "v15.13.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use `Buffer.from(data, 'base64')` instead.", "signatures": [ { "params": [ { "textRaw": "`data` {any} The Base64-encoded input string.", "name": "data", "type": "any", "desc": "The Base64-encoded input string." } ] } ], "desc": "

Decodes a string of Base64-encoded data into bytes, and encodes those bytes\ninto a string using Latin-1 (ISO-8859-1).

\n

The data may be any JavaScript-value that can be coerced into a string.

\n

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').

" }, { "textRaw": "`buffer.btoa(data)`", "type": "method", "name": "btoa", "meta": { "added": [ "v15.13.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.

\n

The data may be any JavaScript-value that can be coerced into a string.

\n

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').

" }, { "textRaw": "`buffer.resolveObjectURL(id)`", "type": "method", "name": "resolveObjectURL", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {Blob}", "name": "return", "type": "Blob" }, "params": [ { "textRaw": "`id` {string} A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.", "name": "id", "type": "string", "desc": "A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`." } ] } ], "desc": "

Resolves a 'blob:nodedata:...' an associated <Blob> object registered using\na prior call to URL.createObjectURL().

" }, { "textRaw": "`buffer.transcode(source, fromEnc, toEnc)`", "type": "method", "name": "transcode", "meta": { "added": [ "v7.1.0" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10236", "description": "The `source` parameter can now be a `Uint8Array`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`source` {Buffer|Uint8Array} A `Buffer` or `Uint8Array` instance.", "name": "source", "type": "Buffer|Uint8Array", "desc": "A `Buffer` or `Uint8Array` instance." }, { "textRaw": "`fromEnc` {string} The current encoding.", "name": "fromEnc", "type": "string", "desc": "The current encoding." }, { "textRaw": "`toEnc` {string} To target encoding.", "name": "toEnc", "type": "string", "desc": "To target encoding." } ] } ], "desc": "

Re-encodes the given Buffer or Uint8Array instance from one character\nencoding to another. Returns a new Buffer instance.

\n

Throws if the fromEnc or toEnc specify invalid character encodings or if\nconversion from fromEnc to toEnc is not permitted.

\n

Encodings supported by buffer.transcode() are: 'ascii', 'utf8',\n'utf16le', 'ucs2', 'latin1', and 'binary'.

\n

The transcoding process will use substitution characters if a given byte\nsequence cannot be adequately represented in the target encoding. For instance:

\n
import { Buffer, transcode } from 'buffer';\n\nconst newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n
\n
const { Buffer, transcode } = require('buffer');\n\nconst newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n
\n

Because the Euro () sign is not representable in US-ASCII, it is replaced\nwith ? in the transcoded Buffer.

" } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` {integer} **Default:** `50`", "type": "integer", "name": "INSPECT_MAX_BYTES", "meta": { "added": [ "v0.5.4" ], "changes": [] }, "default": "`50`", "desc": "

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.

" }, { "textRaw": "`kMaxLength` {integer} The largest size allowed for a single `Buffer` instance.", "type": "integer", "name": "kMaxLength", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "desc": "

An alias for buffer.constants.MAX_LENGTH.

", "shortDesc": "The largest size allowed for a single `Buffer` instance." }, { "textRaw": "`kStringMaxLength` {integer} The largest length allowed for a single `string` instance.", "type": "integer", "name": "kStringMaxLength", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "desc": "

An alias for buffer.constants.MAX_STRING_LENGTH.

", "shortDesc": "The largest length allowed for a single `string` instance." } ], "classes": [ { "textRaw": "Class: `SlowBuffer`", "type": "class", "name": "SlowBuffer", "meta": { "deprecated": [ "v6.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.", "desc": "

See Buffer.allocUnsafeSlow(). This was never a class in the sense that\nthe constructor always returned a Buffer instance, rather than a SlowBuffer\ninstance.

", "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `SlowBuffer`.", "name": "size", "type": "integer", "desc": "The desired length of the new `SlowBuffer`." } ], "desc": "

See Buffer.allocUnsafeSlow().

" } ] } ], "modules": [ { "textRaw": "Buffer constants", "name": "buffer_constants", "meta": { "added": [ "v8.2.0" ], "changes": [] }, "properties": [ { "textRaw": "`MAX_LENGTH` {integer} The largest size allowed for a single `Buffer` instance.", "type": "integer", "name": "MAX_LENGTH", "meta": { "added": [ "v8.2.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35415", "description": "Value is changed to 232 on 64-bit architectures." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/32116", "description": "Value is changed from 231 - 1 to 232 - 1 on 64-bit architectures." } ] }, "desc": "

On 32-bit architectures, this value currently is 230 - 1 (about 1\nGB).

\n

On 64-bit architectures, this value currently is 232 (about 4 GB).

\n

It reflects v8::TypedArray::kMaxLength under the hood.

\n

This value is also available as buffer.kMaxLength.

", "shortDesc": "The largest size allowed for a single `Buffer` instance." }, { "textRaw": "`MAX_STRING_LENGTH` {integer} The largest length allowed for a single `string` instance.", "type": "integer", "name": "MAX_STRING_LENGTH", "meta": { "added": [ "v8.2.0" ], "changes": [] }, "desc": "

Represents the largest length that a string primitive can have, counted\nin UTF-16 code units.

\n

This value may depend on the JS engine that is being used.

", "shortDesc": "The largest length allowed for a single `string` instance." } ], "type": "module", "displayName": "Buffer constants" } ], "type": "module", "displayName": "`buffer` module APIs" }, { "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", "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:

\n
    \n
  • Passing a number as the first argument to 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.
  • \n
  • Passing a string, array, or Buffer as the first argument copies the\npassed object's data into the Buffer.
  • \n
  • Passing an ArrayBuffer or a SharedArrayBuffer returns a Buffer\nthat shares allocated memory with the given array buffer.
  • \n
\n

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.

\n

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.

\n

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.

\n

Developers should migrate all existing uses of the new Buffer() constructors\nto one of these new APIs.

\n\n

Buffer instances returned by Buffer.allocUnsafe() and\nBuffer.from(array) may be allocated off a shared internal memory pool\nif size is less than or equal to half Buffer.poolSize. Instances\nreturned by Buffer.allocUnsafeSlow() never use the shared internal\nmemory pool.

", "modules": [ { "textRaw": "The `--zero-fill-buffers` command-line option", "name": "the_`--zero-fill-buffers`_command-line_option", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "desc": "

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(),\nBuffer.allocUnsafeSlow(), and new SlowBuffer(size) are not zero-filled.\nUse of this flag can have a measurable negative impact on performance. Use the\n--zero-fill-buffers option only when necessary to enforce that newly allocated\nBuffer instances cannot contain old data that is potentially sensitive.

\n
$ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n
", "type": "module", "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\"?", "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.

\n

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.

", "type": "module", "displayName": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?" } ], "type": "module", "displayName": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`" } ], "classes": [ { "textRaw": "Class: `Blob`", "type": "class", "name": "Blob", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

A Blob encapsulates immutable, raw data that can be safely shared across\nmultiple worker threads.

", "methods": [ { "textRaw": "`blob.arrayBuffer()`", "type": "method", "name": "arrayBuffer", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [] } ], "desc": "

Returns a promise that fulfills with an <ArrayBuffer> containing a copy of\nthe Blob data.

" }, { "textRaw": "`blob.slice([start, [end, [type]]])`", "type": "method", "name": "slice", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`start` {number} The starting index.", "name": "start", "type": "number", "desc": "The starting index." }, { "textRaw": "`end` {number} The ending index.", "name": "end", "type": "number", "desc": "The ending index." }, { "textRaw": "`type` {string} The content-type for the new `Blob`", "name": "type", "type": "string", "desc": "The content-type for the new `Blob`" } ] } ], "desc": "

Creates and returns a new Blob containing a subset of this Blob objects\ndata. The original Blob is not altered.

" }, { "textRaw": "`blob.stream()`", "type": "method", "name": "stream", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ReadableStream}", "name": "return", "type": "ReadableStream" }, "params": [] } ], "desc": "

Returns a new ReadableStream that allows the content of the Blob to be read.

" }, { "textRaw": "`blob.text()`", "type": "method", "name": "text", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [] } ], "desc": "

Returns a promise that fulfills with the contents of the Blob decoded as a\nUTF-8 string.

" } ], "properties": [ { "textRaw": "`blob.size`", "name": "size", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "

The total size of the Blob in bytes.

" }, { "textRaw": "`type` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "

The content-type of the Blob.

" } ], "modules": [ { "textRaw": "`Blob` objects and `MessageChannel`", "name": "`blob`_objects_and_`messagechannel`", "desc": "

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.

\n
import { Blob, Buffer } from 'buffer';\nimport { setTimeout as delay } from '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.\ndata.text().then(console.log);\n
\n
const { Blob, Buffer } = require('buffer');\nconst { setTimeout: delay } = require('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.\ndata.text().then(console.log);\n
", "type": "module", "displayName": "`Blob` objects and `MessageChannel`" } ], "signatures": [ { "params": [ { "textRaw": "`sources` {string[]|ArrayBuffer[]|TypedArray[]|DataView[]|Blob[]} An array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, or any mix of such objects, that will be stored within the `Blob`.", "name": "sources", "type": "string[]|ArrayBuffer[]|TypedArray[]|DataView[]|Blob[]", "desc": "An array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, or any mix of such objects, that will be stored within the `Blob`." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`endings` {string} One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to the platform native line-ending as specified by `require('os').EOL`.", "name": "endings", "type": "string", "desc": "One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to the platform native line-ending as specified by `require('os').EOL`." }, { "textRaw": "`type` {string} The Blob content-type. The intent is for `type` to convey the MIME media type of the data, however no validation of the type format is performed.", "name": "type", "type": "string", "desc": "The Blob content-type. The intent is for `type` to convey the MIME media type of the data, however no validation of the type format is performed." } ] } ], "desc": "

Creates a new Blob object containing a concatenation of the given sources.

\n

<ArrayBuffer>, <TypedArray>, <DataView>, and <Buffer> sources are copied into\nthe 'Blob' and can therefore be safely modified after the 'Blob' is created.

\n

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.

" } ] }, { "textRaw": "Class: `Buffer`", "type": "class", "name": "Buffer", "desc": "

The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.

", "classMethods": [ { "textRaw": "Static method: `Buffer.alloc(size[, fill[, encoding]])`", "type": "classMethod", "name": "alloc", "meta": { "added": [ "v5.10.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/34682", "description": "Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments." }, { "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 `fill` triggers a thrown exception." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17428", "description": "Specifying an invalid string for `fill` now results in a zero-filled buffer." } ] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`.", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." }, { "textRaw": "`fill` {string|Buffer|Uint8Array|integer} A value to pre-fill the new `Buffer` with. **Default:** `0`.", "name": "fill", "type": "string|Buffer|Uint8Array|integer", "default": "`0`", "desc": "A value to pre-fill the new `Buffer` with." }, { "textRaw": "`encoding` {string} If `fill` is a string, this is its encoding. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "If `fill` is a string, this is its encoding." } ] } ], "desc": "

Allocates a new Buffer of size bytes. If fill is undefined, the\nBuffer will be zero-filled.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n
\n
const { Buffer } = require('buffer');\n\nconst buf = Buffer.alloc(5);\n\nconsole.log(buf);\n// Prints: <Buffer 00 00 00 00 00>\n
\n

If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_ARG_VALUE\nis thrown.

\n

If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill).

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n
\n
const { Buffer } = require('buffer');\n\nconst buf = Buffer.alloc(5, 'a');\n\nconsole.log(buf);\n// Prints: <Buffer 61 61 61 61 61>\n
\n

If both fill and encoding are specified, the allocated Buffer will be\ninitialized by calling buf.fill(fill, encoding).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

Calling 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.

\n

A TypeError will be thrown if size is not a number.

" }, { "textRaw": "Static method: `Buffer.allocUnsafe(size)`", "type": "classMethod", "name": "allocUnsafe", "meta": { "added": [ "v5.10.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/34682", "description": "Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7079", "description": "Passing a negative `size` will now throw an error." } ] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`.", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ] } ], "desc": "

Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_ARG_VALUE\nis thrown.

\n

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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if size is not a number.

\n

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(),\nBuffer.from(array), Buffer.concat(), and the deprecated\nnew Buffer(size) constructor only when size is less than or equal\nto Buffer.poolSize >> 1 (floor of Buffer.poolSize divided by two).

\n

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.

" }, { "textRaw": "Static method: `Buffer.allocUnsafeSlow(size)`", "type": "classMethod", "name": "allocUnsafeSlow", "meta": { "added": [ "v5.12.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/34682", "description": "Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments." } ] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`.", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ] } ], "desc": "

Allocates a new Buffer of size bytes. If size is larger than\nbuffer.constants.MAX_LENGTH or smaller than 0, ERR_INVALID_ARG_VALUE\nis thrown. A zero-length Buffer is created if size is 0.

\n

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.

\n

When using Buffer.allocUnsafe() to allocate new Buffer instances,\nallocations under 4 KB are sliced from a single pre-allocated Buffer. This\nallows applications to avoid the garbage collection overhead of creating many\nindividually allocated Buffer instances. This approach improves both\nperformance and memory usage by eliminating the need to track and clean up as\nmany individual ArrayBuffer objects.

\n

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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if size is not a number.

" }, { "textRaw": "Static method: `Buffer.byteLength(string[, encoding])`", "type": "classMethod", "name": "byteLength", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/8946", "description": "Passing invalid input will now throw an error." }, { "version": "v5.10.0", "pr-url": "https://github.com/nodejs/node/pull/5255", "description": "The `string` parameter can now be any `TypedArray`, `DataView` or `ArrayBuffer`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} The number of bytes contained within `string`.", "name": "return", "type": "integer", "desc": "The number of bytes contained within `string`." }, "params": [ { "textRaw": "`string` {string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer} A value to calculate the length of.", "name": "string", "type": "string|Buffer|TypedArray|DataView|ArrayBuffer|SharedArrayBuffer", "desc": "A value to calculate the length of." }, { "textRaw": "`encoding` {string} If `string` is a string, this is its encoding. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "If `string` is a string, this is its encoding." } ] } ], "desc": "

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.

\n

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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

When string is a Buffer/DataView/TypedArray/ArrayBuffer/\nSharedArrayBuffer, the byte length as reported by .byteLength\nis returned.

" }, { "textRaw": "Static method: `Buffer.compare(buf1, buf2)`", "type": "classMethod", "name": "compare", "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": [ { "return": { "textRaw": "Returns: {integer} Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details.", "name": "return", "type": "integer", "desc": "Either `-1`, `0`, or `1`, depending on the result of the comparison. See [`buf.compare()`][] for details." }, "params": [ { "textRaw": "`buf1` {Buffer|Uint8Array}", "name": "buf1", "type": "Buffer|Uint8Array" }, { "textRaw": "`buf2` {Buffer|Uint8Array}", "name": "buf2", "type": "Buffer|Uint8Array" } ] } ], "desc": "

Compares buf1 to buf2, typically for the purpose of sorting arrays of\nBuffer instances. This is equivalent to calling\nbuf1.compare(buf2).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "classMethod", "name": "concat", "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": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "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." } ] } ], "desc": "

Returns a new Buffer which is the result of concatenating all the Buffer\ninstances in the list together.

\n

If the list has no items, or if the totalLength is 0, then a new zero-length\nBuffer is returned.

\n

If totalLength is not provided, it is calculated from the Buffer instances\nin list by adding their lengths.

\n

If totalLength is provided, it is coerced to an unsigned integer. If the\ncombined length of the Buffers in list exceeds totalLength, the result is\ntruncated to totalLength.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

Buffer.concat() may also use the internal Buffer pool like\nBuffer.allocUnsafe() does.

" }, { "textRaw": "Static method: `Buffer.from(array)`", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`array` {integer[]}", "name": "array", "type": "integer[]" } ] } ], "desc": "

Allocates a new Buffer using an array of bytes in the range 0255.\nArray entries outside that range will be truncated to fit into it.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if array is not an Array or another type\nappropriate for Buffer.from() variants.

\n

Buffer.from(array) and Buffer.from(string) may also use the internal\nBuffer pool like Buffer.allocUnsafe() does.

" }, { "textRaw": "Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][].", "name": "arrayBuffer", "type": "ArrayBuffer|SharedArrayBuffer", "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][], for example the `.buffer` property of a [`TypedArray`][]." }, { "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", "name": "byteOffset", "type": "integer", "default": "`0`", "desc": "Index of first byte to expose." }, { "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", "name": "length", "type": "integer", "default": "`arrayBuffer.byteLength - byteOffset`", "desc": "Number of bytes to expose." } ] } ], "desc": "

This creates a view of the ArrayBuffer without copying the underlying\nmemory. For example, when passed a reference to the .buffer property of a\nTypedArray instance, the newly created Buffer will share the same\nallocated memory as the TypedArray's underlying ArrayBuffer.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

\n
import { Buffer } from 'buffer';\n\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n
\n
const { Buffer } = require('buffer');\n\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\nconsole.log(buf.length);\n// Prints: 2\n
\n

A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a\nSharedArrayBuffer or another type appropriate for Buffer.from()\nvariants.

\n

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:

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "classMethod", "name": "from", "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." } ] } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if buffer is not a Buffer or another type\nappropriate for Buffer.from() variants.

" }, { "textRaw": "Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`", "type": "classMethod", "name": "from", "meta": { "added": [ "v8.2.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`object` {Object} An object supporting `Symbol.toPrimitive` or `valueOf()`.", "name": "object", "type": "Object", "desc": "An object supporting `Symbol.toPrimitive` or `valueOf()`." }, { "textRaw": "`offsetOrEncoding` {integer|string} A byte-offset or encoding.", "name": "offsetOrEncoding", "type": "integer|string", "desc": "A byte-offset or encoding." }, { "textRaw": "`length` {integer} A length.", "name": "length", "type": "integer", "desc": "A length." } ] } ], "desc": "

For objects whose valueOf() function returns a value not strictly equal to\nobject, returns Buffer.from(object.valueOf(), offsetOrEncoding, length).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

For objects that support Symbol.toPrimitive, returns\nBuffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if object does not have the mentioned methods or\nis not of another type appropriate for Buffer.from() variants.

" }, { "textRaw": "Static method: `Buffer.from(string[, encoding])`", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`string` {string} A string to encode.", "name": "string", "type": "string", "desc": "A string to encode." }, { "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "The encoding of `string`." } ] } ], "desc": "

Creates a new Buffer containing string. The encoding parameter identifies\nthe character encoding to be used when converting string into bytes.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

A TypeError will be thrown if string is not a string or another type\nappropriate for Buffer.from() variants.

" }, { "textRaw": "Static method: `Buffer.isBuffer(obj)`", "type": "classMethod", "name": "isBuffer", "meta": { "added": [ "v0.1.101" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`obj` {Object}", "name": "obj", "type": "Object" } ] } ], "desc": "

Returns true if obj is a Buffer, false otherwise.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "classMethod", "name": "isEncoding", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`encoding` {string} A character encoding name to check.", "name": "encoding", "type": "string", "desc": "A character encoding name to check." } ] } ], "desc": "

Returns true if encoding is the name of a supported character encoding,\nor false otherwise.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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": "`poolSize` {integer} **Default:** `8192`", "type": "integer", "name": "poolSize", "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.

" }, { "textRaw": "`[index]` `index` {integer}", "type": "integer", "name": "index", "desc": "

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).

\n

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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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": "`buffer` {ArrayBuffer} The underlying `ArrayBuffer` object based on which this `Buffer` object is created.", "type": "ArrayBuffer", "name": "buffer", "desc": "

This ArrayBuffer is not guaranteed to correspond exactly to the original\nBuffer. See the notes on buf.byteOffset for details.

\n
import { Buffer } from 'buffer';\n\nconst arrayBuffer = new ArrayBuffer(16);\nconst buffer = Buffer.from(arrayBuffer);\n\nconsole.log(buffer.buffer === arrayBuffer);\n// Prints: true\n
\n
const { Buffer } = require('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": "`byteOffset` {integer} The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.", "type": "integer", "name": "byteOffset", "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.

\n

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.

\n

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:

\n
import { Buffer } from 'buffer';\n\n// Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = new 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
\n
const { Buffer } = require('buffer');\n\n// Create a buffer smaller than `Buffer.poolSize`.\nconst nodeBuffer = new 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": "`length` {integer}", "type": "integer", "name": "length", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

Returns the number of bytes in buf.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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", "meta": { "deprecated": [ "v8.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`buf.buffer`][] instead.", "desc": "

The buf.parent property is a deprecated alias for buf.buffer.

" } ], "methods": [ { "textRaw": "`buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`", "type": "method", "name": "compare", "meta": { "added": [ "v0.11.13" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10236", "description": "The `target` parameter can now be a `Uint8Array`." }, { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/5880", "description": "Additional parameters for specifying offsets are supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [ { "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] with which to compare `buf`.", "name": "target", "type": "Buffer|Uint8Array", "desc": "A `Buffer` or [`Uint8Array`][] with which to compare `buf`." }, { "textRaw": "`targetStart` {integer} The offset within `target` at which to begin comparison. **Default:** `0`.", "name": "targetStart", "type": "integer", "default": "`0`", "desc": "The offset within `target` at which to begin comparison." }, { "textRaw": "`targetEnd` {integer} The offset within `target` at which to end comparison (not inclusive). **Default:** `target.length`.", "name": "targetEnd", "type": "integer", "default": "`target.length`", "desc": "The offset within `target` at which to end comparison (not inclusive)." }, { "textRaw": "`sourceStart` {integer} The offset within `buf` at which to begin comparison. **Default:** `0`.", "name": "sourceStart", "type": "integer", "default": "`0`", "desc": "The offset within `buf` at which to begin comparison." }, { "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to end comparison (not inclusive). **Default:** [`buf.length`][].", "name": "sourceEnd", "type": "integer", "default": "[`buf.length`][]", "desc": "The offset within `buf` at which to end comparison (not inclusive)." } ] } ], "desc": "

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.

\n
    \n
  • 0 is returned if target is the same as buf
  • \n
  • 1 is returned if target should come before buf when sorted.
  • \n
  • -1 is returned if target should come after buf when sorted.
  • \n
\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

The optional targetStart, targetEnd, sourceStart, and sourceEnd\narguments can be used to limit the comparison to specific ranges within target\nand buf respectively.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

ERR_OUT_OF_RANGE is thrown if targetStart < 0, sourceStart < 0,\ntargetEnd > target.byteLength, or sourceEnd > source.byteLength.

" }, { "textRaw": "`buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`", "type": "method", "name": "copy", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} The number of bytes copied.", "name": "return", "type": "integer", "desc": "The number of bytes copied." }, "params": [ { "textRaw": "`target` {Buffer|Uint8Array} A `Buffer` or [`Uint8Array`][] to copy into.", "name": "target", "type": "Buffer|Uint8Array", "desc": "A `Buffer` or [`Uint8Array`][] to copy into." }, { "textRaw": "`targetStart` {integer} The offset within `target` at which to begin writing. **Default:** `0`.", "name": "targetStart", "type": "integer", "default": "`0`", "desc": "The offset within `target` at which to begin writing." }, { "textRaw": "`sourceStart` {integer} The offset within `buf` from which to begin copying. **Default:** `0`.", "name": "sourceStart", "type": "integer", "default": "`0`", "desc": "The offset within `buf` from which to begin copying." }, { "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to stop copying (not inclusive). **Default:** [`buf.length`][].", "name": "sourceEnd", "type": "integer", "default": "[`buf.length`][]", "desc": "The offset within `buf` at which to stop copying (not inclusive)." } ] } ], "desc": "

Copies data from a region of buf to a region in target, even if the target\nmemory region overlaps with buf.

\n

TypedArray.prototype.set() performs the same operation, and is available\nfor all TypedArrays, including Node.js Buffers, although it takes\ndifferent function arguments.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n
import { Buffer } from '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
\n
const { Buffer } = require('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()`", "type": "method", "name": "entries", "meta": { "added": [ "v1.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Creates and returns an iterator of [index, byte] pairs from the contents\nof buf.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "equals", "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": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "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`." } ] } ], "desc": "

Returns true if both buf and otherBuffer have exactly the same bytes,\nfalse otherwise. Equivalent to\nbuf.compare(otherBuffer) === 0.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "fill", "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": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`.", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [ { "textRaw": "`value` {string|Buffer|Uint8Array|integer} The value with which to fill `buf`.", "name": "value", "type": "string|Buffer|Uint8Array|integer", "desc": "The value with which to fill `buf`." }, { "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`." }, { "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)." }, { "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." } ] } ], "desc": "

Fills buf with the specified value. If the offset and end are not given,\nthe entire buf will be filled:

\n
import { Buffer } from '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
const { Buffer } = require('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

value 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.

\n

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:

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

If value contains invalid characters, it is truncated; if no valid\nfill data remains, an exception is thrown:

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "includes", "meta": { "added": [ "v5.3.0" ], "changes": [] }, "signatures": [ { "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." }, "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`." }, { "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." } ] } ], "desc": "

Equivalent to buf.indexOf() !== -1.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "indexOf", "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": [ { "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`." }, "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`." }, { "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`." } ] } ], "desc": "

If value is:

\n
    \n
  • a string, value is interpreted according to the character encoding in\nencoding.
  • \n
  • a Buffer or Uint8Array, value will be used in its entirety.\nTo compare a partial Buffer, use buf.slice().
  • \n
  • a number, value will be interpreted as an unsigned 8-bit integer\nvalue between 0 and 255.
  • \n
\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

If 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.

\n

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().

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

If 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.

" }, { "textRaw": "`buf.keys()`", "type": "method", "name": "keys", "meta": { "added": [ "v1.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Creates and returns an iterator of buf keys (indices).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "lastIndexOf", "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": [ { "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`." }, "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`." }, { "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`." } ] } ], "desc": "

Identical to buf.indexOf(), except the last occurrence of value is found\nrather than the first occurrence.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

If 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.

\n

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().

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

If value is an empty string or empty Buffer, byteOffset will be returned.

" }, { "textRaw": "`buf.readBigInt64BE([offset])`", "type": "method", "name": "readBigInt64BE", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "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`." } ] } ], "desc": "

Reads a signed, big-endian 64-bit integer from buf at the specified offset.

\n

Integers read from a Buffer are interpreted as two's complement signed\nvalues.

" }, { "textRaw": "`buf.readBigInt64LE([offset])`", "type": "method", "name": "readBigInt64LE", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "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`." } ] } ], "desc": "

Reads a signed, little-endian 64-bit integer from buf at the specified\noffset.

\n

Integers read from a Buffer are interpreted as two's complement signed\nvalues.

" }, { "textRaw": "`buf.readBigUInt64BE([offset])`", "type": "method", "name": "readBigUInt64BE", "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.readBigUint64BE()`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "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`." } ] } ], "desc": "

Reads an unsigned, big-endian 64-bit integer from buf at the specified\noffset.

\n

This function is also available under the readBigUint64BE alias.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64BE(0));\n// Prints: 4294967295n\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "readBigUInt64LE", "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": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "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`." } ] } ], "desc": "

Reads an unsigned, little-endian 64-bit integer from buf at the specified\noffset.

\n

This function is also available under the readBigUint64LE alias.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);\n\nconsole.log(buf.readBigUInt64LE(0));\n// Prints: 18446744069414584320n\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "readDoubleBE", "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": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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`." } ] } ], "desc": "

Reads a 64-bit, big-endian double from buf at the specified offset.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readDoubleLE", "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": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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`." } ] } ], "desc": "

Reads a 64-bit, little-endian double from buf at the specified offset.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readFloatBE", "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": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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`." } ] } ], "desc": "

Reads a 32-bit, big-endian float from buf at the specified offset.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([1, 2, 3, 4]);\n\nconsole.log(buf.readFloatBE(0));\n// Prints: 2.387939260590663e-38\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "readFloatLE", "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": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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`." } ] } ], "desc": "

Reads a 32-bit, little-endian float from buf at the specified offset.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readInt8", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads a signed 8-bit integer from buf at the specified offset.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readInt16BE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads a signed, big-endian 16-bit integer from buf at the specified offset.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n
\n
const { Buffer } = require('buffer');\n\nconst buf = Buffer.from([0, 5]);\n\nconsole.log(buf.readInt16BE(0));\n// Prints: 5\n
" }, { "textRaw": "`buf.readInt16LE([offset])`", "type": "method", "name": "readInt16LE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads a signed, little-endian 16-bit integer from buf at the specified\noffset.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readInt32BE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads a signed, big-endian 32-bit integer from buf at the specified offset.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n
\n
const { Buffer } = require('buffer');\n\nconst buf = Buffer.from([0, 0, 0, 5]);\n\nconsole.log(buf.readInt32BE(0));\n// Prints: 5\n
" }, { "textRaw": "`buf.readInt32LE([offset])`", "type": "method", "name": "readInt32LE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads a signed, little-endian 32-bit integer from buf at the specified\noffset.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "readIntBE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "readIntLE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readUInt8", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads an unsigned 8-bit integer from buf at the specified offset.

\n

This function is also available under the readUint8 alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readUInt16BE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads an unsigned, big-endian 16-bit integer from buf at the specified\noffset.

\n

This function is also available under the readUint16BE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readUInt16LE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads an unsigned, little-endian 16-bit integer from buf at the specified\noffset.

\n

This function is also available under the readUint16LE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "readUInt32BE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads an unsigned, big-endian 32-bit integer from buf at the specified\noffset.

\n

This function is also available under the readUint32BE alias.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\nconsole.log(buf.readUInt32BE(0).toString(16));\n// Prints: 12345678\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "readUInt32LE", "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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "desc": "

Reads an unsigned, little-endian 32-bit integer from buf at the specified\noffset.

\n

This function is also available under the readUint32LE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "readUIntBE", "meta": { "added": [ "v0.11.15" ], "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.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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "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.

\n

This function is also available under the readUintBE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "readUIntLE", "meta": { "added": [ "v0.11.15" ], "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.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": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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`." } ] } ], "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.

\n

This function is also available under the readUintLE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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]])`", "type": "method", "name": "subarray", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "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." }, { "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)." } ] } ], "desc": "

Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

\n

Specifying end greater than buf.length will return the same result as\nthat of end equal to buf.length.

\n

This method is inherited from TypedArray.prototype.subarray().

\n

Modifying the new Buffer slice will modify the memory in the original Buffer\nbecause the allocated memory of the two objects overlap.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

Specifying negative indexes causes the slice to be generated relative to the\nend of buf rather than the beginning.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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]])`", "type": "method", "name": "slice", "meta": { "added": [ "v0.3.0" ], "changes": [ { "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." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "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." }, { "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)." } ] } ], "desc": "

Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

\n

This is the same behavior as buf.subarray().

\n

This method is not compatible with the Uint8Array.prototype.slice(),\nwhich is a superclass of Buffer. To copy the slice, use\nUint8Array.prototype.slice().

\n
import { Buffer } from '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
const { Buffer } = require('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
" }, { "textRaw": "`buf.swap16()`", "type": "method", "name": "swap16", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`.", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

One convenient use of buf.swap16() is to perform a fast in-place conversion\nbetween UTF-16 little-endian and UTF-16 big-endian:

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.from('This is little-endian UTF-16', 'utf16le');\nbuf.swap16(); // Convert to big-endian UTF-16 text.\n
\n
const { Buffer } = require('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()`", "type": "method", "name": "swap32", "meta": { "added": [ "v5.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`.", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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()`", "type": "method", "name": "swap64", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`.", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v0.9.2" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns a JSON representation of buf. JSON.stringify() implicitly calls\nthis function when stringifying a Buffer instance.

\n

Buffer.from() accepts objects in the format returned from this method.\nIn particular, Buffer.from(buf.toJSON()) works like Buffer.from(buf).

\n
import { Buffer } from '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
\n
const { Buffer } = require('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]]])`", "type": "method", "name": "toString", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`encoding` {string} The character encoding to use. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "The character encoding to use." }, { "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." }, { "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)." } ] } ], "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.

\n

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.

\n

The maximum length of a string instance (in UTF-16 code units) is available\nas buffer.constants.MAX_STRING_LENGTH.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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()`", "type": "method", "name": "values", "meta": { "added": [ "v1.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} Number of bytes written.", "name": "return", "type": "integer", "desc": "Number of bytes written." }, "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`." }, { "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`)." }, { "textRaw": "`encoding` {string} The character encoding of `string`. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "The character encoding of `string`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeBigInt64BE", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as big-endian.

\n

value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeBigInt64LE", "meta": { "added": [ "v12.0.0", "v10.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as little-endian.

\n

value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeBigUInt64BE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as big-endian.

\n

This function is also available under the writeBigUint64BE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeBigUInt64LE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as little-endian

\n
import { Buffer } from '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
\n
const { Buffer } = require('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
\n

This function is also available under the writeBigUint64LE alias.

" }, { "textRaw": "`buf.writeDoubleBE(value[, offset])`", "type": "method", "name": "writeDoubleBE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeDoubleLE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeFloatBE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as big-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 4f 4a fe bb>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeFloatLE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "desc": "

Writes value to buf at the specified offset as little-endian. Behavior is\nundefined when value is anything other than a JavaScript number.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n// Prints: <Buffer bb fe 4a 4f>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeInt8", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeInt16BE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

The value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16BE(0x0102, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeInt16LE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

The value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt16LE(0x0304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 04 03>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeInt32BE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

The value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32BE(0x01020304, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 01 02 03 04>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeInt32LE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

The value is interpreted and written as a two's complement signed integer.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt32LE(0x05060708, 0);\n\nconsole.log(buf);\n// Prints: <Buffer 08 07 06 05>\n
\n
const { Buffer } = require('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)`", "type": "method", "name": "writeIntBE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "writeIntLE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeUInt8", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUint8 alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeUInt16BE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUint16BE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeUInt16LE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUint16LE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeUInt32BE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUint32BE alias.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer fe ed fa ce>\n
\n
const { Buffer } = require('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])`", "type": "method", "name": "writeUInt32LE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUint32LE alias.

\n
import { Buffer } from 'buffer';\n\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n// Prints: <Buffer ce fa ed fe>\n
\n
const { Buffer } = require('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)`", "type": "method", "name": "writeUIntBE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUintBE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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)`", "type": "method", "name": "writeUIntLE", "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": [ { "return": { "textRaw": "Returns: {integer} `offset` plus the number of bytes written.", "name": "return", "type": "integer", "desc": "`offset` plus the number of bytes written." }, "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`." } ] } ], "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.

\n

This function is also available under the writeUintLE alias.

\n
import { Buffer } from '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
\n
const { Buffer } = require('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": [ { "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).

" }, { "params": [ { "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].", "name": "arrayBuffer", "type": "ArrayBuffer|SharedArrayBuffer", "desc": "An [`ArrayBuffer`][], [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][]." }, { "textRaw": "`byteOffset` {integer} Index of first byte to expose. **Default:** `0`.", "name": "byteOffset", "type": "integer", "default": "`0`", "desc": "Index of first byte to expose." }, { "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.byteLength - byteOffset`.", "name": "length", "type": "integer", "default": "`arrayBuffer.byteLength - byteOffset`", "desc": "Number of bytes to expose." } ], "desc": "

See\nBuffer.from(arrayBuffer[, byteOffset[, length]]).

" }, { "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." } ], "desc": "

See Buffer.from(buffer).

" }, { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`.", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ], "desc": "

See Buffer.alloc() and Buffer.allocUnsafe(). This variant of the\nconstructor is equivalent to Buffer.alloc().

" }, { "params": [ { "textRaw": "`string` {string} String to encode.", "name": "string", "type": "string", "desc": "String to encode." }, { "textRaw": "`encoding` {string} The encoding of `string`. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "The encoding of `string`." } ], "desc": "

See Buffer.from(string[, encoding]).

" } ] } ], "type": "module", "displayName": "Buffer", "source": "doc/api/buffer.md" }, { "textRaw": "C++ embedder API", "name": "c++_embedder_api", "introduced_in": "v12.19.0", "desc": "

Node.js provides a number of C++ APIs that can be used to execute JavaScript\nin a Node.js environment from other C++ software.

\n

The 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.

\n

Because 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.

\n

Example embedding application

\n

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.

\n

The full code can be found in the Node.js source tree.

", "modules": [ { "textRaw": "Setting up per-process state", "name": "setting_up_per-process_state", "desc": "

Node.js requires some per-process state management in order to run:

\n
    \n
  • Arguments parsing for Node.js CLI options,
  • \n
  • V8 per-process requirements, such as a v8::Platform instance.
  • \n
\n

The following example shows how these can be set up. Some class names are from\nthe node and v8 C++ namespaces, respectively.

\n
int main(int argc, char** argv) {\n  argv = uv_setup_args(argc, argv);\n  std::vector<std::string> args(argv, argv + argc);\n  std::vector<std::string> exec_args;\n  std::vector<std::string> errors;\n  // Parse Node.js CLI options, and print any errors that have occurred while\n  // trying to parse them.\n  int exit_code = node::InitializeNodeWithArgs(&args, &exec_args, &errors);\n  for (const std::string& error : errors)\n    fprintf(stderr, \"%s: %s\\n\", args[0].c_str(), error.c_str());\n  if (exit_code != 0) {\n    return 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(platform.get(), args, exec_args);\n\n  V8::Dispose();\n  V8::ShutdownPlatform();\n  return ret;\n}\n
", "type": "module", "displayName": "Setting up per-process state" }, { "textRaw": "Per-instance state", "name": "per-instance_state", "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:

\n
    \n
  • Exactly one v8::Isolate, i.e. one JS Engine instance,
  • \n
  • Exactly one uv_loop_t, i.e. one event loop, and
  • \n
  • A number of v8::Contexts, but exactly one main v8::Context.
  • \n
  • One node::IsolateData instance that contains information that could be\nshared by multiple node::Environments that use the same v8::Isolate.\nCurrently, no testing if performed for this scenario.
  • \n
\n

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().

\n

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.

\n

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.

\n
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    // 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('module').createRequire(process.cwd() + '/');\"\n        \"globalThis.require = publicRequire;\"\n        \"require('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
", "type": "module", "displayName": "Per-instance state" } ], "type": "module", "displayName": "C++ embedder API", "source": "doc/api/embedding.md" }, { "textRaw": "Child process", "name": "child_process", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/child_process.js

\n

The 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:

\n
const { spawn } = require('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
\n

By 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.

\n

The command lookup is performed using the options.env.PATH environment\nvariable if it is in the options object. Otherwise, process.env.PATH is\nused.

\n

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.

\n

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.

\n

For convenience, the child_process module provides a handful of synchronous\nand 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().

\n\n

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", "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.

\n

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.

\n

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.

", "modules": [ { "textRaw": "Spawning `.bat` and `.cmd` files on Windows", "name": "spawning_`.bat`_and_`.cmd`_files_on_windows", "desc": "

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 using\nchild_process.spawn() with the shell option set, with\nchild_process.exec(), or by spawning cmd.exe and passing the .bat or\n.cmd file as an argument (which is what the shell option and\nchild_process.exec() do). In any case, if the script filename contains\nspaces it needs to be quoted.

\n
// On Windows Only...\nconst { spawn } = require('child_process');\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\nbat.stdout.on('data', (data) => {\n  console.log(data.toString());\n});\n\nbat.stderr.on('data', (data) => {\n  console.error(data.toString());\n});\n\nbat.on('exit', (code) => {\n  console.log(`Child exited with code ${code}`);\n});\n
\n
// OR...\nconst { exec, spawn } = require('child_process');\nexec('my.bat', (err, stdout, stderr) => {\n  if (err) {\n    console.error(err);\n    return;\n  }\n  console.log(stdout);\n});\n\n// Script with spaces in the filename:\nconst bat = spawn('\"my script.cmd\"', ['a', 'b'], { shell: true });\n// or:\nexec('\"my script.cmd\" a b', (err, stdout, stderr) => {\n  // ...\n});\n
", "type": "module", "displayName": "Spawning `.bat` and `.cmd` files on Windows" } ], "methods": [ { "textRaw": "`child_process.exec(command[, options][, callback])`", "type": "method", "name": "exec", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v16.4.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": [ { "return": { "textRaw": "Returns: {ChildProcess}", "name": "return", "type": "ChildProcess" }, "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." } ] }, { "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" } ] } ] } ], "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:

\n
const { exec } = require('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
\n

Never pass unsanitized user input to this function. Any input containing shell\nmetacharacters may be used to trigger arbitrary command execution.

\n

If 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.

\n

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.

\n
const { exec } = require('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
\n

If timeout is greater than 0, the parent will send the signal\nidentified by the killSignal property (the default is 'SIGTERM') if the\nchild runs longer than timeout milliseconds.

\n

Unlike the exec(3) POSIX system call, child_process.exec() does not replace\nthe existing process and uses a shell to execute the command.

\n

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.

\n
const util = require('util');\nconst exec = util.promisify(require('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
\n

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:

\n
const { exec } = require('child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = exec('grep ssh', { signal }, (error) => {\n  console.log(error); // an AbortError\n});\ncontroller.abort();\n
" }, { "textRaw": "`child_process.execFile(file[, args][, options][, callback])`", "type": "method", "name": "execFile", "meta": { "added": [ "v0.1.91" ], "changes": [ { "version": "v16.4.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": [ { "return": { "textRaw": "Returns: {ChildProcess}", "name": "return", "type": "ChildProcess" }, "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." }, { "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." } ] }, { "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" } ] } ] } ], "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().

\n

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.

\n
const { execFile } = require('child_process');\nconst child = execFile('node', ['--version'], (error, stdout, stderr) => {\n  if (error) {\n    throw error;\n  }\n  console.log(stdout);\n});\n
\n

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.

\n

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.

\n
const util = require('util');\nconst execFile = util.promisify(require('child_process').execFile);\nasync function getVersion() {\n  const { stdout } = await execFile('node', ['--version']);\n  console.log(stdout);\n}\ngetVersion();\n
\n

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.

\n

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:

\n
const { execFile } = require('child_process');\nconst controller = new AbortController();\nconst { signal } = controller;\nconst child = execFile('node', ['--version'], { signal }, (error) => {\n  console.log(error); // an AbortError\n});\ncontroller.abort();\n
" }, { "textRaw": "`child_process.fork(modulePath[, args][, options])`", "type": "method", "name": "fork", "meta": { "added": [ "v0.5.0" ], "changes": [ { "version": "v16.4.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", "pr-url": "https://github.com/nodejs/node/pull/37256", "description": "timeout was added." }, { "version": "v15.11.0", "pr-url": "https://github.com/nodejs/node/pull/37325", "description": "killSignal for AbortSignal was added." }, { "version": "v15.6.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": [ { "return": { "textRaw": "Returns: {ChildProcess}", "name": "return", "type": "ChildProcess" }, "params": [ { "textRaw": "`modulePath` {string} The module to run in the child.", "name": "modulePath", "type": "string", "desc": "The module to run in the child." }, { "textRaw": "`args` {string[]} List of string arguments.", "name": "args", "type": "string[]", "desc": "List of string arguments." }, { "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 to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", "name": "detached", "type": "boolean", "desc": "Prepare child 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 will be piped to the parent, otherwise they will be inherited from the parent, 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 will be piped to the parent, otherwise they will be inherited from the parent, 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." } ] } ] } ], "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.

\n

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.

\n

By 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.

\n

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.

\n

Unlike the fork(2) POSIX system call, child_process.fork() does not clone the\ncurrent process.

\n

The shell option available in child_process.spawn() is not supported by\nchild_process.fork() and will be ignored if set.

\n

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:

\n
if (process.argv[2] === 'child') {\n  setTimeout(() => {\n    console.log(`Hello from ${process.argv[2]}!`);\n  }, 1_000);\n} else {\n  const { fork } = require('child_process');\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
" }, { "textRaw": "`child_process.spawn(command[, args][, options])`", "type": "method", "name": "spawn", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v16.4.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", "pr-url": "https://github.com/nodejs/node/pull/37256", "description": "timeout was added." }, { "version": "v15.11.0", "pr-url": "https://github.com/nodejs/node/pull/37325", "description": "killSignal for AbortSignal was added." }, { "version": "v15.5.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": [ { "return": { "textRaw": "Returns: {ChildProcess}", "name": "return", "type": "ChildProcess" }, "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." }, { "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`][`stdio`]).", "name": "stdio", "type": "Array|string", "desc": "Child's stdio configuration (see [`options.stdio`][`stdio`])." }, { "textRaw": "`detached` {boolean} Prepare child to run independently of its parent process. Specific behavior depends on the platform, see [`options.detached`][]).", "name": "detached", "type": "boolean", "desc": "Prepare child 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." } ] } ] } ], "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.

\n

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.

\n

A third argument may be used to specify additional options, with these defaults:

\n
const defaults = {\n  cwd: undefined,\n  env: process.env\n};\n
\n

Use 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.

\n

Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.

\n

undefined values in env will be ignored.

\n

Example of running ls -lh /usr, capturing stdout, stderr, and the\nexit code:

\n
const { spawn } = require('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
\n

Example: A very elaborate way to run ps ax | grep ssh

\n
const { spawn } = require('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
\n

Example of checking for failed spawn:

\n
const { spawn } = require('child_process');\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n  console.error('Failed to start subprocess.');\n});\n
\n

Certain platforms (macOS, Linux) will use the value of argv[0] for the process\ntitle while others (Windows, SunOS) will use command.

\n

Node.js currently 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.

\n

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:

\n
const { spawn } = require('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", "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 will have\nits own console window. Once enabled for a child process, it cannot be\ndisabled.

\n

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.

\n

By default, the parent will wait for the detached child to exit. To prevent the\nparent 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 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.

\n

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's stdio is inherited, the child will remain attached to the\ncontrolling terminal.

\n

Example of a long-running process, by detaching and also ignoring its parent\nstdio file descriptors, in order to ignore the parent's termination:

\n
const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
\n

Alternatively one can redirect the child process' output into files:

\n
const fs = require('fs');\nconst { spawn } = require('child_process');\nconst out = fs.openSync('./out.log', 'a');\nconst err = fs.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", "meta": { "added": [ "v0.7.10" ], "changes": [ { "version": "v15.6.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'].

\n

For convenience, options.stdio may be one of the following strings:

\n
    \n
  • 'pipe': equivalent to ['pipe', 'pipe', 'pipe'] (the default)
  • \n
  • 'overlapped': equivalent to ['overlapped', 'overlapped', 'overlapped']
  • \n
  • 'ignore': equivalent to ['ignore', 'ignore', 'ignore']
  • \n
  • 'inherit': equivalent to ['inherit', 'inherit', 'inherit'] or [0, 1, 2]
  • \n
\n

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:

\n
    \n
  1. \n

    '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.

    \n
  2. \n
  3. \n

    '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.

    \n
  4. \n
  5. \n

    '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 is a Node.js process, the\npresence of an IPC channel will enable process.send() and\nprocess.disconnect() methods, as well as 'disconnect' and\n'message' events within the child.

    \n

    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.

    \n
  6. \n
  7. \n

    '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.

    \n
  8. \n
  9. \n

    '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'.

    \n
  10. \n
  11. \n

    <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 until the 'open' event has\noccurred).

    \n
  12. \n
  13. \n

    Positive integer: The integer value is interpreted as a file descriptor\nthat is currently 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.

    \n
  14. \n
  15. \n

    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'.

    \n
  16. \n
\n
const { spawn } = require('child_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
\n

It is worth noting that when an IPC channel is established between the\nparent and child processes, and the child is a Node.js process, the child\nis launched with the IPC channel unreferenced (using unref()) until the\nchild registers an event handler for the 'disconnect' event\nor the 'message' event. This allows the child to exit\nnormally without the process being held open by the open IPC channel.

\n

On Unix-like operating systems, the child_process.spawn() method\nperforms memory operations synchronously before decoupling the event loop\nfrom the child. Applications with a large memory footprint may find frequent\nchild_process.spawn() calls to be a bottleneck. For more information,\nsee V8 issue 7381.

\n

See also: child_process.exec() and child_process.fork().

" } ] } ], "type": "module", "displayName": "Asynchronous process creation" }, { "textRaw": "Synchronous process creation", "name": "synchronous_process_creation", "desc": "

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.

\n

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])`", "type": "method", "name": "execFileSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v16.4.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": [ { "return": { "textRaw": "Returns: {Buffer|string} The stdout from the command.", "name": "return", "type": "Buffer|string", "desc": "The stdout from the command." }, "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." }, { "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. 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. Supplying this value will override `stdio[0]`." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. `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. `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][]." } ] } ] } ], "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.

\n

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.

\n

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().

\n

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.

" }, { "textRaw": "`child_process.execSync(command[, options])`", "type": "method", "name": "execSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v16.4.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": [ { "return": { "textRaw": "Returns: {Buffer|string} The stdout from the command.", "name": "return", "type": "Buffer|string", "desc": "The stdout from the command." }, "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. 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. Supplying this value will override `stdio[0]`." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. `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. `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." } ] } ] } ], "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.

\n

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().

\n

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])`", "type": "method", "name": "spawnSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v16.4.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": [ { "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." } ] }, "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." }, { "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. 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. 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.", "name": "stdio", "type": "string|Array", "desc": "Child's stdio configuration." }, { "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." } ] } ] } ], "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.

\n

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.

" } ], "type": "module", "displayName": "Synchronous process creation" }, { "textRaw": "`maxBuffer` and Unicode", "name": "`maxbuffer`_and_unicode", "desc": "

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.

", "type": "module", "displayName": "`maxBuffer` and Unicode" }, { "textRaw": "Shell requirements", "name": "shell_requirements", "desc": "

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.

", "type": "module", "displayName": "Shell requirements" }, { "textRaw": "Default Windows shell", "name": "default_windows_shell", "desc": "

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.

", "type": "module", "displayName": "Default Windows shell" }, { "textRaw": "Advanced serialization", "name": "advanced_serialization", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "desc": "

Child processes support a serialization mechanism for IPC that is based on the\nserialization API of the 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.

\n

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().

", "type": "module", "displayName": "Advanced serialization" } ], "classes": [ { "textRaw": "Class: `ChildProcess`", "type": "class", "name": "ChildProcess", "meta": { "added": [ "v2.2.0" ], "changes": [] }, "desc": "\n

Instances of the ChildProcess represent spawned child processes.

\n

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.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [ { "textRaw": "`code` {number} The exit code if the child exited on its own.", "name": "code", "type": "number", "desc": "The exit code if the child exited on its own." }, { "textRaw": "`signal` {string} The signal by which the child process was terminated.", "name": "signal", "type": "string", "desc": "The signal by which the child process was terminated." } ], "desc": "

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 failed to spawn.

\n
const { spawn } = require('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
" }, { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "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.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "params": [ { "textRaw": "`err` {Error} The error.", "name": "err", "type": "Error", "desc": "The error." } ], "desc": "

The 'error' event is emitted whenever:

\n
    \n
  1. The process could not be spawned, or
  2. \n
  3. The process could not be killed, or
  4. \n
  5. Sending a message to the child process failed.
  6. \n
\n

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.

\n

See also subprocess.kill() and subprocess.send().

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "`code` {number} The exit code if the child exited on its own.", "name": "code", "type": "number", "desc": "The exit code if the child exited on its own." }, { "textRaw": "`signal` {string} The signal by which the child process was terminated.", "name": "signal", "type": "string", "desc": "The signal by which the child process was terminated." } ], "desc": "

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.

\n

When the 'exit' event is triggered, child process stdio streams might still be\nopen.

\n

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.

\n

See waitpid(2).

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "params": [ { "textRaw": "`message` {Object} A parsed JSON object or primitive value.", "name": "message", "type": "Object", "desc": "A parsed JSON object or primitive value." }, { "textRaw": "`sendHandle` {Handle} A [`net.Socket`][] or [`net.Server`][] object, or undefined.", "name": "sendHandle", "type": "Handle", "desc": "A [`net.Socket`][] or [`net.Server`][] object, or undefined." } ], "desc": "

The 'message' event is triggered when a child process uses\nprocess.send() to send messages.

\n

The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

\n

If 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.

" }, { "textRaw": "Event: `'spawn'`", "type": "event", "name": "spawn", "meta": { "added": [ "v15.1.0" ], "changes": [] }, "params": [], "desc": "

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.

\n

If emitted, the 'spawn' event comes before all other events and before any\ndata is received via stdout or stderr.

\n

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 }.

" } ], "properties": [ { "textRaw": "`channel` {Object} A pipe representing the IPC channel to the child process.", "type": "Object", "name": "channel", "meta": { "added": [ "v7.1.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30165", "description": "The object no longer accidentally exposes native C++ bindings." } ] }, "desc": "

The subprocess.channel property is a reference to the child's IPC channel. If\nno IPC channel currently exists, this property is undefined.

", "shortDesc": "A pipe representing the IPC channel to the child process.", "methods": [ { "textRaw": "`subprocess.channel.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This method makes the IPC channel keep the event loop of the parent process\nrunning if .unref() has been called before.

" }, { "textRaw": "`subprocess.channel.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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": "`connected` {boolean} Set to `false` after `subprocess.disconnect()` is called.", "type": "boolean", "name": "connected", "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.

", "shortDesc": "Set to `false` after `subprocess.disconnect()` is called." }, { "textRaw": "`exitCode` {integer}", "type": "integer", "name": "exitCode", "desc": "

The subprocess.exitCode property indicates the exit code of the child process.\nIf the child process is still running, the field will be null.

" }, { "textRaw": "`killed` {boolean} Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process.", "type": "boolean", "name": "killed", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "desc": "

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.

", "shortDesc": "Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process." }, { "textRaw": "`pid` {integer|undefined}", "type": "integer|undefined", "name": "pid", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

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.

\n
const { spawn } = require('child_process');\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
" }, { "textRaw": "`signalCode` {string|null}", "type": "string|null", "name": "signalCode", "desc": "

The subprocess.signalCode property indicates the signal received by\nthe child process if any, else null.

" }, { "textRaw": "`spawnargs` {Array}", "type": "Array", "name": "spawnargs", "desc": "

The subprocess.spawnargs property represents the full list of command-line\narguments the child process was launched with.

" }, { "textRaw": "`spawnfile` {string}", "type": "string", "name": "spawnfile", "desc": "

The subprocess.spawnfile property indicates the executable file name of\nthe child process that is launched.

\n

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.

" }, { "textRaw": "`stderr` {stream.Readable}", "type": "stream.Readable", "name": "stderr", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

A Readable Stream that represents the child process's stderr.

\n

If the child was spawned with stdio[2] set to anything other than 'pipe',\nthen this will be null.

\n

subprocess.stderr is an alias for subprocess.stdio[2]. Both properties will\nrefer to the same value.

\n

The subprocess.stderr property can be null if the child process could\nnot be successfully spawned.

" }, { "textRaw": "`stdin` {stream.Writable}", "type": "stream.Writable", "name": "stdin", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

A Writable Stream that represents the child process's stdin.

\n

If a child process waits to read all of its input, the child will not continue\nuntil this stream has been closed via end().

\n

If the child was spawned with stdio[0] set to anything other than 'pipe',\nthen this will be null.

\n

subprocess.stdin is an alias for subprocess.stdio[0]. Both properties will\nrefer to the same value.

\n

The subprocess.stdin property can be undefined if the child process could\nnot be successfully spawned.

" }, { "textRaw": "`stdio` {Array}", "type": "Array", "name": "stdio", "meta": { "added": [ "v0.7.10" ], "changes": [] }, "desc": "

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.

\n

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.

\n
const assert = require('assert');\nconst fs = require('fs');\nconst child_process = require('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
\n

The subprocess.stdio property can be undefined if the child process could\nnot be successfully spawned.

" }, { "textRaw": "`stdout` {stream.Readable}", "type": "stream.Readable", "name": "stdout", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

A Readable Stream that represents the child process's stdout.

\n

If the child was spawned with stdio[1] set to anything other than 'pipe',\nthen this will be null.

\n

subprocess.stdout is an alias for subprocess.stdio[1]. Both properties will\nrefer to the same value.

\n
const { spawn } = require('child_process');\n\nconst subprocess = spawn('ls');\n\nsubprocess.stdout.on('data', (data) => {\n  console.log(`Received chunk ${data}`);\n});\n
\n

The subprocess.stdout property can be null if the child process could\nnot be successfully spawned.

" } ], "methods": [ { "textRaw": "`subprocess.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the IPC channel between parent and child, allowing the child to exit\ngracefully once there are no other connections keeping it alive. After calling\nthis method the subprocess.connected and process.connected properties in\nboth the parent and child (respectively) will be set to false, and it will be\nno longer possible to pass messages between the processes.

\n

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().

\n

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.

" }, { "textRaw": "`subprocess.kill([signal])`", "type": "method", "name": "kill", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`signal` {number|string}", "name": "signal", "type": "number|string" } ] } ], "desc": "

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.

\n
const { spawn } = require('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
\n

The 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.

\n

While the function is called kill, the signal delivered to the child process\nmay not actually terminate the process.

\n

See kill(2) for reference.

\n

On Windows, where POSIX signals do not exist, the signal argument will be\nignored, and the process will be killed forcefully and abruptly (similar to\n'SIGKILL').\nSee Signal Events for more details.

\n

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:

\n
'use strict';\nconst { spawn } = require('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.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v0.7.10" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calling subprocess.ref() after making a call to subprocess.unref() will\nrestore the removed reference count for the child process, forcing the parent\nto wait for the child to exit before exiting itself.

\n
const { spawn } = require('child_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])`", "type": "method", "name": "send", "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": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle}", "name": "sendHandle", "type": "Handle" }, { "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." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

When an IPC channel has been established between the parent and child (\ni.e. when using child_process.fork()), the subprocess.send() method can\nbe 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.

\n

The message goes through serialization and parsing. The resulting\nmessage might not be the same as what is originally sent.

\n

For example, in the parent script:

\n
const cp = require('child_process');\nconst n = cp.fork(`${__dirname}/sub.js`);\n\nn.on('message', (m) => {\n  console.log('PARENT got message:', m);\n});\n\n// Causes the child to print: CHILD got message: { hello: 'world' }\nn.send({ hello: 'world' });\n
\n

And then the child script, 'sub.js' might look like this:

\n
process.on('message', (m) => {\n  console.log('CHILD got message:', m);\n});\n\n// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }\nprocess.send({ foo: 'bar', baz: NaN });\n
\n

Child Node.js processes will have a process.send() method of their own\nthat allows the child to send messages back to the parent.

\n

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.

\n

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 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.

\n

The optional callback is a function that is invoked after the message is\nsent but before the child may have received it. The function is called with a\nsingle argument: null on success, or an Error object on failure.

\n

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.

\n

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.

\n

Example: sending a server object

\n

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:

\n
const subprocess = require('child_process').fork('subprocess.js');\n\n// Open up the server object and send the handle.\nconst server = require('net').createServer();\nserver.on('connection', (socket) => {\n  socket.end('handled by parent');\n});\nserver.listen(1337, () => {\n  subprocess.send('server', server);\n});\n
\n

The child would then receive the server object as:

\n
process.on('message', (m, server) => {\n  if (m === 'server') {\n    server.on('connection', (socket) => {\n      socket.end('handled by child');\n    });\n  }\n});\n
\n

Once the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.

\n

While the example above uses a server created using the net module, dgram\nmodule servers use exactly the same workflow with the exceptions of listening on\na 'message' event instead of 'connection' and using server.bind() instead\nof server.listen(). This is, however, currently only supported on Unix\nplatforms.

\n

Example: sending a socket object

\n

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:

\n
const { fork } = require('child_process');\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 = require('net').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
\n

The subprocess.js would receive the socket handle as the second argument\npassed to the event callback function:

\n
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
\n

Do not use .maxConnections on a socket that has been passed to a subprocess.\nThe parent cannot track when the socket is destroyed.

\n

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.

" }, { "textRaw": "`subprocess.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.7.10" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

By default, the parent will wait for the detached child to exit. To prevent the\nparent 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 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.

\n
const { spawn } = require('child_process');\n\nconst subprocess = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: 'ignore'\n});\n\nsubprocess.unref();\n
" } ] } ], "type": "module", "displayName": "Child process", "source": "doc/api/child_process.md" }, { "textRaw": "Cluster", "name": "cluster", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/cluster.js

\n

A single instance of Node.js runs in a single thread. To take advantage of\nmulti-core systems, the user will sometimes want to launch a cluster of Node.js\nprocesses to handle the load.

\n

The cluster module allows easy creation of child processes that all share\nserver ports.

\n
import cluster from 'cluster';\nimport http from 'http';\nimport { cpus } from 'os';\nimport process from 'process';\n\nconst numCPUs = cpus().length;\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
\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\nconst process = require('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
\n

Running 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
\n

On 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.

\n

The cluster module supports two methods of distributing incoming\nconnections.

\n

The 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.

\n

The second approach is where the primary process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.

\n

The 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.

\n

Because 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:

\n
    \n
  1. 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.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the primary\nprocess.
  4. \n
  5. 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.
  6. \n
\n

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.

\n

Because 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.

\n

Although a primary use case for the cluster module is networking, it can\nalso be used for other use cases requiring worker processes.

" } ], "classes": [ { "textRaw": "Class: `Worker`", "type": "class", "name": "Worker", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [], "desc": "

Similar to the cluster.on('disconnect') event, but specific to this worker.

\n
cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n
" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.7.3" ], "changes": [] }, "params": [], "desc": "

This event is the same as the one provided by child_process.fork().

\n

Within a worker, process.on('error') may also be used.

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "params": [ { "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": "

Similar to the cluster.on('exit') event, but specific to this worker.

\n
import cluster from 'cluster';\n\nconst worker = cluster.fork();\nworker.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
const cluster = require('cluster');\n\nconst worker = cluster.fork();\nworker.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
" }, { "textRaw": "Event: `'listening'`", "type": "event", "name": "listening", "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.

\n
import cluster from 'cluster';\n\ncluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
\n
const cluster = require('cluster');\n\ncluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
\n

It is not emitted in the worker.

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "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.

\n

Within a worker, process.on('message') may also be used.

\n

See process event: 'message'.

\n

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:

\n
import cluster from 'cluster';\nimport http from 'http';\nimport { cpus } from 'os';\nimport process from '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 = cpus().length;\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
\n
const cluster = require('cluster');\nconst http = require('http');\nconst process = require('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 = require('os').cpus().length;\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'`", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [], "desc": "

Similar to the cluster.on('online') event, but specific to this worker.

\n
cluster.fork().on('online', () => {\n  // Worker is online\n});\n
\n

It is not emitted in the worker.

" } ], "methods": [ { "textRaw": "`worker.disconnect()`", "type": "method", "name": "disconnect", "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": [ { "return": { "textRaw": "Returns: {cluster.Worker} A reference to `worker`.", "name": "return", "type": "cluster.Worker", "desc": "A reference to `worker`." }, "params": [] } ], "desc": "

In a worker, this function will close all servers, wait for the 'close' event\non those servers, and then disconnect the IPC channel.

\n

In the primary, an internal message is sent to the worker causing it to call\n.disconnect() on itself.

\n

Causes .exitedAfterDisconnect to be set.

\n

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.

\n

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.

\n

In a worker, process.disconnect exists, but it is not this function;\nit is disconnect().

\n

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.

\n
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('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()`", "type": "method", "name": "isConnected", "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.

" }, { "textRaw": "`worker.isDead()`", "type": "method", "name": "isDead", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.

\n
import cluster from 'cluster';\nimport http from 'http';\nimport { cpus } from 'os';\nimport process from 'process';\n\nconst numCPUs = cpus().length;\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
\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\nconst process = require('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])`", "type": "method", "name": "kill", "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." } ] } ], "desc": "

This function will kill the worker. In the primary, it does this\nby disconnecting the worker.process, and once disconnected, killing\nwith signal. In the worker, it does it by disconnecting the channel,\nand then exiting with code 0.

\n

Because kill() attempts to gracefully disconnect the worker process, it is\nsusceptible to waiting indefinitely for the disconnect to complete. For example,\nif the worker enters an infinite loop, a graceful disconnect will never occur.\nIf the graceful disconnect behavior is not needed, use worker.process.kill().

\n

Causes .exitedAfterDisconnect to be set.

\n

This method is aliased as worker.destroy() for backward compatibility.

\n

In a worker, process.kill() exists, but it is not this function;\nit is kill().

" }, { "textRaw": "`worker.send(message[, sendHandle[, options]][, callback])`", "type": "method", "name": "send", "meta": { "added": [ "v0.7.0" ], "changes": [ { "version": "v4.0.0", "pr-url": "https://github.com/nodejs/node/pull/2620", "description": "The `callback` parameter is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle}", "name": "sendHandle", "type": "Handle" }, { "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." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Send a message to a worker or primary, optionally with a handle.

\n

In the primary this sends a message to a specific worker. It is identical to\nChildProcess.send().

\n

In a worker this sends a message to the primary. It is identical to\nprocess.send().

\n

This example will echo back all messages from the primary:

\n
if (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": "`exitedAfterDisconnect` {boolean}", "type": "boolean", "name": "exitedAfterDisconnect", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "desc": "

This property is true if the worker exited due to .kill() or\n.disconnect(). If the worker exited any other way, it is false. If the\nworker has not exited, it is undefined.

\n

The boolean worker.exitedAfterDisconnect allows distinguishing between\nvoluntary and accidental exit, the primary may choose not to respawn a worker\nbased on this value.

\n
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": "`id` {number}", "type": "number", "name": "id", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers.

" }, { "textRaw": "`process` {ChildProcess}", "type": "ChildProcess", "name": "process", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

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.

\n

See: Child Process module.

\n

Workers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.

" } ] } ], "events": [ { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.9" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

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()).

\n

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.

\n
cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "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.

\n

This can be used to restart the worker by calling .fork() again.

\n
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
\n

See child_process event: 'exit'.

" }, { "textRaw": "Event: `'fork'`", "type": "event", "name": "fork", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

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.

\n
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'`", "type": "event", "name": "listening", "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.

\n

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.

\n
cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});\n
\n

The addressType is one of:

\n
    \n
  • 4 (TCPv4)
  • \n
  • 6 (TCPv6)
  • \n
  • -1 (Unix domain socket)
  • \n
  • 'udp4' or 'udp6' (UDP v4 or v6)
  • \n
" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v2.5.0" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5361", "description": "The `worker` parameter is passed now; see below for details." } ] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" }, { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`handle` {undefined|Object}", "name": "handle", "type": "undefined|Object" } ], "desc": "

Emitted when the cluster primary receives a message from any worker.

\n

See child_process event: 'message'.

" }, { "textRaw": "Event: `'online'`", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {cluster.Worker}", "name": "worker", "type": "cluster.Worker" } ], "desc": "

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.

\n
cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});\n
" }, { "textRaw": "Event: `'setup'`", "type": "event", "name": "setup", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "params": [ { "textRaw": "`settings` {Object}", "name": "settings", "type": "Object" } ], "desc": "

Emitted every time .setupPrimary() is called.

\n

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.

\n

If accuracy is important, use cluster.settings.

" } ], "methods": [ { "textRaw": "`cluster.disconnect([callback])`", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Called when all workers are disconnected and handles are closed.", "name": "callback", "type": "Function", "desc": "Called when all workers are disconnected and handles are closed." } ] } ], "desc": "

Calls .disconnect() on each worker in cluster.workers.

\n

When they are disconnected all internal handles will be closed, allowing the\nprimary process to die gracefully if no other event is waiting.

\n

The method takes an optional callback argument which will be called when\nfinished.

\n

This can only be called from the primary process.

" }, { "textRaw": "`cluster.fork([env])`", "type": "method", "name": "fork", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {cluster.Worker}", "name": "return", "type": "cluster.Worker" }, "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." } ] } ], "desc": "

Spawn a new worker process.

\n

This can only be called from the primary process.

" }, { "textRaw": "`cluster.setupMaster([settings])`", "type": "method", "name": "setupMaster", "meta": { "added": [ "v0.7.1" ], "deprecated": [ "v16.0.0" ], "changes": [ { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7838", "description": "The `stdio` option is supported now." } ] }, "signatures": [ { "params": [] } ], "desc": "

Deprecated alias for .setupPrimary().

" }, { "textRaw": "`cluster.setupPrimary([settings])`", "type": "method", "name": "setupPrimary", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {Object} See [`cluster.settings`][].", "name": "settings", "type": "Object", "desc": "See [`cluster.settings`][]." } ] } ], "desc": "

setupPrimary is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.

\n

Any settings changes only affect future calls to .fork() and have no\neffect on workers that are already running.

\n

The only attribute of a worker that cannot be set via .setupPrimary() is\nthe env passed to .fork().

\n

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.

\n
import cluster from '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
\n
const cluster = require('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
\n

This can only be called from the primary process.

" } ], "properties": [ { "textRaw": "`cluster.isMaster`", "name": "isMaster", "meta": { "added": [ "v0.8.1" ], "deprecated": [ "v16.0.0" ], "changes": [] }, "desc": "

Deprecated alias for cluster.isPrimary.\ndetails.

" }, { "textRaw": "`isPrimary` {boolean}", "type": "boolean", "name": "isPrimary", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`isWorker` {boolean}", "type": "boolean", "name": "isWorker", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "desc": "

True if the process is not a primary (it is the negation of cluster.isPrimary).

" }, { "textRaw": "`cluster.schedulingPolicy`", "name": "schedulingPolicy", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "desc": "

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.

\n

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.

\n

cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are 'rr' and 'none'.

" }, { "textRaw": "`settings` {Object}", "type": "Object", "name": "settings", "meta": { "added": [ "v0.7.1" ], "changes": [ { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30162", "description": "The `serialization` option is supported now." }, { "version": "v9.5.0", "pr-url": "https://github.com/nodejs/node/pull/18399", "description": "The `cwd` option is supported now." }, { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/17412", "description": "The `windowsHide` option is supported now." }, { "version": "v8.2.0", "pr-url": "https://github.com/nodejs/node/pull/14140", "description": "The `inspectPort` option is supported now." }, { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7838", "description": "The `stdio` option is supported now." } ] }, "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`.", "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`." }, { "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." } ], "desc": "

After calling .setupPrimary() (or .fork()) this settings object will\ncontain the settings, including the default values.

\n

This object is not intended to be changed or set manually.

" }, { "textRaw": "`worker` {Object}", "type": "Object", "name": "worker", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

A reference to the current worker object. Not available in the primary process.

\n
import cluster from '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
\n
const cluster = require('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": "`workers` {Object}", "type": "Object", "name": "workers", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the primary\nprocess.

\n

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 last 'disconnect' or 'exit' event is emitted.

\n
import cluster from 'cluster';\n\n// Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n
\n
const cluster = require('cluster');\n\n// Go through all workers\nfunction eachWorker(callback) {\n  for (const id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\n});\n
\n

Using the worker's unique id is the easiest way to locate the worker.

\n
socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n
" } ], "type": "module", "displayName": "Cluster", "source": "doc/api/cluster.md" }, { "textRaw": "Console", "name": "console", "introduced_in": "v0.10.13", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/console.js

\n

The console module provides a simple debugging console that is similar to the\nJavaScript console mechanism provided by web browsers.

\n

The module exports two specific components:

\n
    \n
  • A Console class with methods such as console.log(), console.error() and\nconsole.warn() that can be used to write to any Node.js stream.
  • \n
  • A global console instance configured to write to process.stdout and\nprocess.stderr. The global console can be used without calling\nrequire('console').
  • \n
\n

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. See the note on process I/O for\nmore information.

\n

Example using the global console:

\n
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
\n

Example using the Console class:

\n
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`", "type": "class", "name": "Console", "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('console').Console\nor console.Console (or their destructured counterparts):

\n
const { Console } = require('console');\n
\n
const { Console } = console;\n
", "methods": [ { "textRaw": "`console.assert(value[, ...message])`", "type": "method", "name": "assert", "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." } ] } ], "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().

\n

If value is truthy, nothing happens.

\n
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()`", "type": "method", "name": "clear", "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.

\n

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.

" }, { "textRaw": "`console.count([label])`", "type": "method", "name": "count", "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." } ] } ], "desc": "

Maintains an internal counter specific to label and outputs to stdout the\nnumber of times console.count() has been called with the given label.

\n\n
> 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])`", "type": "method", "name": "countReset", "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." } ] } ], "desc": "

Resets the internal counter specific to label.

\n\n
> 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])`", "type": "method", "name": "debug", "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" } ] } ], "desc": "

The console.debug() function is an alias for console.log().

" }, { "textRaw": "`console.dir(obj[, options])`", "type": "method", "name": "dir", "meta": { "added": [ "v0.1.101" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`obj` {any}", "name": "obj", "type": "any" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`showHidden` {boolean} If `true` then the object's non-enumerable and symbol properties will be shown too. **Default:** `false`.", "name": "showHidden", "type": "boolean", "default": "`false`", "desc": "If `true` then the object's non-enumerable and symbol properties will be shown too." }, { "textRaw": "`depth` {number} Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`.", "name": "depth", "type": "number", "default": "`2`", "desc": "Tells [`util.inspect()`][] how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`." }, { "textRaw": "`colors` {boolean} If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]. **Default:** `false`.", "name": "colors", "type": "boolean", "default": "`false`", "desc": "If `true`, then the output will be styled with ANSI color codes. Colors are customizable; see [customizing `util.inspect()` colors][]." } ] } ] } ], "desc": "

Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj.

" }, { "textRaw": "`console.dirxml(...data)`", "type": "method", "name": "dirxml", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v9.3.0", "pr-url": "https://github.com/nodejs/node/pull/17152", "description": "`console.dirxml` now calls `console.log` for its arguments." } ] }, "signatures": [ { "params": [ { "textRaw": "`...data` {any}", "name": "...data", "type": "any" } ] } ], "desc": "

This method calls console.log() passing it the arguments received.\nThis method does not produce any XML formatting.

" }, { "textRaw": "`console.error([data][, ...args])`", "type": "method", "name": "error", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {any}", "name": "data", "type": "any" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

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\nutil.format()).

\n
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
\n

If 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.

" }, { "textRaw": "`console.group([...label])`", "type": "method", "name": "group", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`...label` {any}", "name": "...label", "type": "any" } ] } ], "desc": "

Increases indentation of subsequent lines by spaces for groupIndentation\nlength.

\n

If one or more labels are provided, those are printed first without the\nadditional indentation.

" }, { "textRaw": "`console.groupCollapsed()`", "type": "method", "name": "groupCollapsed", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

An alias for console.group().

" }, { "textRaw": "`console.groupEnd()`", "type": "method", "name": "groupEnd", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Decreases indentation of subsequent lines by spaces for groupIndentation\nlength.

" }, { "textRaw": "`console.info([data][, ...args])`", "type": "method", "name": "info", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {any}", "name": "data", "type": "any" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

The console.info() function is an alias for console.log().

" }, { "textRaw": "`console.log([data][, ...args])`", "type": "method", "name": "log", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {any}", "name": "data", "type": "any" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

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\nutil.format()).

\n
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
\n

See util.format() for more information.

" }, { "textRaw": "`console.table(tabularData[, properties])`", "type": "method", "name": "table", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`tabularData` {any}", "name": "tabularData", "type": "any" }, { "textRaw": "`properties` {string[]} Alternate properties for constructing the table.", "name": "properties", "type": "string[]", "desc": "Alternate properties for constructing the table." } ] } ], "desc": "

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.

\n
// 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])`", "type": "method", "name": "time", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} **Default:** `'default'`", "name": "label", "type": "string", "default": "`'default'`" } ] } ], "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\".

" }, { "textRaw": "`console.timeEnd([label])`", "type": "method", "name": "timeEnd", "meta": { "added": [ "v0.1.104" ], "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29251", "description": "The elapsed time is displayed with a suitable time unit." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5901", "description": "This method no longer supports multiple calls that don’t map to individual `console.time()` calls; see below for details." } ] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} **Default:** `'default'`", "name": "label", "type": "string", "default": "`'default'`" } ] } ], "desc": "

Stops a timer that was previously started by calling console.time() and\nprints the result to stdout:

\n
console.time('100-elements');\nfor (let i = 0; i < 100; i++) {}\nconsole.timeEnd('100-elements');\n// prints 100-elements: 225.438ms\n
" }, { "textRaw": "`console.timeLog([label][, ...data])`", "type": "method", "name": "timeLog", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} **Default:** `'default'`", "name": "label", "type": "string", "default": "`'default'`" }, { "textRaw": "`...data` {any}", "name": "...data", "type": "any" } ] } ], "desc": "

For a timer that was previously started by calling console.time(), prints\nthe elapsed time and other data arguments to stdout:

\n
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])`", "type": "method", "name": "trace", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {any}", "name": "message", "type": "any" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

Prints to stderr the string 'Trace: ', followed by the util.format()\nformatted message and stack trace to the current position in the code.

\n
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])`", "type": "method", "name": "warn", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {any}", "name": "data", "type": "any" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

The console.warn() function is an alias for console.error().

" } ], "signatures": [ { "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} Specifies options that are passed along to [`util.inspect()`][].", "name": "inspectOptions", "type": "Object", "desc": "Specifies options that are passed along to [`util.inspect()`][]." }, { "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.

\n
const 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
\n

The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

\n
new Console({ stdout: process.stdout, stderr: process.stderr });\n
" }, { "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} Specifies options that are passed along to [`util.inspect()`][].", "name": "inspectOptions", "type": "Object", "desc": "Specifies options that are passed along to [`util.inspect()`][]." }, { "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.

\n
const 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
\n

The global console is a special Console whose output is sent to\nprocess.stdout and process.stderr. It is equivalent to calling:

\n
new Console({ stdout: process.stdout, stderr: process.stderr });\n
" } ] } ], "modules": [ { "textRaw": "Inspector only methods", "name": "inspector_only_methods", "desc": "

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).

", "methods": [ { "textRaw": "`console.profile([label])`", "type": "method", "name": "profile", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string}", "name": "label", "type": "string" } ] } ], "desc": "

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.

\n
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])`", "type": "method", "name": "profileEnd", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string}", "name": "label", "type": "string" } ] } ], "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.

\n

If this method is called without a label, the most recently started profile is\nstopped.

" }, { "textRaw": "`console.timeStamp([label])`", "type": "method", "name": "timeStamp", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`label` {string}", "name": "label", "type": "string" } ] } ], "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.

" } ], "type": "module", "displayName": "Inspector only methods" } ], "type": "module", "displayName": "Console", "source": "doc/api/console.md" }, { "textRaw": "Crypto", "name": "crypto", "introduced_in": "v0.3.6", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/crypto.js

\n

The crypto module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

\n
const { createHmac } = await import('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
\n
const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.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", "desc": "

It is possible for Node.js to be built without including support for the\ncrypto module. In such cases, attempting to import from crypto or\ncalling require('crypto') will result in an error being thrown.

\n

When using CommonJS, the error thrown can be caught using try/catch:

\n
let crypto;\ntry {\n  crypto = require('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
\n

When 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.

\n

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:

\n
let crypto;\ntry {\n  crypto = await import('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
", "type": "module", "displayName": "Determining if crypto support is unavailable" }, { "textRaw": "`crypto` module methods and properties", "name": "`crypto`_module_methods_and_properties", "properties": [ { "textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][].", "type": "Object", "name": "return", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][]." }, { "textRaw": "`crypto.DEFAULT_ENCODING`", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes methods\ndefault to Buffer objects.

\n

The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.

\n

New applications should expect the default to be 'buffer'.

\n

This property is deprecated.

" }, { "textRaw": "`crypto.fips`", "name": "fips", "meta": { "added": [ "v6.0.0" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "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.

\n

This property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.

" }, { "textRaw": "`crypto.webcrypto`", "name": "webcrypto", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Type: <Crypto> An implementation of the Web Crypto API standard.

\n

See the Web Crypto API documentation for details.

" } ], "methods": [ { "textRaw": "`crypto.checkPrime(candidate[, options, [callback]])`", "type": "method", "name": "checkPrime", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "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." } ] }, { "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.

" }, { "textRaw": "`crypto.checkPrimeSync(candidate[, options])`", "type": "method", "name": "checkPrimeSync", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.", "name": "return", "type": "boolean", "desc": "`true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`." }, "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." } ] } ] } ], "desc": "

Checks the primality of the candidate.

" }, { "textRaw": "`crypto.createCipher(algorithm, password[, options])`", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password argument can be an ArrayBuffer and is limited to a maximum of 2 ** 31 - 1 bytes." }, { "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/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createCipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates and returns a Cipher object that uses the given algorithm and\npassword.

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). 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.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

The password is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1' encoded string, a Buffer, a\nTypedArray, or a DataView.

\n

The implementation of crypto.createCipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

\n

In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createCipheriv()\nto create the Cipher object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when\nthey are used in order to avoid the risk of IV reuse that causes\nvulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting\nAdversaries for details.

" }, { "textRaw": "`crypto.createCipheriv(algorithm, key, iv[, options])`", "type": "method", "name": "createCipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password and iv arguments can be an ArrayBuffer and are each limited to a maximum of 2 ** 31 - 1 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` 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/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." }, { "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": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "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][]" } ] } ], "desc": "

Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). 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.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

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.

\n

When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n

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.createDecipher(algorithm, password[, options])`", "type": "method", "name": "createDecipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createDecipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates and returns a Decipher object that uses the given algorithm and\npassword (key).

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.

\n

The implementation of crypto.createDecipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

\n

In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createDecipheriv()\nto create the Decipher object.

" }, { "textRaw": "`crypto.createDecipheriv(algorithm, key, iv[, options])`", "type": "method", "name": "createDecipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "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` 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": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "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][]" } ] } ], "desc": "

Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). 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 restrict accepted authentication tags\nto those with the specified length.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

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.

\n

When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n

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])`", "type": "method", "name": "createDiffieHellman", "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": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "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." }, { "textRaw": "`generator` {number|string|ArrayBuffer|Buffer|TypedArray|DataView} **Default:** `2`", "name": "generator", "type": "number|string|ArrayBuffer|Buffer|TypedArray|DataView", "default": "`2`" }, { "textRaw": "`generatorEncoding` {string} The [encoding][] of the `generator` string.", "name": "generatorEncoding", "type": "string", "desc": "The [encoding][] of the `generator` string." } ] } ], "desc": "

Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.

\n

The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.

\n

If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.

\n

If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.

" }, { "textRaw": "`crypto.createDiffieHellman(primeLength[, generator])`", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "params": [ { "textRaw": "`primeLength` {number}", "name": "primeLength", "type": "number" }, { "textRaw": "`generator` {number} **Default:** `2`", "name": "generator", "type": "number", "default": "`2`" } ] } ], "desc": "

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.

" }, { "textRaw": "`crypto.createDiffieHellmanGroup(name)`", "type": "method", "name": "createDiffieHellmanGroup", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellmanGroup}", "name": "return", "type": "DiffieHellmanGroup" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

An alias for crypto.getDiffieHellman()

" }, { "textRaw": "`crypto.createECDH(curveName)`", "type": "method", "name": "createECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ECDH}", "name": "return", "type": "ECDH" }, "params": [ { "textRaw": "`curveName` {string}", "name": "curveName", "type": "string" } ] } ], "desc": "

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.

" }, { "textRaw": "`crypto.createHash(algorithm[, options])`", "type": "method", "name": "createHash", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v12.8.0", "pr-url": "https://github.com/nodejs/node/pull/28805", "description": "The `outputLength` option was added for XOF hash functions." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Hash}", "name": "return", "type": "Hash" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

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.

\n

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\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

\n

Example: generating the sha256 sum of a file

\n
import {\n  createReadStream\n} from 'fs';\nimport { argv } from 'process';\nconst {\n  createHash\n} = await import('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
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHash,\n} = require('crypto');\nconst { argv } = require('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])`", "type": "method", "name": "createHmac", "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": [ { "return": { "textRaw": "Returns: {Hmac}", "name": "return", "type": "Hmac" }, "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." } ] } ] } ], "desc": "

Creates and returns an Hmac object that uses the given algorithm and key.\nOptional options argument controls stream behavior.

\n

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\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

\n

The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret.

\n

Example: generating the sha256 HMAC of a file

\n
import {\n  createReadStream\n} from 'fs';\nimport { argv } from 'process';\nconst {\n  createHmac\n} = await import('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
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHmac,\n} = require('crypto');\nconst { argv } = require('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)`", "type": "method", "name": "createPrivateKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "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": [] } ], "desc": "\n\n\n

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.

\n

If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.

" }, { "textRaw": "`crypto.createPublicKey(key)`", "type": "method", "name": "createPublicKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "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." }, { "version": "v11.13.0", "pr-url": "https://github.com/nodejs/node/pull/26278", "description": "The `key` argument can now be a `KeyObject` with type `private`." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25217", "description": "The `key` argument can now be a private key." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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.

\n

If the format is 'pem', the 'key' may also be an X.509 certificate.

\n

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.

" }, { "textRaw": "`crypto.createSecretKey(key[, encoding])`", "type": "method", "name": "createSecretKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The key can also be an ArrayBuffer or string. The encoding argument was added. The key cannot contain more than 2 ** 32 - 1 bytes." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The string encoding when `key` is a string.", "name": "encoding", "type": "string", "desc": "The string encoding when `key` is a string." } ] } ], "desc": "

Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.

" }, { "textRaw": "`crypto.createSign(algorithm[, options])`", "type": "method", "name": "createSign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Sign}", "name": "return", "type": "Sign" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]" } ] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`crypto.createVerify(algorithm[, options])`", "type": "method", "name": "createVerify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Verify}", "name": "return", "type": "Verify" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]" } ] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`crypto.diffieHellman(options)`", "type": "method", "name": "diffieHellman", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`privateKey`: {KeyObject}", "name": "privateKey", "type": "KeyObject" }, { "textRaw": "`publicKey`: {KeyObject}", "name": "publicKey", "type": "KeyObject" } ] } ] } ], "desc": "

Computes the Diffie-Hellman secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType, which must be one of 'dh'\n(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

" }, { "textRaw": "`crypto.generateKey(type, options, callback)`", "type": "method", "name": "generateKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type`: {string} The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.", "name": "type", "type": "string", "desc": "The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`length`: {number} The bit length of the key to generate. This must be a value greater than 0.", "name": "length", "type": "number", "desc": "The bit length of the key to generate. This must be a value greater than 0.", "options": [ { "textRaw": "If `type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`.", "name": "If", "desc": "`type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`." }, { "textRaw": "If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.", "name": "If", "desc": "`type` is `'aes'`, the length must be one of `128`, `192`, or `256`." } ] } ] }, { "textRaw": "`callback`: {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err`: {Error}", "name": "err", "type": "Error" }, { "textRaw": "`key`: {KeyObject}", "name": "key", "type": "KeyObject" } ] } ] } ], "desc": "

Asynchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.

\n
const {\n  generateKey\n} = await import('crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n  if (err) throw err;\n  console.log(key.export().toString('hex'));  // 46e..........620\n});\n
\n
const {\n  generateKey,\n} = require('crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n  if (err) throw err;\n  console.log(key.export().toString('hex'));  // 46e..........620\n});\n
" }, { "textRaw": "`crypto.generateKeyPair(type, options, callback)`", "type": "method", "name": "generateKeyPair", "meta": { "added": [ "v10.12.0" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Add support for Diffie-Hellman." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26774", "description": "Add ability to generate X25519 and X448 key pairs." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26554", "description": "Add ability to generate Ed25519 and Ed448 key pairs." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." } ] }, "signatures": [ { "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "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 to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`prime`: {Buffer} The prime parameter (DH).", "name": "prime", "type": "Buffer", "desc": "The prime parameter (DH)." }, { "textRaw": "`primeLength`: {number} Prime length in bits (DH).", "name": "primeLength", "type": "number", "desc": "Prime length in bits (DH)." }, { "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", "name": "generator", "type": "number", "default": "`2`", "desc": "Custom generator (DH)." }, { "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", "name": "groupName", "type": "string", "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." }, { "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "publicKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." }, { "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "privateKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." } ] }, { "textRaw": "`callback`: {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err`: {Error}", "name": "err", "type": "Error" }, { "textRaw": "`publicKey`: {string | Buffer | KeyObject}", "name": "publicKey", "type": "string | Buffer | KeyObject" }, { "textRaw": "`privateKey`: {string | Buffer | KeyObject}", "name": "privateKey", "type": "string | Buffer | KeyObject" } ] } ] } ], "desc": "

Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

\n

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.

\n

It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:

\n
const {\n  generateKeyPair\n} = await import('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
\n
const {\n  generateKeyPair,\n} = require('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
\n

On completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.

\n

If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.

" }, { "textRaw": "`crypto.generateKeyPairSync(type, options)`", "type": "method", "name": "generateKeyPairSync", "meta": { "added": [ "v10.12.0" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Add support for Diffie-Hellman." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26554", "description": "Add ability to generate Ed25519 and Ed448 key pairs." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`publicKey`: {string | Buffer | KeyObject}", "name": "publicKey", "type": "string | Buffer | KeyObject" }, { "textRaw": "`privateKey`: {string | Buffer | KeyObject}", "name": "privateKey", "type": "string | Buffer | KeyObject" } ] }, "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "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 to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`prime`: {Buffer} The prime parameter (DH).", "name": "prime", "type": "Buffer", "desc": "The prime parameter (DH)." }, { "textRaw": "`primeLength`: {number} Prime length in bits (DH).", "name": "primeLength", "type": "number", "desc": "Prime length in bits (DH)." }, { "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", "name": "generator", "type": "number", "default": "`2`", "desc": "Custom generator (DH)." }, { "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", "name": "groupName", "type": "string", "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." }, { "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "publicKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." }, { "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "privateKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." } ] } ] } ], "desc": "

Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

\n

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.

\n

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.

\n
const {\n  generateKeyPairSync\n} = await import('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
\n
const {\n  generateKeyPairSync,\n} = require('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
\n

The 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.

" }, { "textRaw": "`crypto.generateKeySync(type, options)`", "type": "method", "name": "generateKeySync", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`type`: {string} The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.", "name": "type", "type": "string", "desc": "The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`length`: {number} The bit length of the key to generate.", "name": "length", "type": "number", "desc": "The bit length of the key to generate.", "options": [ { "textRaw": "If `type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`.", "name": "If", "desc": "`type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`." }, { "textRaw": "If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.", "name": "If", "desc": "`type` is `'aes'`, the length must be one of `128`, `192`, or `256`." } ] } ] } ] } ], "desc": "

Synchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.

\n
const {\n  generateKeySync\n} = await import('crypto');\n\nconst key = generateKeySync('hmac', 64);\nconsole.log(key.export().toString('hex'));  // e89..........41e\n
\n
const {\n  generateKeySync,\n} = require('crypto');\n\nconst key = generateKeySync('hmac', 64);\nconsole.log(key.export().toString('hex'));  // e89..........41e\n
" }, { "textRaw": "`crypto.generatePrime(size[, options[, callback]])`", "type": "method", "name": "generatePrime", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} The size (in bits) of the prime to generate.", "name": "size", "type": "number", "desc": "The size (in bits) of the prime to generate." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "add", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "rem", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`safe` {boolean} **Default:** `false`.", "name": "safe", "type": "boolean", "default": "`false`" }, { "textRaw": "`bigint` {boolean} When `true`, the generated prime is returned as a `bigint`.", "name": "bigint", "type": "boolean", "desc": "When `true`, the generated prime is returned as a `bigint`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`prime` {ArrayBuffer|bigint}", "name": "prime", "type": "ArrayBuffer|bigint" } ] } ] } ], "desc": "

Generates a pseudorandom prime of size bits.

\n

If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.

\n

The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:

\n
    \n
  • If options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.
  • \n
  • If only options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.
  • \n
  • If only 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.
  • \n
  • options.rem is ignored if options.add is not given.
  • \n
\n

Both options.add and options.rem must be encoded as big-endian sequences\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.

\n

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.

" }, { "textRaw": "`crypto.generatePrimeSync(size[, options])`", "type": "method", "name": "generatePrimeSync", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer|bigint}", "name": "return", "type": "ArrayBuffer|bigint" }, "params": [ { "textRaw": "`size` {number} The size (in bits) of the prime to generate.", "name": "size", "type": "number", "desc": "The size (in bits) of the prime to generate." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "add", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "rem", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`safe` {boolean} **Default:** `false`.", "name": "safe", "type": "boolean", "default": "`false`" }, { "textRaw": "`bigint` {boolean} When `true`, the generated prime is returned as a `bigint`.", "name": "bigint", "type": "boolean", "desc": "When `true`, the generated prime is returned as a `bigint`." } ] } ] } ], "desc": "

Generates a pseudorandom prime of size bits.

\n

If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.

\n

The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:

\n
    \n
  • If options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.
  • \n
  • If only options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.
  • \n
  • If only 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.
  • \n
  • options.rem is ignored if options.add is not given.
  • \n
\n

Both options.add and options.rem must be encoded as big-endian sequences\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.

\n

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.

" }, { "textRaw": "`crypto.getCipherInfo(nameOrNid[, options])`", "type": "method", "name": "getCipherInfo", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`name` {string} The name of the cipher", "name": "name", "type": "string", "desc": "The name of the cipher" }, { "textRaw": "`nid` {number} The nid of the cipher", "name": "nid", "type": "number", "desc": "The nid of the cipher" }, { "textRaw": "`blockSize` {number} The block size of the cipher in bytes. This property is omitted when `mode` is `'stream'`.", "name": "blockSize", "type": "number", "desc": "The block size of the cipher in bytes. This property is omitted when `mode` is `'stream'`." }, { "textRaw": "`ivLength` {number} The expected or default initialization vector length in bytes. This property is omitted if the cipher does not use an initialization vector.", "name": "ivLength", "type": "number", "desc": "The expected or default initialization vector length in bytes. This property is omitted if the cipher does not use an initialization vector." }, { "textRaw": "`keyLength` {number} The expected or default key length in bytes.", "name": "keyLength", "type": "number", "desc": "The expected or default key length in bytes." }, { "textRaw": "`mode` {string} The cipher mode. One of `'cbc'`, `'ccm'`, `'cfb'`, `'ctr'`, `'ecb'`, `'gcm'`, `'ocb'`, `'ofb'`, `'stream'`, `'wrap'`, `'xts'`.", "name": "mode", "type": "string", "desc": "The cipher mode. One of `'cbc'`, `'ccm'`, `'cfb'`, `'ctr'`, `'ecb'`, `'gcm'`, `'ocb'`, `'ofb'`, `'stream'`, `'wrap'`, `'xts'`." } ] }, "params": [ { "textRaw": "`nameOrNid`: {string|number} The name or nid of the cipher to query.", "name": "nameOrNid", "type": "string|number", "desc": "The name or nid of the cipher to query." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`keyLength`: {number} A test key length.", "name": "keyLength", "type": "number", "desc": "A test key length." }, { "textRaw": "`ivLength`: {number} A test IV length.", "name": "ivLength", "type": "number", "desc": "A test IV length." } ] } ] } ], "desc": "

Returns information about a given cipher.

\n

Some 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.

" }, { "textRaw": "`crypto.getCiphers()`", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]} An array with the names of the supported cipher algorithms.", "name": "return", "type": "string[]", "desc": "An array with the names of the supported cipher algorithms." }, "params": [] } ], "desc": "
const {\n  getCiphers\n} = await import('crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n
const {\n  getCiphers,\n} = require('crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
" }, { "textRaw": "`crypto.getCurves()`", "type": "method", "name": "getCurves", "meta": { "added": [ "v2.3.0" ], "changes": [] }, "signatures": [ { "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." }, "params": [] } ], "desc": "
const {\n  getCurves\n} = await import('crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
\n
const {\n  getCurves,\n} = require('crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
" }, { "textRaw": "`crypto.getDiffieHellman(groupName)`", "type": "method", "name": "getDiffieHellman", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellmanGroup}", "name": "return", "type": "DiffieHellmanGroup" }, "params": [ { "textRaw": "`groupName` {string}", "name": "groupName", "type": "string" } ] } ], "desc": "

Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in\nRFC 2412, but see Caveats) and 'modp14', 'modp15',\n'modp16', 'modp17', 'modp18' (defined in RFC 3526). The\nreturned 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.

\n

Example (obtaining a shared secret):

\n
const {\n  getDiffieHellman\n} = await import('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
\n
const {\n  getDiffieHellman,\n} = require('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()`", "type": "method", "name": "getFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "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}." }, "params": [] } ] }, { "textRaw": "`crypto.getHashes()`", "type": "method", "name": "getHashes", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "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." }, "params": [] } ], "desc": "
const {\n  getHashes\n} = await import('crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n
const {\n  getHashes,\n} = require('crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
" }, { "textRaw": "`crypto.hkdf(digest, ikm, salt, info, keylen, callback)`", "type": "method", "name": "hkdf", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "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. It must be at least one byte in length.", "name": "ikm", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject", "desc": "The input keying material. It must be at least one byte in 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.

\n

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.

\n
import { Buffer } from 'buffer';\nconst {\n  hkdf\n} = await import('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
\n
const {\n  hkdf,\n} = require('crypto');\nconst { Buffer } = require('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)`", "type": "method", "name": "hkdfSync", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer}", "name": "return", "type": "ArrayBuffer" }, "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. It must be at least one byte in length.", "name": "ikm", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject", "desc": "The input keying material. It must be at least one byte in 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)." } ] } ], "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.

\n

The successfully generated derivedKey will be returned as an <ArrayBuffer>.

\n

An error will be thrown if any of the input arguments specify invalid values or\ntypes, or if the derived key cannot be generated.

\n
import { Buffer } from 'buffer';\nconst {\n  hkdfSync\n} = await import('crypto');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'\n
\n
const {\n  hkdfSync,\n} = require('crypto');\nconst { Buffer } = require('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)`", "type": "method", "name": "pbkdf2", "meta": { "added": [ "v0.5.5" ], "changes": [ { "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.

\n

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.

\n

If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

\n

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.

\n

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.

\n

When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n
const {\n  pbkdf2\n} = await import('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
\n
const {\n  pbkdf2,\n} = require('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
\n

The crypto.DEFAULT_ENCODING property can be used to change the way the\nderivedKey is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.

\n
import crypto from 'crypto';\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
\n
const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
\n

An array of supported digest functions can be retrieved using\ncrypto.getHashes().

\n

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.

" }, { "textRaw": "`crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`", "type": "method", "name": "pbkdf2Sync", "meta": { "added": [ "v0.9.3" ], "changes": [ { "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": "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": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "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": "`iterations` {number}", "name": "iterations", "type": "number" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`digest` {string}", "name": "digest", "type": "string" } ] } ], "desc": "

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.

\n

If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer.

\n

If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

\n

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.

\n

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.

\n

When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n
const {\n  pbkdf2Sync\n} = await import('crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
\n
const {\n  pbkdf2Sync,\n} = require('crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
\n

The crypto.DEFAULT_ENCODING property may be used to change the way the\nderivedKey is returned. This property, however, is deprecated and use\nshould be avoided.

\n
import crypto from 'crypto';\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
\n
const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
\n

An array of supported digest functions can be retrieved using\ncrypto.getHashes().

" }, { "textRaw": "`crypto.privateDecrypt(privateKey, buffer)`", "type": "method", "name": "privateDecrypt", "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 can be an ArrayBuffer. 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": [] } ], "desc": "\n\n\n

Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().

\n

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.

" }, { "textRaw": "`crypto.privateEncrypt(privateKey, buffer)`", "type": "method", "name": "privateEncrypt", "meta": { "added": [ "v1.1.0" ], "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 passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().

\n

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.

" }, { "textRaw": "`crypto.publicDecrypt(key, buffer)`", "type": "method", "name": "publicDecrypt", "meta": { "added": [ "v1.1.0" ], "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 passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().

\n

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.

\n

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)`", "type": "method", "name": "publicEncrypt", "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": [] } ], "desc": "\n\n\n

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().

\n

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.

\n

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])`", "type": "method", "name": "randomBytes", "meta": { "added": [ "v0.5.8" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", "name": "return", "type": "Buffer", "desc": "if the `callback` function is not provided." }, "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" } ] } ] } ], "desc": "

Generates cryptographically strong pseudorandom data. The size argument\nis a number indicating the number of bytes to generate.

\n

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.

\n
// Asynchronous\nconst {\n  randomBytes\n} = await import('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('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

If 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.

\n
// Synchronous\nconst {\n  randomBytes\n} = await import('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('crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
\n

The 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.

\n

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.

\n

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.

" }, { "textRaw": "`crypto.randomFillSync(buffer[, offset][, size])`", "type": "method", "name": "randomFillSync", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer|Buffer|TypedArray|DataView} The object passed as `buffer` argument.", "name": "return", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "The object passed as `buffer` argument." }, "params": [ { "textRaw": "`buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.", "name": "buffer", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`" }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "default": "`buffer.length - offset`. The `size` must not be larger than `2**31 - 1`" } ] } ], "desc": "

Synchronous version of crypto.randomFill().

\n
import { Buffer } from 'buffer';\nconst { randomFillSync } = await import('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
\n
const { randomFillSync } = require('crypto');\nconst { Buffer } = require('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
\n

Any ArrayBuffer, TypedArray or DataView instance may be passed as\nbuffer.

\n
import { Buffer } from 'buffer';\nconst { randomFillSync } = await import('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
\n
const { randomFillSync } = require('crypto');\nconst { Buffer } = require('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.randomFill(buffer[, offset][, size], callback)`", "type": "method", "name": "randomFill", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.", "name": "buffer", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`" }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "default": "`buffer.length - offset`. The `size` must not be larger than `2**31 - 1`" }, { "textRaw": "`callback` {Function} `function(err, buf) {}`.", "name": "callback", "type": "Function", "desc": "`function(err, buf) {}`." } ] } ], "desc": "

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.

\n

If the callback function is not provided, an error will be thrown.

\n
import { Buffer } from 'buffer';\nconst { randomFill } = await import('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
\n
const { randomFill } = require('crypto');\nconst { Buffer } = require('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
\n

Any ArrayBuffer, TypedArray, or DataView instance may be passed as\nbuffer.

\n

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.

\n
import { Buffer } from 'buffer';\nconst { randomFill } = await import('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
\n
const { randomFill } = require('crypto');\nconst { Buffer } = require('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
\n

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.

\n

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.

" }, { "textRaw": "`crypto.randomInt([min, ]max[, callback])`", "type": "method", "name": "randomInt", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`min` {integer} Start of random range (inclusive). **Default:** `0`.", "name": "min", "type": "integer", "default": "`0`", "desc": "Start of random range (inclusive)." }, { "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) {}`." } ] } ], "desc": "

Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.

\n

The range (max - min) must be less than 248. min and max must\nbe safe integers.

\n

If the callback function is not provided, the random integer is\ngenerated synchronously.

\n
// Asynchronous\nconst {\n  randomInt\n} = await import('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('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('crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
\n
// Synchronous\nconst {\n  randomInt,\n} = require('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('crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
\n
// With `min` argument\nconst {\n  randomInt,\n} = require('crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
" }, { "textRaw": "`crypto.randomUUID([options])`", "type": "method", "name": "randomUUID", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "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`." } ] } ] } ], "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)`", "type": "method", "name": "scrypt", "meta": { "added": [ "v10.5.0" ], "changes": [ { "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`." } ] }, { "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.

\n

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.

\n

When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n

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.

\n

An exception is thrown when any of the input arguments specify invalid values\nor types.

\n
const {\n  scrypt\n} = await import('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
\n
const {\n  scrypt,\n} = require('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])`", "type": "method", "name": "scryptSync", "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": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "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`." } ] } ] } ], "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.

\n

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.

\n

When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.

\n

An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.

\n

An exception is thrown when any of the input arguments specify invalid values\nor types.

\n
const {\n  scryptSync\n} = await import('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
\n
const {\n  scryptSync,\n} = require('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()`", "type": "method", "name": "secureHeapUsed", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "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." } ] }, "params": [] } ] }, { "textRaw": "`crypto.setEngine(engine[, flags])`", "type": "method", "name": "setEngine", "meta": { "added": [ "v0.11.11" ], "changes": [] }, "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`" } ] } ], "desc": "

Load and set the engine for some or all OpenSSL functions (selected by flags).

\n

engine could be either an id or a path to the engine's shared library.

\n

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):

\n
    \n
  • crypto.constants.ENGINE_METHOD_RSA
  • \n
  • crypto.constants.ENGINE_METHOD_DSA
  • \n
  • crypto.constants.ENGINE_METHOD_DH
  • \n
  • crypto.constants.ENGINE_METHOD_RAND
  • \n
  • crypto.constants.ENGINE_METHOD_EC
  • \n
  • crypto.constants.ENGINE_METHOD_CIPHERS
  • \n
  • crypto.constants.ENGINE_METHOD_DIGESTS
  • \n
  • crypto.constants.ENGINE_METHOD_PKEY_METHS
  • \n
  • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
  • \n
  • crypto.constants.ENGINE_METHOD_ALL
  • \n
  • crypto.constants.ENGINE_METHOD_NONE
  • \n
\n

The flags below are deprecated in OpenSSL-1.1.0.

\n
    \n
  • crypto.constants.ENGINE_METHOD_ECDH
  • \n
  • crypto.constants.ENGINE_METHOD_ECDSA
  • \n
  • crypto.constants.ENGINE_METHOD_STORE
  • \n
" }, { "textRaw": "`crypto.setFips(bool)`", "type": "method", "name": "setFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`bool` {boolean} `true` to enable FIPS mode.", "name": "bool", "type": "boolean", "desc": "`true` to enable FIPS mode." } ] } ], "desc": "

Enables 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])`", "type": "method", "name": "sign", "meta": { "added": [ "v12.0.0" ], "changes": [ { "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": [] } ], "desc": "\n\n\n

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 (especially Ed25519 and Ed448).

\n

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:

\n
    \n
  • \n

    dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

    \n
      \n
    • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
    • \n
    • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
    • \n
    \n
  • \n
  • \n

    padding <integer> Optional padding value for RSA, one of the following:

    \n
      \n
    • crypto.constants.RSA_PKCS1_PADDING (default)
    • \n
    • crypto.constants.RSA_PKCS1_PSS_PADDING
    • \n
    \n

    RSA_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.

    \n
  • \n
  • \n

    saltLength <integer> Salt length for when padding is\nRSA_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.

    \n
  • \n
\n

If the callback function is provided this function uses libuv's threadpool.

" }, { "textRaw": "`crypto.timingSafeEqual(a, b)`", "type": "method", "name": "timingSafeEqual", "meta": { "added": [ "v6.6.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The a and b arguments can also be ArrayBuffer." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`a` {ArrayBuffer|Buffer|TypedArray|DataView}", "name": "a", "type": "ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`b` {ArrayBuffer|Buffer|TypedArray|DataView}", "name": "b", "type": "ArrayBuffer|Buffer|TypedArray|DataView" } ] } ], "desc": "

This function is based on a constant-time algorithm.\nReturns true if a is equal to b, without leaking 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.

\n

a and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same byte length.

\n

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.

\n

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.

" }, { "textRaw": "`crypto.verify(algorithm, data, key, signature[, callback])`", "type": "method", "name": "verify", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37500", "description": "Optional callback argument added." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The data, key, and signature arguments can also be ArrayBuffer." }, { "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": [] } ], "desc": "\n\n\n

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 (especially Ed25519 and Ed448).

\n

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:

\n
    \n
  • \n

    dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:

    \n
      \n
    • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
    • \n
    • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
    • \n
    \n
  • \n
  • \n

    padding <integer> Optional padding value for RSA, one of the following:

    \n
      \n
    • crypto.constants.RSA_PKCS1_PADDING (default)
    • \n
    • crypto.constants.RSA_PKCS1_PSS_PADDING
    • \n
    \n

    RSA_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.

    \n
  • \n
  • \n

    saltLength <integer> Salt length for when padding is\nRSA_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.

    \n
  • \n
\n

The signature argument is the previously calculated signature for the data.

\n

Because public keys can be derived from private keys, a private key or a public\nkey may be passed for key.

\n

If the callback function is provided this function uses libuv's threadpool.

" } ], "type": "module", "displayName": "`crypto` module methods and properties" }, { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Using strings as inputs to cryptographic APIs", "name": "using_strings_as_inputs_to_cryptographic_apis", "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.

\n

When passing strings to cryptographic APIs, consider the following factors.

\n
    \n
  • \n

    Not 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.

    \n
  • \n
  • \n

    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.

    \n
    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
    \n

    The outputs of ciphers, hash functions, signature algorithms, and key\nderivation functions are pseudorandom byte sequences and should not be\nused as Unicode strings.

    \n
  • \n
  • \n

    When 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.

    \n
  • \n
", "type": "module", "displayName": "Using strings as inputs to cryptographic APIs" }, { "textRaw": "Legacy streams API (prior to Node.js 0.10)", "name": "legacy_streams_api_(prior_to_node.js_0.10)", "desc": "

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, the many of the crypto defined 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 after Node.js v0.8 to use Buffer objects by default\ninstead.

", "type": "module", "displayName": "Legacy streams API (prior to Node.js 0.10)" }, { "textRaw": "Recent ECDH changes", "name": "recent_ecdh_changes", "desc": "

Usage of ECDH with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey() can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey() now also validates that the private key is valid for\nthe selected curve.

\n

The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or ecdh.generateKeys()\nshould be called. The main drawback of using ecdh.setPublicKey() is that\nit can be used to put the ECDH key pair into an inconsistent state.

", "type": "module", "displayName": "Recent ECDH changes" }, { "textRaw": "Support for weak or compromised algorithms", "name": "support_for_weak_or_compromised_algorithms", "desc": "

The crypto module still supports some algorithms which are already\ncompromised and are not currently 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.

\n

Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.

\n

Based on the recommendations of NIST SP 800-131A:

\n
    \n
  • MD5 and SHA-1 are no longer acceptable where collision resistance is\nrequired such as digital signatures.
  • \n
  • The key used with RSA, DSA, and DH algorithms is recommended to have\nat least 2048 bits and that of the curve of ECDSA and ECDH at least\n224 bits, to be safe to use for several years.
  • \n
  • The DH groups of modp1, modp2 and modp5 have a key size\nsmaller than 2048 bits and are not recommended.
  • \n
\n

See the reference for other recommendations and details.

", "type": "module", "displayName": "Support for weak or compromised algorithms" }, { "textRaw": "CCM mode", "name": "ccm_mode", "desc": "

CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:

\n
    \n
  • The authentication tag length must be specified during cipher creation by\nsetting the authTagLength option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.
  • \n
  • The length of the initialization vector (nonce) N must be between 7 and 13\nbytes (7 ≤ N ≤ 13).
  • \n
  • The length of the plaintext is limited to 2 ** (8 * (15 - N)) bytes.
  • \n
  • When decrypting, the authentication tag must be set via setAuthTag() before\ncalling update().\nOtherwise, decryption will fail and final() will throw an error in\ncompliance with section 2.6 of RFC 3610.
  • \n
  • Using stream methods such as write(data), end(data) or pipe() in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.
  • \n
  • When passing additional authenticated data (AAD), the length of the actual\nmessage in bytes must be passed to 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.
  • \n
  • As CCM processes the whole message at once, update() must be called exactly\nonce.
  • \n
  • Even though calling update() is sufficient to encrypt/decrypt the message,\napplications must call final() to compute or verify the\nauthentication tag.
  • \n
\n
import { Buffer } from 'buffer';\nconst {\n  createCipheriv,\n  createDecipheriv,\n  randomBytes\n} = await import('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  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
\n
const {\n  createCipheriv,\n  createDecipheriv,\n  randomBytes,\n} = require('crypto');\nconst { Buffer } = require('buffer');\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  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
", "type": "module", "displayName": "CCM mode" } ], "type": "module", "displayName": "Notes" }, { "textRaw": "Crypto constants", "name": "crypto_constants", "desc": "

The following constants exported by crypto.constants apply to various uses of\nthe crypto, tls, and https modules and are generally specific to OpenSSL.

", "modules": [ { "textRaw": "OpenSSL options", "name": "openssl_options", "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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\n for detail.
SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
SSL_OP_CIPHER_SERVER_PREFERENCEAttempts 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/man1.0.2/ssl/SSL_CTX_set_options.html.
SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's \"speshul\" version of DTLS_BAD_VER.
SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft.
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d.
SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations.
SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
SSL_OP_MICROSOFT_SESS_ID_BUG
SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation.
SSL_OP_NETSCAPE_CA_DN_BUG
SSL_OP_NETSCAPE_CHALLENGE_BUG
SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
SSL_OP_NO_QUERY_MTU
SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing\n renegotiation.
SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
SSL_OP_PKCS1_CHECK_1
SSL_OP_PKCS1_CHECK_2
SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305\n when client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled.
SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters.
SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters.
SSL_OP_SSLEAY_080_CLIENT_DH_BUG
SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
SSL_OP_TLS_BLOCK_PADDING_BUG
SSL_OP_TLS_D5_BUG
SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
", "type": "module", "displayName": "OpenSSL options" }, { "textRaw": "OpenSSL engine constants", "name": "openssl_engine_constants", "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
ConstantDescription
ENGINE_METHOD_RSALimit engine usage to RSA
ENGINE_METHOD_DSALimit engine usage to DSA
ENGINE_METHOD_DHLimit engine usage to DH
ENGINE_METHOD_RANDLimit engine usage to RAND
ENGINE_METHOD_ECLimit engine usage to EC
ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHDS
ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
ENGINE_METHOD_ALL
ENGINE_METHOD_NONE
", "type": "module", "displayName": "OpenSSL engine constants" }, { "textRaw": "Other OpenSSL constants", "name": "other_openssl_constants", "desc": "

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
ConstantDescription
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
ALPN_ENABLED
RSA_PKCS1_PADDING
RSA_SSLV23_PADDING
RSA_NO_PADDING
RSA_PKCS1_OAEP_PADDING
RSA_X931_PADDING
RSA_PKCS1_PSS_PADDING
RSA_PSS_SALTLEN_DIGESTSets the salt length for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying.
RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data.
RSA_PSS_SALTLEN_AUTOCauses 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
", "type": "module", "displayName": "Other OpenSSL constants" }, { "textRaw": "Node.js crypto constants", "name": "node.js_crypto_constants", "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
defaultCipherListSpecifies the active default cipher list used by the current Node.js\n process.
", "type": "module", "displayName": "Node.js crypto constants" } ], "type": "module", "displayName": "Crypto constants" } ], "classes": [ { "textRaw": "Class: `Certificate`", "type": "class", "name": "Certificate", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "

SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.

\n

<keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.

\n

The 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.

", "classMethods": [ { "textRaw": "Static method: `Certificate.exportChallenge(spkac[, encoding])`", "type": "classMethod", "name": "exportChallenge", "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": [ { "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." }, "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." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
\n
const { Certificate } = require('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])`", "type": "classMethod", "name": "exportPublicKey", "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": [ { "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." }, "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." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n
const { Certificate } = require('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])`", "type": "classMethod", "name": "verifySpkac", "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": [ { "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." }, "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." } ] } ], "desc": "
import { Buffer } from 'buffer';\nconst { Certificate } = await import('crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n
const { Certificate } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
" } ], "modules": [ { "textRaw": "Legacy API", "name": "legacy_api", "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.

", "ctors": [ { "textRaw": "`new crypto.Certificate()`", "type": "ctor", "name": "crypto.Certificate", "signatures": [ { "params": [] } ], "desc": "

Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:

\n
const { Certificate } = await import('crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
\n
const { Certificate } = require('crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
" } ], "methods": [ { "textRaw": "`certificate.exportChallenge(spkac[, encoding])`", "type": "method", "name": "exportChallenge", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "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." }, "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." } ] } ], "desc": "
const { Certificate } = await import('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
\n
const { Certificate } = require('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])`", "type": "method", "name": "exportPublicKey", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "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." }, "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." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n
const { Certificate } = require('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])`", "type": "method", "name": "verifySpkac", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "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." }, "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." } ] } ], "desc": "
import { Buffer } from 'buffer';\nconst { Certificate } = await import('crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n
const { Certificate } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
" } ], "type": "module", "displayName": "Legacy API" } ] }, { "textRaw": "Class: `Cipher`", "type": "class", "name": "Cipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:

\n
    \n
  • As a stream that is both readable and writable, where plain unencrypted\ndata is written to produce encrypted data on the readable side, or
  • \n
  • Using the cipher.update() and cipher.final() methods to produce\nthe encrypted data.
  • \n
\n

The crypto.createCipher() or crypto.createCipheriv() methods are\nused to create Cipher instances. Cipher objects are not to be created\ndirectly using the new keyword.

\n

Example: Using Cipher objects as streams:

\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv\n} = await import('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
\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv\n} = require('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
\n

Example: Using Cipher and piped streams:

\n
import {\n  createReadStream,\n  createWriteStream,\n} from 'fs';\n\nimport {\n  pipeline\n} from 'stream';\n\nconst {\n  scrypt,\n  randomFill,\n  createCipheriv\n} = await import('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
\n
const {\n  createReadStream,\n  createWriteStream,\n} = require('fs');\n\nconst {\n  pipeline\n} = require('stream');\n\nconst {\n  scrypt,\n  randomFill,\n  createCipheriv,\n} = require('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
\n

Example: Using the cipher.update() and cipher.final() methods:

\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv\n} = await import('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
\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv,\n} = require('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])`", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Once the cipher.final() method has been called, the Cipher object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.

" }, { "textRaw": "`cipher.getAuthTag()`", "type": "method", "name": "getAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data.", "name": "return", "type": "Buffer", "desc": "When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data." }, "params": [] } ], "desc": "

The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.

" }, { "textRaw": "`cipher.setAAD(buffer[, options])`", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "buffer", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" }, { "textRaw": "`encoding` {string} The string encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "The string encoding to use when `buffer` is a string." } ] } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

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.

\n

The cipher.setAAD() method must be called before cipher.update().

" }, { "textRaw": "`cipher.setAutoPadding([autoPadding])`", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`" } ] } ], "desc": "

When using block encryption algorithms, the Cipher class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).

\n

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.

\n

The cipher.setAutoPadding() method must be called before\ncipher.final().

" }, { "textRaw": "`cipher.update(data[, inputEncoding][, outputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the data.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the data." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

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.

\n

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.

\n

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.

" } ] }, { "textRaw": "Class: `Decipher`", "type": "class", "name": "Decipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:

\n
    \n
  • As a stream that is both readable and writable, where plain encrypted\ndata is written to produce unencrypted data on the readable side, or
  • \n
  • Using the decipher.update() and decipher.final() methods to\nproduce the unencrypted data.
  • \n
\n

The crypto.createDecipher() or crypto.createDecipheriv() methods are\nused to create Decipher instances. Decipher objects are not to be created\ndirectly using the new keyword.

\n

Example: Using Decipher objects as streams:

\n
import { Buffer } from 'buffer';\nconst {\n  scryptSync,\n  createDecipheriv\n} = await import('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  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
\n
const {\n  scryptSync,\n  createDecipheriv,\n} = require('crypto');\nconst { Buffer } = require('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  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
\n

Example: Using Decipher and piped streams:

\n
import {\n  createReadStream,\n  createWriteStream,\n} from 'fs';\nimport { Buffer } from 'buffer';\nconst {\n  scryptSync,\n  createDecipheriv\n} = await import('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
\n
const {\n  createReadStream,\n  createWriteStream,\n} = require('fs');\nconst {\n  scryptSync,\n  createDecipheriv,\n} = require('crypto');\nconst { Buffer } = require('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
\n

Example: Using the decipher.update() and decipher.final() methods:

\n
import { Buffer } from 'buffer';\nconst {\n  scryptSync,\n  createDecipheriv\n} = await import('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
\n
const {\n  scryptSync,\n  createDecipheriv,\n} = require('crypto');\nconst { Buffer } = require('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])`", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Once the decipher.final() method has been called, the Decipher object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.

" }, { "textRaw": "`decipher.setAAD(buffer[, options])`", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "buffer", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" }, { "textRaw": "`encoding` {string} String encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "String encoding to use when `buffer` is a string." } ] } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

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.

\n

The decipher.setAAD() method must be called before decipher.update().

\n

When passing a string as the buffer, please consider\ncaveats when using strings as inputs to cryptographic APIs.

" }, { "textRaw": "`decipher.setAuthTag(buffer[, encoding])`", "type": "method", "name": "setAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/17825", "description": "This method now throws if the GCM tag length is invalid." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|Buffer|ArrayBuffer|TypedArray|DataView}", "name": "buffer", "type": "string|Buffer|ArrayBuffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} String encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "String encoding to use when `buffer` is a string." } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB 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.

\n

The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes.\ndecipher.setAuthTag() can only be called once.

\n

When passing a string as the authentication tag, please consider\ncaveats when using strings as inputs to cryptographic APIs.

" }, { "textRaw": "`decipher.setAutoPadding([autoPadding])`", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`" } ] } ], "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.

\n

Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.

\n

The decipher.setAutoPadding() method must be called before\ndecipher.final().

" }, { "textRaw": "`decipher.update(data[, inputEncoding][, outputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

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.

\n

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.

\n

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.

" } ] }, { "textRaw": "Class: `DiffieHellman`", "type": "class", "name": "DiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.

\n

Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.

\n
import assert from 'assert';\n\nconst {\n  createDiffieHellman\n} = await import('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
\n
const assert = require('assert');\n\nconst {\n  createDiffieHellman,\n} = require('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])`", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "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." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "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.

\n

If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.

" }, { "textRaw": "`diffieHellman.generateKeys([encoding])`", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Generates private and public Diffie-Hellman key values, 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.

" }, { "textRaw": "`diffieHellman.getGenerator([encoding])`", "type": "method", "name": "getGenerator", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPrime([encoding])`", "type": "method", "name": "getPrime", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPrivateKey([encoding])`", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPublicKey([encoding])`", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.setPrivateKey(privateKey[, encoding])`", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "privateKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string." } ] } ], "desc": "

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.

" }, { "textRaw": "`diffieHellman.setPublicKey(publicKey[, encoding])`", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "publicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string." } ] } ], "desc": "

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.

" } ], "properties": [ { "textRaw": "`diffieHellman.verifyError`", "name": "verifyError", "meta": { "added": [ "v0.11.12" ], "changes": [] }, "desc": "

A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.

\n

The following values are valid for this property (as defined in constants\nmodule):

\n
    \n
  • DH_CHECK_P_NOT_SAFE_PRIME
  • \n
  • DH_CHECK_P_NOT_PRIME
  • \n
  • DH_UNABLE_TO_CHECK_GENERATOR
  • \n
  • DH_NOT_SUITABLE_GENERATOR
  • \n
" } ] }, { "textRaw": "Class: `DiffieHellmanGroup`", "type": "class", "name": "DiffieHellmanGroup", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "desc": "

The 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.

\n
const { createDiffieHellmanGroup } = await import('crypto');\nconst dh = createDiffieHellmanGroup('modp1');\n
\n
const { createDiffieHellmanGroup } = require('crypto');\nconst dh = createDiffieHellmanGroup('modp1');\n
\n

The name (e.g. 'modp1') is taken from RFC 2412 (modp1 and 2) and\nRFC 3526:

\n
$ perl -ne 'print \"$1\\n\" if /\"(modp\\d+)\"/' src/node_crypto_groups.h\nmodp1  #  768 bits\nmodp2  # 1024 bits\nmodp5  # 1536 bits\nmodp14 # 2048 bits\nmodp15 # etc.\nmodp16\nmodp17\nmodp18\n
" }, { "textRaw": "Class: `ECDH`", "type": "class", "name": "ECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "

The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.

\n

Instances of the ECDH class can be created using the\ncrypto.createECDH() function.

\n
import assert from 'assert';\n\nconst {\n  createECDH\n} = await import('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
\n
const assert = require('assert');\n\nconst {\n  createECDH,\n} = require('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]]])`", "type": "classMethod", "name": "convertKey", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "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." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "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.

\n

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.

\n

If format is not specified the point will be returned in 'uncompressed'\nformat.

\n

If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.

\n

Example (uncompressing a key):

\n
const {\n  createECDH,\n  ECDH\n} = await import('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
\n
const {\n  createECDH,\n  ECDH,\n} = require('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])`", "type": "method", "name": "computeSecret", "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": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "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." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "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.

\n

If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.

\n

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.

" }, { "textRaw": "`ecdh.generateKeys([encoding[, format]])`", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "desc": "

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.

\n

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.

\n

If encoding is provided a string is returned; otherwise a Buffer\nis returned.

" }, { "textRaw": "`ecdh.getPrivateKey([encoding])`", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman in the specified `encoding`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

" }, { "textRaw": "`ecdh.getPublicKey([encoding][, format])`", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified `encoding` and `format`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman public key in the specified `encoding` and `format`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "desc": "

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.

\n

If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

" }, { "textRaw": "`ecdh.setPrivateKey(privateKey[, encoding])`", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "privateKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string." } ] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`ecdh.setPublicKey(publicKey[, encoding])`", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.11.14" ], "deprecated": [ "v5.2.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "publicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string." } ] } ], "desc": "

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.

\n

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.

\n

Example (obtaining a shared secret):

\n
const {\n  createECDH,\n  createHash\n} = await import('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
\n
const {\n  createECDH,\n  createHash,\n} = require('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`", "type": "class", "name": "Hash", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:

\n
    \n
  • As a stream that is both readable and writable, where data is written\nto produce a computed hash digest on the readable side, or
  • \n
  • Using the hash.update() and hash.digest() methods to produce the\ncomputed hash.
  • \n
\n

The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.

\n

Example: Using Hash objects as streams:

\n
const {\n  createHash\n} = await import('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
\n
const {\n  createHash,\n} = require('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
\n

Example: Using Hash and piped streams:

\n
import { createReadStream } from 'fs';\nimport { stdout } from 'process';\nconst { createHash } = await import('crypto');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
\n
const { createReadStream } = require('fs');\nconst { createHash } = require('crypto');\nconst { stdout } = require('process');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
\n

Example: Using the hash.update() and hash.digest() methods:

\n
const {\n  createHash\n} = await import('crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
\n
const {\n  createHash,\n} = require('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])`", "type": "method", "name": "copy", "meta": { "added": [ "v13.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Hash}", "name": "return", "type": "Hash" }, "params": [ { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.

\n

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.

\n

An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.

\n
// Calculate a rolling hash.\nconst {\n  createHash\n} = await import('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('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])`", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "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.

\n

The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.

" }, { "textRaw": "`hash.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "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": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

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.

\n

This can be called many times with new data as it is streamed.

" } ] }, { "textRaw": "Class: `Hmac`", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:

\n
    \n
  • As a stream that is both readable and writable, where data is written\nto produce a computed HMAC digest on the readable side, or
  • \n
  • Using the hmac.update() and hmac.digest() methods to produce the\ncomputed HMAC digest.
  • \n
\n

The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.

\n

Example: Using Hmac objects as streams:

\n
const {\n  createHmac\n} = await import('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
\n
const {\n  createHmac,\n} = require('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
\n

Example: Using Hmac and piped streams:

\n
import { createReadStream } from 'fs';\nimport { stdout } from 'process';\nconst {\n  createHmac\n} = await import('crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHmac,\n} = require('crypto');\nconst { stdout } = require('process');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
\n

Example: Using the hmac.update() and hmac.digest() methods:

\n
const {\n  createHmac\n} = await import('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
\n
const {\n  createHmac,\n} = require('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])`", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "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;

\n

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.

" }, { "textRaw": "`hmac.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "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": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

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.

\n

This can be called many times with new data as it is streamed.

" } ] }, { "textRaw": "Class: `KeyObject`", "type": "class", "name": "KeyObject", "meta": { "added": [ "v11.6.0" ], "changes": [ { "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.

\n

Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.

\n

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.

", "classMethods": [ { "textRaw": "Static method: `KeyObject.from(key)`", "type": "classMethod", "name": "from", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`key` {CryptoKey}", "name": "key", "type": "CryptoKey" } ] } ], "desc": "

Example: Converting a CryptoKey instance to a KeyObject:

\n
const { webcrypto, KeyObject } = await import('crypto');\nconst { subtle } = webcrypto;\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
\n
const {\n  webcrypto: {\n    subtle,\n  },\n  KeyObject,\n} = require('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": "`asymmetricKeyDetails` {Object}", "type": "Object", "name": "asymmetricKeyDetails", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "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": "`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)." } ], "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.

\n

RSA-PSS parameters, DH, or any future key type details might be exposed via this\nAPI using additional attributes.

" }, { "textRaw": "`asymmetricKeyType` {string}", "type": "string", "name": "asymmetricKeyType", "meta": { "added": [ "v11.6.0" ], "changes": [ { "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. Supported key\ntypes are:

\n
    \n
  • 'rsa' (OID 1.2.840.113549.1.1.1)
  • \n
  • 'rsa-pss' (OID 1.2.840.113549.1.1.10)
  • \n
  • 'dsa' (OID 1.2.840.10040.4.1)
  • \n
  • 'ec' (OID 1.2.840.10045.2.1)
  • \n
  • 'x25519' (OID 1.3.101.110)
  • \n
  • 'x448' (OID 1.3.101.111)
  • \n
  • 'ed25519' (OID 1.3.101.112)
  • \n
  • 'ed448' (OID 1.3.101.113)
  • \n
  • 'dh' (OID 1.2.840.113549.1.3.1)
  • \n
\n

This property is undefined for unrecognized KeyObject types and symmetric\nkeys.

" }, { "textRaw": "`symmetricKeySize` {number}", "type": "number", "name": "symmetricKeySize", "meta": { "added": [ "v11.6.0" ], "changes": [] }, "desc": "

For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.

" }, { "textRaw": "`type` {string}", "type": "string", "name": "type", "meta": { "added": [ "v11.6.0" ], "changes": [] }, "desc": "

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.

" } ], "methods": [ { "textRaw": "`keyObject.export([options])`", "type": "method", "name": "export", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37081", "description": "Added support for `'jwk'` format." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string | Buffer | Object}", "name": "return", "type": "string | Buffer | Object" }, "params": [ { "textRaw": "`options`: {Object}", "name": "options", "type": "Object" } ] } ], "desc": "

For symmetric keys, the following encoding options can be used:

\n
    \n
  • format: <string> Must be 'buffer' (default) or 'jwk'.
  • \n
\n

For public keys, the following encoding options can be used:

\n
    \n
  • type: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.
  • \n
  • format: <string> Must be 'pem', 'der', or 'jwk'.
  • \n
\n

For private keys, the following encoding options can be used:

\n
    \n
  • type: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or\n'sec1' (EC only).
  • \n
  • format: <string> Must be 'pem', 'der', or 'jwk'.
  • \n
  • cipher: <string> If specified, the private key will be encrypted with\nthe given cipher and passphrase using PKCS#5 v2.0 password based\nencryption.
  • \n
  • passphrase: <string> | <Buffer> The passphrase to use for encryption, see\ncipher.
  • \n
\n

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.

\n

When JWK encoding format was selected, all other encoding options are\nignored.

\n

PKCS#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.

" } ] }, { "textRaw": "Class: `Sign`", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Sign class is a utility for generating signatures. It can be used in one\nof two ways:

\n
    \n
  • As a writable stream, where data to be signed is written and the\nsign.sign() method is used to generate and return the signature, or
  • \n
  • Using the sign.update() and sign.sign() methods to produce the\nsignature.
  • \n
\n

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.

\n

Example: Using Sign and Verify objects as streams:

\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify\n} = await import('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
\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify,\n} = require('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
\n

Example: Using the sign.update() and verify.update() methods:

\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify\n} = await import('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
\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify,\n} = require('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])`", "type": "method", "name": "sign", "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": [] } ], "desc": "\n\n\n

Calculates the signature on all the data passed through using either\nsign.update() or sign.write().

\n

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:

\n
    \n
  • \n

    dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:

    \n
      \n
    • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
    • \n
    • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
    • \n
    \n
  • \n
  • \n

    padding <integer> Optional padding value for RSA, one of the following:

    \n
      \n
    • crypto.constants.RSA_PKCS1_PADDING (default)
    • \n
    • crypto.constants.RSA_PKCS1_PSS_PADDING
    • \n
    \n

    RSA_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.

    \n
  • \n
  • \n

    saltLength <integer> Salt length for when padding is\nRSA_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.

    \n
  • \n
\n

If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.

\n

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.

" }, { "textRaw": "`sign.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "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": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

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.

\n

This can be called many times with new data as it is streamed.

" } ] }, { "textRaw": "Class: `Verify`", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:

\n
    \n
  • As a writable stream where written data is used to validate against the\nsupplied signature, or
  • \n
  • Using the verify.update() and verify.verify() methods to verify\nthe signature.
  • \n
\n

The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.

\n

See Sign for examples.

", "methods": [ { "textRaw": "`verify.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "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": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

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.

\n

This can be called many times with new data as it is streamed.

" }, { "textRaw": "`verify.verify(object, signature[, signatureEncoding])`", "type": "method", "name": "verify", "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": [] } ], "desc": "\n\n\n

Verifies the provided data using the given object and signature.

\n

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:

\n
    \n
  • \n

    dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:

    \n
      \n
    • 'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).
    • \n
    • 'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.
    • \n
    \n
  • \n
  • \n

    padding <integer> Optional padding value for RSA, one of the following:

    \n
      \n
    • crypto.constants.RSA_PKCS1_PADDING (default)
    • \n
    • crypto.constants.RSA_PKCS1_PSS_PADDING
    • \n
    \n

    RSA_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.

    \n
  • \n
  • \n

    saltLength <integer> Salt length for when padding is\nRSA_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.

    \n
  • \n
\n

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.

\n

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.

\n

Because public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

" } ] }, { "textRaw": "Class: `X509Certificate`", "type": "class", "name": "X509Certificate", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

Encapsulates an X509 certificate and provides read-only access to\nits information.

\n
const { X509Certificate } = await import('crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
\n
const { X509Certificate } = require('crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
", "properties": [ { "textRaw": "`ca` Type: {boolean} Will be `true` if this is a Certificate Authority (ca) certificate.", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "Will be `true` if this is a Certificate Authority (ca) certificate." }, { "textRaw": "`fingerprint` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The SHA-1 fingerprint of this certificate.

" }, { "textRaw": "`fingerprint256` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The SHA-256 fingerprint of this certificate.

" }, { "textRaw": "`infoAccess` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The information access content of this certificate.

" }, { "textRaw": "`issuer` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The issuer identification included in this certificate.

" }, { "textRaw": "`issuerCertificate` Type: {X509Certificate}", "type": "X509Certificate", "name": "Type", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "desc": "

The issuer certificate or undefined if the issuer certificate is not\navailable.

" }, { "textRaw": "`keyUsage` Type: {string[]}", "type": "string[]", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

An array detailing the key usages for this certificate.

" }, { "textRaw": "`publicKey` Type: {KeyObject}", "type": "KeyObject", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The public key <KeyObject> for this certificate.

" }, { "textRaw": "`raw` Type: {Buffer}", "type": "Buffer", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

A Buffer containing the DER encoding of this certificate.

" }, { "textRaw": "`serialNumber` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The serial number of this certificate.

" }, { "textRaw": "`subject` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The complete subject of this certificate.

" }, { "textRaw": "`subjectAltName` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The subject alternative name specified for this certificate.

" }, { "textRaw": "`validFrom` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The date/time from which this certificate is considered valid.

" }, { "textRaw": "`validTo` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The date/time until which this certificate is considered valid.

" } ], "methods": [ { "textRaw": "`x509.checkEmail(email[, options])`", "type": "method", "name": "checkEmail", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`email` {string}", "name": "email", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Checks whether the certificate matches the given email address.

" }, { "textRaw": "`x509.checkHost(name[, options])`", "type": "method", "name": "checkHost", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|undefined} Returns `name` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `name` if the certificate matches, `undefined` if it does not." }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Checks whether the certificate matches the given host name.

" }, { "textRaw": "`x509.checkIP(ip[, options])`", "type": "method", "name": "checkIP", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|undefined} Returns `ip` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `ip` if the certificate matches, `undefined` if it does not." }, "params": [ { "textRaw": "`ip` {string}", "name": "ip", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Checks whether the certificate matches the given IP address (IPv4 or IPv6).

" }, { "textRaw": "`x509.checkIssued(otherCert)`", "type": "method", "name": "checkIssued", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`otherCert` {X509Certificate}", "name": "otherCert", "type": "X509Certificate" } ] } ], "desc": "

Checks whether this certificate was issued by the given otherCert.

" }, { "textRaw": "`x509.checkPrivateKey(privateKey)`", "type": "method", "name": "checkPrivateKey", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`privateKey` {KeyObject} A private key.", "name": "privateKey", "type": "KeyObject", "desc": "A private key." } ] } ], "desc": "

Checks whether the public key for this certificate is consistent with\nthe given private key.

" }, { "textRaw": "`x509.toJSON()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {string}", "name": "Type", "type": "string" } ] } ], "desc": "

There is no standard JSON encoding for X509 certificates. The\ntoJSON() method returns a string containing the PEM encoded\ncertificate.

" }, { "textRaw": "`x509.toLegacyObject()`", "type": "method", "name": "toLegacyObject", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {Object}", "name": "Type", "type": "Object" } ] } ], "desc": "

Returns information about this certificate using the legacy\ncertificate object encoding.

" }, { "textRaw": "`x509.toString()`", "type": "method", "name": "toString", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {string}", "name": "Type", "type": "string" } ] } ], "desc": "

Returns the PEM-encoded certificate.

" }, { "textRaw": "`x509.verify(publicKey)`", "type": "method", "name": "verify", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`publicKey` {KeyObject} A public key.", "name": "publicKey", "type": "KeyObject", "desc": "A public key." } ] } ], "desc": "

Verifies that this certificate was signed by the given public key.\nDoes not perform any other validation checks on the certificate.

" } ], "signatures": [ { "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." } ] } ] } ], "type": "module", "displayName": "Crypto", "source": "doc/api/crypto.md" }, { "textRaw": "Diagnostics Channel", "name": "diagnostics_channel", "introduced_in": "v15.1.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Source Code: lib/diagnostics_channel.js

\n

The diagnostics_channel module provides an API to create named channels\nto report arbitrary message data for diagnostics purposes.

\n

It can be accessed using:

\n
import diagnostics_channel from 'diagnostics_channel';\n
\n
const diagnostics_channel = require('diagnostics_channel');\n
\n

It 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.

\n

If 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", "modules": [ { "textRaw": "Overview", "name": "overview", "desc": "

Following is a simple overview of the public API.

\n
import diagnostics_channel from 'diagnostics_channel';\n\n// Get a reusable channel object\nconst channel = diagnostics_channel.channel('my-channel');\n\n// Subscribe to the channel\nchannel.subscribe((message, name) => {\n  // Received data\n});\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
const diagnostics_channel = require('diagnostics_channel');\n\n// Get a reusable channel object\nconst channel = diagnostics_channel.channel('my-channel');\n\n// Subscribe to the channel\nchannel.subscribe((message, name) => {\n  // Received data\n});\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
", "methods": [ { "textRaw": "`diagnostics_channel.hasSubscribers(name)`", "type": "method", "name": "hasSubscribers", "signatures": [ { "return": { "textRaw": "Returns: {boolean} If there are active subscribers", "name": "return", "type": "boolean", "desc": "If there are active subscribers" }, "params": [ { "textRaw": "`name` {string|symbol} The channel name", "name": "name", "type": "string|symbol", "desc": "The channel name" } ] } ], "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.

\n

This API is optional but helpful when trying to publish messages from very\nperformance-sensitive code.

\n
import diagnostics_channel from 'diagnostics_channel';\n\nif (diagnostics_channel.hasSubscribers('my-channel')) {\n  // There are subscribers, prepare and publish message\n}\n
\n
const diagnostics_channel = require('diagnostics_channel');\n\nif (diagnostics_channel.hasSubscribers('my-channel')) {\n  // There are subscribers, prepare and publish message\n}\n
" }, { "textRaw": "`diagnostics_channel.channel(name)`", "type": "method", "name": "channel", "signatures": [ { "return": { "textRaw": "Returns: {Channel} The named channel object", "name": "return", "type": "Channel", "desc": "The named channel object" }, "params": [ { "textRaw": "`name` {string|symbol} The channel name", "name": "name", "type": "string|symbol", "desc": "The channel name" } ] } ], "desc": "

This is the primary entry-point for anyone wanting to interact with a named\nchannel. It produces a channel object which is optimized to reduce overhead at\npublish time as much as possible.

\n
import diagnostics_channel from 'diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n
\n
const diagnostics_channel = require('diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n
" } ], "type": "module", "displayName": "Overview" } ], "classes": [ { "textRaw": "Class: `Channel`", "type": "class", "name": "Channel", "desc": "

The class Channel represents an individual named channel within the data\npipeline. It is use 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.

", "properties": [ { "textRaw": "`hasSubscribers` Returns: {boolean} If there are active subscribers", "type": "boolean", "name": "return", "desc": "

Check if there are active subscribers to this channel. This is helpful if\nthe message you want to send might be expensive to prepare.

\n

This API is optional but helpful when trying to publish messages from very\nperformance-sensitive code.

\n
import diagnostics_channel from 'diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nif (channel.hasSubscribers) {\n  // There are subscribers, prepare and publish message\n}\n
\n
const diagnostics_channel = require('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)`", "type": "method", "name": "publish", "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.

\n
import diagnostics_channel from 'diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.publish({\n  some: 'message'\n});\n
\n
const diagnostics_channel = require('diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.publish({\n  some: 'message'\n});\n
" }, { "textRaw": "`channel.subscribe(onMessage)`", "type": "method", "name": "subscribe", "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'.

\n
import diagnostics_channel from 'diagnostics_channel';\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.subscribe((message, name) => {\n  // Received data\n});\n
\n
const diagnostics_channel = require('diagnostics_channel');\n\nconst channel = diagnostics_channel.channel('my-channel');\n\nchannel.subscribe((message, name) => {\n  // Received data\n});\n
" }, { "textRaw": "`channel.unsubscribe(onMessage)`", "type": "method", "name": "unsubscribe", "signatures": [ { "params": [ { "textRaw": "`onMessage` {Function} The previous subscribed handler to remove", "name": "onMessage", "type": "Function", "desc": "The previous subscribed handler to remove" } ] } ], "desc": "

Remove a message handler previously registered to this channel with\nchannel.subscribe(onMessage).

\n
import diagnostics_channel from '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
\n
const diagnostics_channel = require('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
" } ] } ], "type": "module", "displayName": "Public API" } ], "type": "module", "displayName": "Diagnostics Channel", "source": "doc/api/diagnostics_channel.md" }, { "textRaw": "DNS", "name": "dns", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/dns.js

\n

The dns module enables name resolution. For example, use it to look up IP\naddresses of host names.

\n

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().

\n
const dns = require('dns');\n\ndns.lookup('example.org', (err, address, family) => {\n  console.log('address: %j family: IPv%s', address, family);\n});\n// address: \"93.184.216.34\" family: IPv4\n
\n

All other functions in the 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.

\n
const dns = require('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
\n

See the Implementation considerations section for more information.

", "classes": [ { "textRaw": "Class: `dns.Resolver`", "type": "class", "name": "dns.Resolver", "meta": { "added": [ "v8.3.0" ], "changes": [] }, "desc": "

An independent resolver for DNS requests.

\n

Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

\n
const { Resolver } = require('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
\n

The following methods from the dns module are available:

\n", "methods": [ { "textRaw": "`Resolver([options])`", "type": "method", "name": "Resolver", "meta": { "added": [ "v8.3.0" ], "changes": [ { "version": "v16.7.0", "pr-url": "https://github.com/nodejs/node/pull/39610", "description": "The `options` object now accepts a `tries` option." }, { "version": "v12.18.3", "pr-url": "https://github.com/nodejs/node/pull/33472", "description": "The constructor now accepts an `options` object. The single supported option is `timeout`." } ] }, "signatures": [ { "params": [] } ], "desc": "

Create a new resolver.

\n
    \n
  • options <Object>\n
      \n
    • timeout <integer> Query timeout in milliseconds, or -1 to use the\ndefault timeout.
    • \n
    • tries <integer> The number of tries the resolver will try contacting\neach name server before giving up. Default: 4
    • \n
    \n
  • \n
" }, { "textRaw": "`resolver.cancel()`", "type": "method", "name": "cancel", "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.

" }, { "textRaw": "`resolver.setLocalAddress([ipv4][, ipv6])`", "type": "method", "name": "setLocalAddress", "meta": { "added": [ "v15.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`ipv4` {string} A string representation of an IPv4 address. **Default:** `'0.0.0.0'`", "name": "ipv4", "type": "string", "default": "`'0.0.0.0'`", "desc": "A string representation of an IPv4 address." }, { "textRaw": "`ipv6` {string} A string representation of an IPv6 address. **Default:** `'::0'`", "name": "ipv6", "type": "string", "default": "`'::0'`", "desc": "A string representation of an IPv6 address." } ] } ], "desc": "

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.

\n

If a v4 or v6 address is not specified, it is set to the default, and the\noperating system will choose a local address automatically.

\n

The 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.

" } ] } ], "methods": [ { "textRaw": "`dns.getServers()`", "type": "method", "name": "getServers", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

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
[\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053',\n]\n
" }, { "textRaw": "`dns.lookup(hostname[, options], callback)`", "type": "method", "name": "lookup", "meta": { "added": [ "v0.1.90" ], "changes": [ { "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} The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned. **Default:** `0`.", "name": "family", "type": "integer", "default": "`0`", "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." }, { "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": "`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. **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`][]. New code should use `{ verbatim: true }`.", "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`][]. New code should use `{ verbatim: true }`", "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." } ] }, { "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 IPv4\nand IPv6 addresses are both returned if found.

\n

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.

\n

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.

\n

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().

\n

Example usage:

\n
const dns = require('dns');\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\ndns.lookup('example.com', options, (err, address, family) =>\n  console.log('address: %j family: IPv%s', address, family));\n// address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndns.lookup('example.com', options, (err, addresses) =>\n  console.log('addresses: %j', addresses));\n// addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n
\n

If 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.

", "modules": [ { "textRaw": "Supported getaddrinfo flags", "name": "supported_getaddrinfo_flags", "meta": { "changes": [ { "version": [ "v13.13.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32183", "description": "Added support for the `dns.ALL` flag." } ] }, "desc": "

The following flags can be passed as hints to dns.lookup().

\n
    \n
  • 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.
  • \n
  • 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).
  • \n
  • dns.ALL: If dns.V4MAPPED is specified, return resolved IPv6 addresses as\nwell as IPv4 mapped IPv6 addresses.
  • \n
", "type": "module", "displayName": "Supported getaddrinfo flags" } ] }, { "textRaw": "`dns.lookupService(address, port, callback)`", "type": "method", "name": "lookupService", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`address` {string}", "name": "address", "type": "string" }, { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`hostname` {string} e.g. `example.com`", "name": "hostname", "type": "string", "desc": "e.g. `example.com`" }, { "textRaw": "`service` {string} e.g. `http`", "name": "service", "type": "string", "desc": "e.g. `http`" } ] } ] } ], "desc": "

Resolves the given address and port into a host name and service using\nthe operating system's underlying getnameinfo implementation.

\n

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.

\n

On an error, err is an Error object, where err.code is the error code.

\n
const dns = require('dns');\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n  console.log(hostname, service);\n  // Prints: localhost ssh\n});\n
\n

If this method is invoked as its util.promisify()ed version, it returns a\nPromise for an Object with hostname and service properties.

" }, { "textRaw": "`dns.resolve(hostname[, rrtype], callback)`", "type": "method", "name": "resolve", "meta": { "added": [ "v0.1.27" ], "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." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`records` {string[] | Object[] | Object}", "name": "records", "type": "string[] | Object[] | Object" } ] } ] } ], "desc": "

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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
rrtyperecords containsResult typeShorthand 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()
'TXT'text records<string[]>dns.resolveTxt()
\n

On error, err is an Error object, where err.code is one of the\nDNS error codes.

" }, { "textRaw": "`dns.resolve4(hostname[, options], callback)`", "type": "method", "name": "resolve4", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9296", "description": "This method now supports passing `options`, specifically `options.ttl`." } ] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} Host name to resolve.", "name": "hostname", "type": "string", "desc": "Host name to resolve." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", "name": "ttl", "type": "boolean", "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`addresses` {string[] | Object[]}", "name": "addresses", "type": "string[] | Object[]" } ] } ] } ], "desc": "

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']).

" }, { "textRaw": "`dns.resolve6(hostname[, options], callback)`", "type": "method", "name": "resolve6", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9296", "description": "This method now supports passing `options`, specifically `options.ttl`." } ] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} Host name to resolve.", "name": "hostname", "type": "string", "desc": "Host name to resolve." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", "name": "ttl", "type": "boolean", "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the callback receives an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`addresses` {string[] | Object[]}", "name": "addresses", "type": "string[] | Object[]" } ] } ] } ], "desc": "

Uses the DNS protocol to resolve a IPv6 addresses (AAAA records) for the\nhostname. The addresses argument passed to the callback function\nwill contain an array of IPv6 addresses.

" }, { "textRaw": "`dns.resolveAny(hostname, callback)`", "type": "method", "name": "resolveAny", "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": "`ret` {Object[]}", "name": "ret", "type": "Object[]" } ] } ] } ], "desc": "

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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
TypeProperties
'A'address/ttl
'AAAA'address/ttl
'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()
'TXT'This type of record contains an array property called entries which refers to dns.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
\n

Here is an example of the ret object passed to the callback:

\n\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
\n

DNS 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.

" }, { "textRaw": "`dns.resolveCname(hostname, callback)`", "type": "method", "name": "resolveCname", "meta": { "added": [ "v0.3.2" ], "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": "`addresses` {string[]}", "name": "addresses", "type": "string[]" } ] } ] } ], "desc": "

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']).

" }, { "textRaw": "`dns.resolveCaa(hostname, callback)`", "type": "method", "name": "resolveCaa", "meta": { "added": [ "v15.0.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 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'}]).

" }, { "textRaw": "`dns.resolveMx(hostname, callback)`", "type": "method", "name": "resolveMx", "meta": { "added": [ "v0.1.27" ], "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": "`addresses` {Object[]}", "name": "addresses", "type": "Object[]" } ] } ] } ], "desc": "

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'}, ...]).

" }, { "textRaw": "`dns.resolveNaptr(hostname, callback)`", "type": "method", "name": "resolveNaptr", "meta": { "added": [ "v0.9.12" ], "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": "`addresses` {Object[]}", "name": "addresses", "type": "Object[]" } ] } ] } ], "desc": "

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:

\n
    \n
  • flags
  • \n
  • service
  • \n
  • regexp
  • \n
  • replacement
  • \n
  • order
  • \n
  • preference
  • \n
\n\n
{\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)`", "type": "method", "name": "resolveNs", "meta": { "added": [ "v0.1.90" ], "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": "`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']).

" }, { "textRaw": "`dns.resolvePtr(hostname, callback)`", "type": "method", "name": "resolvePtr", "meta": { "added": [ "v6.0.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": "`addresses` {string[]}", "name": "addresses", "type": "string[]" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`dns.resolveSoa(hostname, callback)`", "type": "method", "name": "resolveSoa", "meta": { "added": [ "v0.11.10" ], "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": "`address` {Object}", "name": "address", "type": "Object" } ] } ] } ], "desc": "

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:

\n
    \n
  • nsname
  • \n
  • hostmaster
  • \n
  • serial
  • \n
  • refresh
  • \n
  • retry
  • \n
  • expire
  • \n
  • minttl
  • \n
\n\n
{\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)`", "type": "method", "name": "resolveSrv", "meta": { "added": [ "v0.1.27" ], "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": "`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:

\n
    \n
  • priority
  • \n
  • weight
  • \n
  • port
  • \n
  • name
  • \n
\n\n
{\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
" }, { "textRaw": "`dns.resolveTxt(hostname, callback)`", "type": "method", "name": "resolveTxt", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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.

" }, { "textRaw": "`dns.reverse(ip, callback)`", "type": "method", "name": "reverse", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`ip` {string}", "name": "ip", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`hostnames` {string[]}", "name": "hostnames", "type": "string[]" } ] } ] } ], "desc": "

Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

\n

On error, err is an Error object, where err.code is\none of the DNS error codes.

" }, { "textRaw": "`dns.setDefaultResultOrder(order)`", "type": "method", "name": "setDefaultResultOrder", "meta": { "added": [ "v16.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`order` {string} must be `'ipv4first'` or `'verbatim'`.", "name": "order", "type": "string", "desc": "must be `'ipv4first'` or `'verbatim'`." } ] } ], "desc": "

Set the default value of verbatim in dns.lookup() and\ndnsPromises.lookup(). The value could be:

\n
    \n
  • ipv4first: sets default verbatim false.
  • \n
  • verbatim: sets default verbatim true.
  • \n
\n

The default is ipv4first 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.

" }, { "textRaw": "`dns.setServers(servers)`", "type": "method", "name": "setServers", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", "name": "servers", "type": "string[]", "desc": "array of [RFC 5952][] formatted addresses" } ] } ], "desc": "

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.

\n
dns.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053',\n]);\n
\n

An error will be thrown if an invalid address is provided.

\n

The dns.setServers() method must not be called while a DNS query is in\nprogress.

\n

The dns.setServers() method affects only dns.resolve(),\ndns.resolve*() and dns.reverse() (and specifically not\ndns.lookup()).

\n

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.

" } ], "modules": [ { "textRaw": "DNS promises API", "name": "dns_promises_api", "meta": { "added": [ "v10.6.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/32953", "description": "Exposed as `require('dns/promises')`." }, { "version": [ "v11.14.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/26592", "description": "This API is no longer experimental." } ] }, "desc": "

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('dns').promises or require('dns/promises').

", "classes": [ { "textRaw": "Class: `dnsPromises.Resolver`", "type": "class", "name": "dnsPromises.Resolver", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "desc": "

An independent resolver for DNS requests.

\n

Creating a new resolver uses the default server settings. Setting\nthe servers used for a resolver using\nresolver.setServers() does not affect\nother resolvers:

\n
const { Resolver } = require('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
\n

The following methods from the dnsPromises API are available:

\n" } ], "methods": [ { "textRaw": "`resolver.cancel()`", "type": "method", "name": "cancel", "meta": { "added": [ "v15.3.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Cancel all outstanding DNS queries made by this resolver. The corresponding\npromises will be rejected with an error with code ECANCELLED.

" }, { "textRaw": "`dnsPromises.getServers()`", "type": "method", "name": "getServers", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

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
[\n  '4.4.4.4',\n  '2001:4860:4860::8888',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053',\n]\n
" }, { "textRaw": "`dnsPromises.lookup(hostname[, options])`", "type": "method", "name": "lookup", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "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 IPv4 and IPv6 addresses are both returned. **Default:** `0`.", "name": "family", "type": "integer", "default": "`0`", "desc": "The record family. Must be `4`, `6`, or `0`. The value `0` indicates that IPv4 and IPv6 addresses are both returned." }, { "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": "`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. **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`][]. New code should use `{ verbatim: true }`.", "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`][]. New code should use `{ verbatim: true }`", "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." } ] } ] } ], "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 IPv4\nand IPv6 addresses are both returned if found.

\n

With the all option set to true, the Promise is resolved with addresses\nbeing an array of objects with the properties address and family.

\n

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.

\n

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().

\n

Example usage:

\n
const dns = require('dns');\nconst dnsPromises = dns.promises;\nconst options = {\n  family: 6,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n};\n\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('address: %j family: IPv%s', result.address, result.family);\n  // address: \"2606:2800:220:1:248:1893:25c8:1946\" family: IPv6\n});\n\n// When options.all is true, the result will be an Array.\noptions.all = true;\ndnsPromises.lookup('example.com', options).then((result) => {\n  console.log('addresses: %j', result);\n  // addresses: [{\"address\":\"2606:2800:220:1:248:1893:25c8:1946\",\"family\":6}]\n});\n
" }, { "textRaw": "`dnsPromises.lookupService(address, port)`", "type": "method", "name": "lookupService", "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.

\n

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.

\n

On error, the Promise is rejected with an Error object, where err.code\nis the error code.

\n
const dnsPromises = require('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])`", "type": "method", "name": "resolve", "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." } ] } ], "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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
rrtyperecords containsResult typeShorthand 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()
'TXT'text records<string[]>dnsPromises.resolveTxt()
\n

On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

" }, { "textRaw": "`dnsPromises.resolve4(hostname[, options])`", "type": "method", "name": "resolve4", "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": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", "name": "ttl", "type": "boolean", "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '1.2.3.4', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." } ] } ] } ], "desc": "

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']).

" }, { "textRaw": "`dnsPromises.resolve6(hostname[, options])`", "type": "method", "name": "resolve6", "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": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ttl` {boolean} Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds.", "name": "ttl", "type": "boolean", "desc": "Retrieve the Time-To-Live value (TTL) of each record. When `true`, the `Promise` is resolved with an array of `{ address: '0:1:2:3:4:5:6:7', ttl: 60 }` objects rather than an array of strings, with the TTL expressed in seconds." } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`dnsPromises.resolveAny(hostname)`", "type": "method", "name": "resolveAny", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
TypeProperties
'A'address/ttl
'AAAA'address/ttl
'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()
'TXT'This type of record contains an array property called entries which refers to dnsPromises.resolveTxt(), e.g. { entries: ['...'], type: 'TXT' }
\n

Here is an example of the result object:

\n\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)`", "type": "method", "name": "resolveCaa", "meta": { "added": [ "v15.0.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'}]).

" }, { "textRaw": "`dnsPromises.resolveCname(hostname)`", "type": "method", "name": "resolveCname", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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']).

" }, { "textRaw": "`dnsPromises.resolveMx(hostname)`", "type": "method", "name": "resolveMx", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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'}, ...]).

" }, { "textRaw": "`dnsPromises.resolveNaptr(hostname)`", "type": "method", "name": "resolveNaptr", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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:

\n
    \n
  • flags
  • \n
  • service
  • \n
  • regexp
  • \n
  • replacement
  • \n
  • order
  • \n
  • preference
  • \n
\n\n
{\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)`", "type": "method", "name": "resolveNs", "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']).

" }, { "textRaw": "`dnsPromises.resolvePtr(hostname)`", "type": "method", "name": "resolvePtr", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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.

" }, { "textRaw": "`dnsPromises.resolveSoa(hostname)`", "type": "method", "name": "resolveSoa", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string}", "name": "hostname", "type": "string" } ] } ], "desc": "

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:

\n
    \n
  • nsname
  • \n
  • hostmaster
  • \n
  • serial
  • \n
  • refresh
  • \n
  • retry
  • \n
  • expire
  • \n
  • minttl
  • \n
\n\n
{\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)`", "type": "method", "name": "resolveSrv", "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:

\n
    \n
  • priority
  • \n
  • weight
  • \n
  • port
  • \n
  • name
  • \n
\n\n
{\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
" }, { "textRaw": "`dnsPromises.resolveTxt(hostname)`", "type": "method", "name": "resolveTxt", "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.

" }, { "textRaw": "`dnsPromises.reverse(ip)`", "type": "method", "name": "reverse", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`ip` {string}", "name": "ip", "type": "string" } ] } ], "desc": "

Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of host names.

\n

On error, the Promise is rejected with an Error object, where err.code\nis one of the DNS error codes.

" }, { "textRaw": "`dnsPromises.setDefaultResultOrder(order)`", "type": "method", "name": "setDefaultResultOrder", "meta": { "added": [ "v16.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`order` {string} must be `'ipv4first'` or `'verbatim'`.", "name": "order", "type": "string", "desc": "must be `'ipv4first'` or `'verbatim'`." } ] } ], "desc": "

Set the default value of verbatim in dns.lookup() and\ndnsPromises.lookup(). The value could be:

\n
    \n
  • ipv4first: sets default verbatim false.
  • \n
  • verbatim: sets default verbatim true.
  • \n
\n

The default is ipv4first 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.

" }, { "textRaw": "`dnsPromises.setServers(servers)`", "type": "method", "name": "setServers", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`servers` {string[]} array of [RFC 5952][] formatted addresses", "name": "servers", "type": "string[]", "desc": "array of [RFC 5952][] formatted addresses" } ] } ], "desc": "

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.

\n
dnsPromises.setServers([\n  '4.4.4.4',\n  '[2001:4860:4860::8888]',\n  '4.4.4.4:1053',\n  '[2001:4860:4860::8888]:1053',\n]);\n
\n

An error will be thrown if an invalid address is provided.

\n

The dnsPromises.setServers() method must not be called while a DNS query is in\nprogress.

\n

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.

" } ], "type": "module", "displayName": "DNS promises API" }, { "textRaw": "Error codes", "name": "error_codes", "desc": "

Each DNS query can return one of the following error codes:

\n
    \n
  • dns.NODATA: DNS server returned answer with no data.
  • \n
  • dns.FORMERR: DNS server claims query was misformatted.
  • \n
  • dns.SERVFAIL: DNS server returned general failure.
  • \n
  • dns.NOTFOUND: Domain name not found.
  • \n
  • dns.NOTIMP: DNS server does not implement requested operation.
  • \n
  • dns.REFUSED: DNS server refused query.
  • \n
  • dns.BADQUERY: Misformatted DNS query.
  • \n
  • dns.BADNAME: Misformatted host name.
  • \n
  • dns.BADFAMILY: Unsupported address family.
  • \n
  • dns.BADRESP: Misformatted DNS reply.
  • \n
  • dns.CONNREFUSED: Could not contact DNS servers.
  • \n
  • dns.TIMEOUT: Timeout while contacting DNS servers.
  • \n
  • dns.EOF: End of file.
  • \n
  • dns.FILE: Error reading file.
  • \n
  • dns.NOMEM: Out of memory.
  • \n
  • dns.DESTRUCTION: Channel is being destroyed.
  • \n
  • dns.BADSTR: Misformatted string.
  • \n
  • dns.BADFLAGS: Illegal flags specified.
  • \n
  • dns.NONAME: Given host name is not numeric.
  • \n
  • dns.BADHINTS: Illegal hints flags specified.
  • \n
  • dns.NOTINITIALIZED: c-ares library initialization not yet performed.
  • \n
  • dns.LOADIPHLPAPI: Error loading iphlpapi.dll.
  • \n
  • dns.ADDRGETNETWORKPARAMS: Could not find GetNetworkParams function.
  • \n
  • dns.CANCELLED: DNS query cancelled.
  • \n
", "type": "module", "displayName": "Error codes" }, { "textRaw": "Implementation considerations", "name": "implementation_considerations", "desc": "

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.

", "methods": [ { "textRaw": "`dns.lookup()`", "type": "method", "name": "lookup", "signatures": [ { "params": [] } ], "desc": "

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.

\n

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.

\n

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.

" } ], "modules": [ { "textRaw": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`", "name": "`dns.resolve()`,_`dns.resolve*()`_and_`dns.reverse()`", "desc": "

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.

\n

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.

\n

They do not use the same set of configuration files than what dns.lookup()\nuses. For instance, they do not use the configuration from /etc/hosts.

", "type": "module", "displayName": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`" } ], "type": "module", "displayName": "Implementation considerations" } ], "type": "module", "displayName": "DNS", "source": "doc/api/dns.md" }, { "textRaw": "Domain", "name": "domain", "meta": { "deprecated": [ "v1.4.2" ], "changes": [ { "version": "v8.8.0", "pr-url": "https://github.com/nodejs/node/pull/15695", "description": "Any `Promise`s created in VM contexts no longer have a `.domain` property. Their handlers are still executed in the proper domain, however, and `Promise`s created in the main context still possess a `.domain` property." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12489", "description": "Handlers for `Promise`s are now invoked in the domain in which the first promise of a chain was created." } ] }, "introduced_in": "v0.10.0", "stability": 0, "stabilityText": "Deprecated", "desc": "

Source Code: lib/domain.js

\n

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.

\n

Domains 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.

", "miscs": [ { "textRaw": "Warning: Don't ignore errors!", "name": "Warning: Don't ignore errors!", "type": "misc", "desc": "

Domain error handlers are not a substitute for closing down a\nprocess when an error occurs.

\n

By 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.

\n

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.

\n

The 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.

\n

In 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.

\n

For example, this is not a good idea:

\n
// XXX WARNING! BAD IDEA!\n\nconst d = require('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('http').createServer((req, res) => {\n    handleRequest(req, res);\n  }).listen(PORT);\n});\n
\n

By 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('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('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('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.

\n
    \n
  • error.domain The domain that first handled the error.
  • \n
  • error.domainEmitter The event emitter that emitted an 'error' event\nwith the error object.
  • \n
  • error.domainBound The callback function which was bound to the\ndomain, and passed an error as its first argument.
  • \n
  • error.domainThrown A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.
  • \n
" }, { "textRaw": "Implicit binding", "name": "Implicit binding", "type": "misc", "desc": "

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.

\n

Additionally, callbacks passed to lowlevel 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.

\n

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.

\n

To nest Domain objects as children of a parent Domain they must be\nexplicitly added.

\n

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.

" }, { "textRaw": "Explicit binding", "name": "Explicit binding", "type": "misc", "desc": "

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.

\n

For 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.

\n

That is possible via explicit binding.

\n
// Create a top-level domain for the server\nconst domain = require('domain');\nconst http = require('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()`", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "Returns: {Domain}", "name": "return", "type": "Domain" }, "params": [] } ] } ], "classes": [ { "textRaw": "Class: `Domain`", "type": "class", "name": "Domain", "desc": "\n

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.

\n

To handle the errors that it catches, listen to its 'error' event.

", "properties": [ { "textRaw": "`members` {Array}", "type": "Array", "name": "members", "desc": "

An array of timers and event emitters that have been explicitly added\nto the domain.

" } ], "methods": [ { "textRaw": "`domain.add(emitter)`", "type": "method", "name": "add", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be added to the domain", "name": "emitter", "type": "EventEmitter|Timer", "desc": "emitter or timer 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.

\n

This also works with timers that are returned from setInterval() and\nsetTimeout(). If their callback function throws, it will be caught by\nthe domain 'error' handler.

\n

If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.

" }, { "textRaw": "`domain.bind(callback)`", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "Returns: {Function} The bound function", "name": "return", "type": "Function", "desc": "The bound function" }, "params": [ { "textRaw": "`callback` {Function} The callback function", "name": "callback", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

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.

\n
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()`", "type": "method", "name": "enter", "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.

\n

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.

" }, { "textRaw": "`domain.exit()`", "type": "method", "name": "exit", "signatures": [ { "params": [] } ], "desc": "

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.

\n

If there are multiple, nested domains bound to the current execution context,\nexit() will exit any domains nested within this domain.

\n

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.

" }, { "textRaw": "`domain.intercept(callback)`", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "Returns: {Function} The intercepted function", "name": "return", "type": "Function", "desc": "The intercepted function" }, "params": [ { "textRaw": "`callback` {Function} The callback function", "name": "callback", "type": "Function", "desc": "The callback function" } ] } ], "desc": "

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.

\n

In this way, the common if (err) return callback(err); pattern can be replaced\nwith a single error handler in a single place.

\n
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)`", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain", "name": "emitter", "type": "EventEmitter|Timer", "desc": "emitter or timer to be removed from the domain" } ] } ], "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.

" }, { "textRaw": "`domain.run(fn[, ...args])`", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function}", "name": "fn", "type": "Function" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context. Optionally, arguments can be passed to\nthe function.

\n

This is the most basic way to use a domain.

\n
const domain = require('domain');\nconst fs = require('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
\n

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.

" } ] } ], "modules": [ { "textRaw": "Domains and promises", "name": "domains_and_promises", "desc": "

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:

\n
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
\n

A callback may be bound to a specific domain using domain.bind(callback):

\n
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
\n

Domains will not interfere with the error handling mechanisms for\npromises. In other words, no 'error' event will be emitted for unhandled\nPromise rejections.

", "type": "module", "displayName": "Domains and promises" } ], "type": "module", "displayName": "Domain", "source": "doc/api/domain.md" }, { "textRaw": "Events", "name": "Events", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "type": "module", "desc": "

Source Code: lib/events.js

\n

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.

\n

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.

\n

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.

\n

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.

\n

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.

\n
const EventEmitter = require('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", "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.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n  console.log(a, b, this, this === myEmitter);\n  // Prints:\n  //   a b MyEmitter {\n  //     domain: null,\n  //     _events: { event: [Function] },\n  //     _eventsCount: 1,\n  //     _maxListeners: undefined } true\n});\nmyEmitter.emit('event', 'a', 'b');\n
\n

It is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this keyword will no longer reference the EventEmitter instance:

\n
const 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
", "type": "module", "displayName": "Passing arguments and `this` to listeners" }, { "textRaw": "Asynchronous vs. synchronous", "name": "asynchronous_vs._synchronous", "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:

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  setImmediate(() => {\n    console.log('this happens asynchronously');\n  });\n});\nmyEmitter.emit('event', 'a', 'b');\n
", "type": "module", "displayName": "Asynchronous vs. synchronous" }, { "textRaw": "Handling events only once", "name": "handling_events_only_once", "desc": "

When a listener is registered using the eventEmitter.on() method, that\nlistener is invoked every time the named event is emitted.

\n
const 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
\n

Using 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.

\n
const 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
", "type": "module", "displayName": "Handling events only once" }, { "textRaw": "Error events", "name": "error_events", "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.

\n

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.

\n
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
\n

To guard against crashing the Node.js process the domain module can be\nused. (Note, however, that the domain module is deprecated.)

\n

As a best practice, listeners should always be added for the 'error' events.

\n
const 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
\n

It is possible to monitor 'error' events without consuming the emitted error\nby installing a listener using the symbol events.errorMonitor.

\n
const { EventEmitter, errorMonitor } = require('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
", "type": "module", "displayName": "Error events" }, { "textRaw": "Capture rejections of promises", "name": "capture_rejections_of_promises", "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Using async functions with event handlers is problematic, because it\ncan lead to an unhandled rejection in case of a thrown exception:

\n
const ee = new EventEmitter();\nee.on('something', async (value) => {\n  throw new Error('kaboom');\n});\n
\n

The 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.

\n
const 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
\n

Setting events.captureRejections = true will change the default for all\nnew instances of EventEmitter.

\n
const events = require('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
\n

The '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.

", "type": "module", "displayName": "Capture rejections of promises" }, { "textRaw": "`EventTarget` and `Event` API", "name": "`eventtarget`_and_`event`_api", "meta": { "added": [ "v14.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37237", "description": "changed EventTarget error handling." }, { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35496", "description": "The `EventTarget` and `Event` classes are now available as globals." } ] }, "desc": "

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.

\n
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`", "desc": "

There are two key differences between the Node.js EventTarget and the\nEventTarget Web API:

\n
    \n
  1. Whereas DOM 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.
  2. \n
  3. In the Node.js 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).
  4. \n
", "type": "module", "displayName": "Node.js `EventTarget` vs. DOM `EventTarget`" }, { "textRaw": "`NodeEventTarget` vs. `EventEmitter`", "name": "`nodeeventtarget`_vs._`eventemitter`", "desc": "

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.

\n
    \n
  1. Unlike EventEmitter, any given listener can be registered at most once\nper event type. Attempts to register a listener multiple times are\nignored.
  2. \n
  3. The NodeEventTarget does not emulate the full EventEmitter API.\nSpecifically the prependListener(), prependOnceListener(),\nrawListeners(), setMaxListeners(), getMaxListeners(), and\nerrorMonitor APIs are not emulated. The 'newListener' and\n'removeListener' events will also not be emitted.
  4. \n
  5. The NodeEventTarget does not implement any special default behavior\nfor events with type 'error'.
  6. \n
  7. The NodeEventTarget supports EventListener objects as well as\nfunctions as handlers for all event types.
  8. \n
", "type": "module", "displayName": "`NodeEventTarget` vs. `EventEmitter`" }, { "textRaw": "Event listener", "name": "event_listener", "desc": "

Event listeners registered for an event type may either be JavaScript\nfunctions or objects with a handleEvent property whose value is a function.

\n

In either case, the handler function is invoked with the event argument\npassed to the eventTarget.dispatchEvent() function.

\n

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.

\n

An error thrown by one handler function does not prevent the other handlers\nfrom being invoked.

\n

The return value of a handler function is ignored.

\n

Handlers are always invoked in the order they were added.

\n

Handler functions may mutate the event object.

\n
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
", "type": "module", "displayName": "Event listener" }, { "textRaw": "`EventTarget` error handling", "name": "`eventtarget`_error_handling", "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.

\n

Throwing within an event listener will not stop the other registered handlers\nfrom being invoked.

\n

The EventTarget does not implement any special default handling for 'error'\ntype events like EventEmitter.

\n

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.

", "type": "module", "displayName": "`EventTarget` error handling" } ], "classes": [ { "textRaw": "Class: `Event`", "type": "class", "name": "Event", "meta": { "added": [ "v14.5.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35496", "description": "The `Event` class is now available through the global object." } ] }, "desc": "

The Event object is an adaptation of the Event Web API. Instances\nare created internally by Node.js.

", "properties": [ { "textRaw": "`bubbles` Type: {boolean} Always returns `false`.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

This is not used in Node.js and is provided purely for completeness.

", "shortDesc": "Always returns `false`." }, { "textRaw": "`cancelable` Type: {boolean} True if the event was created with the `cancelable` option.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "True if the event was created with the `cancelable` option." }, { "textRaw": "`composed` Type: {boolean} Always returns `false`.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

This is not used in Node.js and is provided purely for completeness.

", "shortDesc": "Always returns `false`." }, { "textRaw": "`currentTarget` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Alias for event.target.

", "shortDesc": "The `EventTarget` dispatching the event." }, { "textRaw": "`defaultPrevented` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Is true if cancelable is true and event.preventDefault() has been\ncalled.

" }, { "textRaw": "`eventPhase` Type: {number} Returns `0` while an event is not being dispatched, `2` while it is being dispatched.", "type": "number", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

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": "`isTrusted` Type: {boolean}", "type": "boolean", "name": "Type", "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.

" }, { "textRaw": "`returnValue` Type: {boolean} True if the event has not been canceled.", "type": "boolean", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

This is not used in Node.js and is provided purely for completeness.

", "shortDesc": "True if the event has not been canceled." }, { "textRaw": "`srcElement` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

Alias for event.target.

", "shortDesc": "The `EventTarget` dispatching the event." }, { "textRaw": "`target` Type: {EventTarget} The `EventTarget` dispatching the event.", "type": "EventTarget", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "The `EventTarget` dispatching the event." }, { "textRaw": "`timeStamp` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The millisecond timestamp when the Event object was created.

" }, { "textRaw": "`type` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

The event type identifier.

" } ], "methods": [ { "textRaw": "`event.cancelBubble()`", "type": "method", "name": "cancelBubble", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Alias for event.stopPropagation(). This is not used in Node.js and is\nprovided purely for completeness.

" }, { "textRaw": "`event.composedPath()`", "type": "method", "name": "composedPath", "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.

" }, { "textRaw": "`event.preventDefault()`", "type": "method", "name": "preventDefault", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sets the defaultPrevented property to true if cancelable is true.

" }, { "textRaw": "`event.stopImmediatePropagation()`", "type": "method", "name": "stopImmediatePropagation", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Stops the invocation of event listeners after the current one completes.

" }, { "textRaw": "`event.stopPropagation()`", "type": "method", "name": "stopPropagation", "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`", "type": "class", "name": "EventTarget", "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])`", "type": "method", "name": "addEventListener", "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": "`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." } ] } ] } ], "desc": "

Adds a new handler for the type event. Any given listener is added\nonly once per type and per capture option value.

\n

If the once option is true, the listener is removed after the\nnext time a type event is dispatched.

\n

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.

\n
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)`", "type": "method", "name": "dispatchEvent", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "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`." }, "params": [ { "textRaw": "`event` {Event}", "name": "event", "type": "Event" } ] } ], "desc": "

Dispatches the event to the list of handlers for event.type.

\n

The registered event listeners is synchronously invoked in the order they\nwere registered.

" }, { "textRaw": "`eventTarget.removeEventListener(type, listener)`", "type": "method", "name": "removeEventListener", "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" } ] } ] } ], "desc": "

Removes the listener from the list of handlers for event type.

" } ] }, { "textRaw": "Class: `NodeEventTarget`", "type": "class", "name": "NodeEventTarget", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "\n

The NodeEventTarget is a Node.js-specific extension to EventTarget\nthat emulates a subset of the EventEmitter API.

", "methods": [ { "textRaw": "`nodeEventTarget.addListener(type, listener[, options])`", "type": "method", "name": "addListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "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}", "name": "once", "type": "boolean" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`nodeEventTarget.eventNames()`", "type": "method", "name": "eventNames", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Node.js-specific extension to the EventTarget class that returns an array\nof event type names for which event listeners are registered.

" }, { "textRaw": "`nodeEventTarget.listenerCount(type)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Node.js-specific extension to the EventTarget class that returns the number\nof event listeners registered for the type.

" }, { "textRaw": "`nodeEventTarget.off(type, listener)`", "type": "method", "name": "off", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" } ] } ], "desc": "

Node.js-specific alias for eventTarget.removeListener().

" }, { "textRaw": "`nodeEventTarget.on(type, listener[, options])`", "type": "method", "name": "on", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "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}", "name": "once", "type": "boolean" } ] } ] } ], "desc": "

Node.js-specific alias for eventTarget.addListener().

" }, { "textRaw": "`nodeEventTarget.once(type, listener[, options])`", "type": "method", "name": "once", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object" } ] } ], "desc": "

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.

" }, { "textRaw": "`nodeEventTarget.removeAllListeners([type])`", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Node.js-specific extension to the EventTarget class. If type is specified,\nremoves all registered listeners for type, otherwise removes all registered\nlisteners.

" }, { "textRaw": "`nodeEventTarget.removeListener(type, listener)`", "type": "method", "name": "removeListener", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventTarget} this", "name": "return", "type": "EventTarget", "desc": "this" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`listener` {Function|EventListener}", "name": "listener", "type": "Function|EventListener" } ] } ], "desc": "

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.

" } ] } ], "type": "module", "displayName": "`EventTarget` and `Event` API" } ], "classes": [ { "textRaw": "Class: `EventEmitter`", "type": "class", "name": "EventEmitter", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": [ "v13.4.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/27867", "description": "Added captureRejections option." } ] }, "desc": "

The EventEmitter class is defined and exposed by the events module:

\n
const EventEmitter = require('events');\n
\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when existing listeners are removed.

\n

It supports the following option:

\n", "events": [ { "textRaw": "Event: `'newListener'`", "type": "event", "name": "newListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "params": [ { "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": "`listener` {Function} The event handler function", "name": "listener", "type": "Function", "desc": "The event handler function" } ], "desc": "

The EventEmitter instance will emit its own 'newListener' event before\na listener is added to its internal array of listeners.

\n

Listeners registered for the 'newListener' event are passed the event\nname and a reference to the listener being added.

\n

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.

\n
class 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'`", "type": "event", "name": "removeListener", "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.

" } ], "methods": [ { "textRaw": "`emitter.addListener(eventName, listener)`", "type": "method", "name": "addListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Alias for emitter.on(eventName, listener).

" }, { "textRaw": "`emitter.emit(eventName[, ...args])`", "type": "method", "name": "emit", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`...args` {any}", "name": "...args", "type": "any" } ] } ], "desc": "

Synchronously calls each of the listeners registered for the event named\neventName, in the order they were registered, passing the supplied arguments\nto each.

\n

Returns true if the event had listeners, false otherwise.

\n
const EventEmitter = require('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()`", "type": "method", "name": "eventNames", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Array}", "name": "return", "type": "Array" }, "params": [] } ], "desc": "

Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array are strings or Symbols.

\n
const EventEmitter = require('events');\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()`", "type": "method", "name": "getMaxListeners", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nevents.defaultMaxListeners.

" }, { "textRaw": "`emitter.listenerCount(eventName)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v3.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [ { "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" } ] } ], "desc": "

Returns the number of listeners listening to the event named eventName.

" }, { "textRaw": "`emitter.listeners(eventName)`", "type": "method", "name": "listeners", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/6881", "description": "For listeners attached using `.once()` this returns the original listeners instead of wrapper functions now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Returns a copy of the array of listeners for the event named eventName.

\n
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)`", "type": "method", "name": "off", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Alias for emitter.removeListener().

" }, { "textRaw": "`emitter.on(eventName, listener)`", "type": "method", "name": "on", "meta": { "added": [ "v0.1.101" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "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" } ] } ], "desc": "

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.

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\n
\n

Returns a reference to the EventEmitter, so that calls can be chained.

\n

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.

\n
const 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)`", "type": "method", "name": "once", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "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" } ] } ], "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.

\n
server.once('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
\n

Returns a reference to the EventEmitter, so that calls can be chained.

\n

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.

\n
const 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)`", "type": "method", "name": "prependListener", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "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" } ] } ], "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.

\n
server.prependListener('connection', (stream) => {\n  console.log('someone connected!');\n});\n
\n

Returns a reference to the EventEmitter, so that calls can be chained.

" }, { "textRaw": "`emitter.prependOnceListener(eventName, listener)`", "type": "method", "name": "prependOnceListener", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "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" } ] } ], "desc": "

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.

\n
server.prependOnceListener('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});\n
\n

Returns a reference to the EventEmitter, so that calls can be chained.

" }, { "textRaw": "`emitter.removeAllListeners([eventName])`", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Removes all listeners, or those of the specified eventName.

\n

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).

\n

Returns a reference to the EventEmitter, so that calls can be chained.

" }, { "textRaw": "`emitter.removeListener(eventName, listener)`", "type": "method", "name": "removeListener", "meta": { "added": [ "v0.1.26" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" }, { "textRaw": "`listener` {Function}", "name": "listener", "type": "Function" } ] } ], "desc": "

Removes the specified listener from the listener array for the event named\neventName.

\n
const callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
\n

removeListener() 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.

\n

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.

\n
const 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
\n

Because listeners are managed using an internal array, calling this will\nchange the position indices 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.

\n

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:

\n
const 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
\n

Returns a reference to the EventEmitter, so that calls can be chained.

" }, { "textRaw": "`emitter.setMaxListeners(n)`", "type": "method", "name": "setMaxListeners", "meta": { "added": [ "v0.3.5" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {EventEmitter}", "name": "return", "type": "EventEmitter" }, "params": [ { "textRaw": "`n` {integer}", "name": "n", "type": "integer" } ] } ], "desc": "

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.

\n

Returns a reference to the EventEmitter, so that calls can be chained.

" }, { "textRaw": "`emitter.rawListeners(eventName)`", "type": "method", "name": "rawListeners", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" }, "params": [ { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Returns a copy of the array of listeners for the event named eventName,\nincluding any wrappers (such as those created by .once()).

\n
const 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
" } ], "modules": [ { "textRaw": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`", "name": "`emitter[symbol.for('nodejs.rejection')](err,_eventname[,_...args])`", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "\n

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').

\n
const { EventEmitter, captureRejectionSymbol } = require('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
", "type": "module", "displayName": "`emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`" } ] } ], "properties": [ { "textRaw": "`events.defaultMaxListeners`", "name": "defaultMaxListeners", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "desc": "

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.

\n

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.

\n

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:

\n
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
\n

The --trace-warnings command-line flag can be used to display the\nstack trace for such warnings.

\n

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'.

" }, { "textRaw": "`events.errorMonitor`", "name": "errorMonitor", "meta": { "added": [ "v13.6.0", "v12.17.0" ], "changes": [] }, "desc": "

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.

\n

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.

" }, { "textRaw": "`events.captureRejections`", "name": "captureRejections", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Value: <boolean>

\n

Change the default captureRejections option on all new EventEmitter objects.

" }, { "textRaw": "`events.captureRejectionSymbol`", "name": "captureRejectionSymbol", "meta": { "added": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "captureRejections is experimental.", "desc": "

Value: Symbol.for('nodejs.rejection')

\n

See how to write a custom rejection handler.

" } ], "methods": [ { "textRaw": "`events.getEventListeners(emitterOrTarget, eventName)`", "type": "method", "name": "getEventListeners", "meta": { "added": [ "v15.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function[]}", "name": "return", "type": "Function[]" }, "params": [ { "textRaw": "`emitterOrTarget` {EventEmitter|EventTarget}", "name": "emitterOrTarget", "type": "EventEmitter|EventTarget" }, { "textRaw": "`eventName` {string|symbol}", "name": "eventName", "type": "string|symbol" } ] } ], "desc": "

Returns a copy of the array of listeners for the event named eventName.

\n

For EventEmitters this behaves exactly the same as calling .listeners on\nthe emitter.

\n

For EventTargets this is the only way to get the event listeners for the\nevent target. This is useful for debugging and diagnostic purposes.

\n
const { getEventListeners, EventEmitter } = require('events');\n\n{\n  const ee = new EventEmitter();\n  const listener = () => console.log('Events are fun');\n  ee.on('foo', listener);\n  getEventListeners(ee, 'foo'); // [listener]\n}\n{\n  const et = new EventTarget();\n  const listener = () => console.log('Events are fun');\n  et.addEventListener('foo', listener);\n  getEventListeners(et, 'foo'); // [listener]\n}\n
" }, { "textRaw": "`events.once(emitter, name[, options])`", "type": "method", "name": "once", "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": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`emitter` {EventEmitter}", "name": "emitter", "type": "EventEmitter" }, { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "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." } ] } ] } ], "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.

\n

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.

\n
const { once, EventEmitter } = require('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.log('error happened', err);\n  }\n}\n\nrun();\n
\n

The 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:

\n
const { EventEmitter, once } = require('events');\n\nconst ee = new EventEmitter();\n\nonce(ee, 'error')\n  .then(([err]) => console.log('ok', err.message))\n  .catch((err) => console.log('error', err.message));\n\nee.emit('error', new Error('boom'));\n\n// Prints: ok boom\n
\n

An <AbortSignal> can be used to cancel waiting for the event:

\n
const { EventEmitter, once } = require('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(); // Abort waiting for the event\nee.emit('foo'); // Prints: Waiting for the event was canceled!\n
", "modules": [ { "textRaw": "Awaiting multiple events emitted on `process.nextTick()`", "name": "awaiting_multiple_events_emitted_on_`process.nexttick()`", "desc": "

There is an edge case worth noting when using the events.once() function\nto await multiple events emitted on in the same batch of process.nextTick()\noperations, or whenever multiple events are emitted synchronously. Specifically,\nbecause the process.nextTick() queue is drained before the Promise microtask\nqueue, and because EventEmitter emits all events synchronously, it is possible\nfor events.once() to miss an event.

\n
const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await once(myEE, 'bar');\n  console.log('bar');\n\n  // This Promise will never resolve because the 'foo' event will\n  // have already been emitted before the Promise is created.\n  await once(myEE, 'foo');\n  console.log('foo');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
\n

To catch both events, create each of the Promises before awaiting either\nof them, then it becomes possible to use Promise.all(), Promise.race(),\nor Promise.allSettled():

\n
const { EventEmitter, once } = require('events');\n\nconst myEE = new EventEmitter();\n\nasync function foo() {\n  await Promise.all([once(myEE, 'bar'), once(myEE, 'foo')]);\n  console.log('foo', 'bar');\n}\n\nprocess.nextTick(() => {\n  myEE.emit('bar');\n  myEE.emit('foo');\n});\n\nfoo().then(() => console.log('done'));\n
", "type": "module", "displayName": "Awaiting multiple events emitted on `process.nextTick()`" } ] }, { "textRaw": "`events.listenerCount(emitter, eventName)`", "type": "method", "name": "listenerCount", "meta": { "added": [ "v0.9.12" ], "deprecated": [ "v3.2.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter} The emitter to query", "name": "emitter", "type": "EventEmitter", "desc": "The emitter to query" }, { "textRaw": "`eventName` {string|symbol} The event name", "name": "eventName", "type": "string|symbol", "desc": "The event name" } ] } ], "desc": "

A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

\n
const { EventEmitter, listenerCount } = require('events');\nconst myEmitter = new EventEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(listenerCount(myEmitter, 'event'));\n// Prints: 2\n
" }, { "textRaw": "`events.on(emitter, eventName[, options])`", "type": "method", "name": "on", "meta": { "added": [ "v13.6.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "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`" }, "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." } ] } ] } ], "desc": "
const { on, EventEmitter } = require('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
\n

Returns 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.

\n

An <AbortSignal> can be used to cancel waiting on events:

\n
const { on, EventEmitter } = require('events');\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])`", "type": "method", "name": "setMaxListeners", "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." }, { "textRaw": "`...eventsTargets` {EventTarget[]|EventEmitter[]} Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} objects.", "name": "...eventsTargets", "type": "EventTarget[]|EventEmitter[]", "desc": "Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} objects." } ] } ], "desc": "
const {\n  setMaxListeners,\n  EventEmitter\n} = require('events');\n\nconst target = new EventTarget();\nconst emitter = new EventEmitter();\n\nsetMaxListeners(5, target, emitter);\n
\n

" } ], "source": "doc/api/events.md" }, { "textRaw": "File system", "name": "fs", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/fs.js

\n

The fs module enables interacting with the file system in a\nway modeled on standard POSIX functions.

\n

To use the promise-based APIs:

\n
import * as fs from 'fs/promises';\n
\n
const fs = require('fs/promises');\n
\n

To use the callback and sync APIs:

\n
import * as fs from 'fs';\n
\n
const fs = require('fs');\n
\n

All 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", "desc": "

Promise-based operations return a promise that is fulfilled when the\nasynchronous operation is complete.

\n
import { unlink } from '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
\n
const { unlink } = require('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
", "type": "module", "displayName": "Promise example" }, { "textRaw": "Callback example", "name": "callback_example", "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.

\n
import { unlink } from 'fs';\n\nunlink('/tmp/hello', (err) => {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});\n
\n
const { unlink } = require('fs');\n\nunlink('/tmp/hello', (err) => {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});\n
\n

The callback-based versions of the fs module APIs are preferable over\nthe use of the promise APIs when maximal performance (both in terms of\nexecution time and memory allocation are required).

", "type": "module", "displayName": "Callback example" }, { "textRaw": "Synchronous example", "name": "synchronous_example", "desc": "

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.

\n
import { unlinkSync } from 'fs';\n\ntry {\n  unlinkSync('/tmp/hello');\n  console.log('successfully deleted /tmp/hello');\n} catch (err) {\n  // handle the error\n}\n
\n
const { unlinkSync } = require('fs');\n\ntry {\n  unlinkSync('/tmp/hello');\n  console.log('successfully deleted /tmp/hello');\n} catch (err) {\n  // handle the error\n}\n
", "type": "module", "displayName": "Synchronous example" }, { "textRaw": "Promises API", "name": "promises_api", "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.

\n

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`", "type": "class", "name": "FileHandle", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

A <FileHandle> object is an object wrapper for a numeric file descriptor.

\n

Instances of the <FileHandle> object are created by the fsPromises.open()\nmethod.

\n

All <FileHandle> objects are <EventEmitter>s.

\n

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.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when the <FileHandle> has been closed and can no\nlonger be used.

" } ], "methods": [ { "textRaw": "`filehandle.appendFile(data[, options])`", "type": "method", "name": "appendFile", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`encoding` {string|null} **Default:** `'utf8'`", "name": "encoding", "type": "string|null", "default": "`'utf8'`" } ] } ] } ], "desc": "

Alias of filehandle.writeFile().

\n

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().

" }, { "textRaw": "`filehandle.chmod(mode)`", "type": "method", "name": "chmod", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`mode` {integer} the file mode bit mask.", "name": "mode", "type": "integer", "desc": "the file mode bit mask." } ] } ], "desc": "

Modifies the permissions on the file. See chmod(2).

" }, { "textRaw": "`filehandle.chown(uid, gid)`", "type": "method", "name": "chown", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`uid` {integer} The file's new owner's user id.", "name": "uid", "type": "integer", "desc": "The file's new owner's user id." }, { "textRaw": "`gid` {integer} The file's new group's group id.", "name": "gid", "type": "integer", "desc": "The file's new group's group id." } ] } ], "desc": "

Changes the ownership of the file. A wrapper for chown(2).

" }, { "textRaw": "`filehandle.close()`", "type": "method", "name": "close", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [] } ], "desc": "

Closes the file handle after waiting for any pending operation on the handle to\ncomplete.

\n
import { open } from 'fs/promises';\n\nlet filehandle;\ntry {\n  filehandle = await open('thefile.txt', 'r');\n} finally {\n  await filehandle?.close();\n}\n
" }, { "textRaw": "`filehandle.datasync()`", "type": "method", "name": "datasync", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [] } ], "desc": "

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.

\n

Unlike filehandle.sync this method does not flush modified metadata.

" }, { "textRaw": "`filehandle.read(buffer, offset, length, position)`", "type": "method", "name": "read", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "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." } ] }, "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": "`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`", "name": "length", "type": "integer", "default": "`buffer.byteLength`", "desc": "The number of bytes to read." }, { "textRaw": "`position` {integer} The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an integer, the current file position will remain unchanged.", "name": "position", "type": "integer", "desc": "The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an integer, the current file position will remain unchanged." } ] } ], "desc": "

Reads data from the file and stores that in the given buffer.

\n

If the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.

" }, { "textRaw": "`filehandle.read([options])`", "type": "method", "name": "read", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "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." } ] }, "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`", "name": "length", "type": "integer", "default": "`buffer.byteLength`", "desc": "The number of bytes to read." }, { "textRaw": "`position` {integer} The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an integer, the current file position will remain unchanged. **Default:**: `null`", "name": "position", "type": "integer", "default": ": `null`", "desc": "The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an integer, the current file position will remain unchanged." } ] } ] } ], "desc": "

Reads data from the file and stores that in the given buffer.

\n

If the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.

" }, { "textRaw": "`filehandle.readFile(options)`", "type": "method", "name": "readFile", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the data will be a string.", "name": "return", "type": "Promise", "desc": "Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the data will be a string." }, "params": [ { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`encoding` {string|null} **Default:** `null`", "name": "encoding", "type": "string|null", "default": "`null`" }, { "textRaw": "`signal` {AbortSignal} allows aborting an in-progress readFile", "name": "signal", "type": "AbortSignal", "desc": "allows aborting an in-progress readFile" } ] } ] } ], "desc": "

Asynchronously reads the entire contents of a file.

\n

If options is a string, then it specifies the encoding.

\n

The <FileHandle> has to support reading.

\n

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.

" }, { "textRaw": "`filehandle.readv(buffers[, position])`", "type": "method", "name": "readv", "meta": { "added": [ "v13.13.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "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." } ] }, "params": [ { "textRaw": "`buffers` {Buffer[]|TypedArray[]|DataView[]}", "name": "buffers", "type": "Buffer[]|TypedArray[]|DataView[]" }, { "textRaw": "`position` {integer} 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.", "name": "position", "type": "integer", "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." } ] } ], "desc": "

Read from a file and write to an array of <ArrayBufferView>s

" }, { "textRaw": "`filehandle.stat([options])`", "type": "method", "name": "stat", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with an {fs.Stats} for the file.", "name": "return", "type": "Promise", "desc": "Fulfills with an {fs.Stats} for the file." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] } ] } ] }, { "textRaw": "`filehandle.sync()`", "type": "method", "name": "sync", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fufills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fufills with `undefined` upon success." }, "params": [] } ], "desc": "

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.

" }, { "textRaw": "`filehandle.truncate(len)`", "type": "method", "name": "truncate", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`len` {integer} **Default:** `0`", "name": "len", "type": "integer", "default": "`0`" } ] } ], "desc": "

Truncates the file.

\n

If the file was larger than len bytes, only the first len bytes will be\nretained in the file.

\n

The following example retains only the first four bytes of the file:

\n
import { open } from '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
\n

If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

\n

If len is negative then 0 will be used.

" }, { "textRaw": "`filehandle.utimes(atime, mtime)`", "type": "method", "name": "utimes", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`atime` {number|string|Date}", "name": "atime", "type": "number|string|Date" }, { "textRaw": "`mtime` {number|string|Date}", "name": "mtime", "type": "number|string|Date" } ] } ], "desc": "

Change the file system timestamps of the object referenced by the <FileHandle>\nthen resolves the promise with no arguments upon success.

" }, { "textRaw": "`filehandle.write(buffer[, offset[, length[, position]]])`", "type": "method", "name": "write", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `buffer` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `buffer` parameter won't coerce unsupported input to buffers anymore." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|string|Object}", "name": "buffer", "type": "Buffer|TypedArray|DataView|string|Object" }, { "textRaw": "`offset` {integer} The start position from within `buffer` where the data to write begins. **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`", "desc": "The start position from within `buffer` where the data to write begins." }, { "textRaw": "`length` {integer} The number of bytes from `buffer` to write. **Default:** `buffer.byteLength`", "name": "length", "type": "integer", "default": "`buffer.byteLength`", "desc": "The number of bytes from `buffer` to write." }, { "textRaw": "`position` {integer} The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail.", "name": "position", "type": "integer", "desc": "The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail." } ] } ], "desc": "

Write buffer to the file.

\n

If buffer is a plain object, it must have an own (not inherited) toString\nfunction property.

\n

The promise is resolved with an object containing two properties:

\n\n

It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

\n

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(string[, position[, encoding]])`", "type": "method", "name": "write", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `string` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `string` parameter won't coerce unsupported input to strings anymore." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`string` {string|Object}", "name": "string", "type": "string|Object" }, { "textRaw": "`position` {integer} The offset from the beginning of the file where the data from `string` should be written. If `position` is not a `number` the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail.", "name": "position", "type": "integer", "desc": "The offset from the beginning of the file where the data from `string` should be written. If `position` is not a `number` the data will be written at the current position. See the POSIX pwrite(2) documentation for more detail." }, { "textRaw": "`encoding` {string} The expected string encoding. **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "The expected string encoding." } ] } ], "desc": "

Write string to the file. If string is not a string, or an object with an\nown toString function property, the promise is rejected with an error.

\n

The promise is resolved with an object containing two properties:

\n\n

It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the promise to be resolved (or rejected). For this\nscenario, use fs.createWriteStream().

\n

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)`", "type": "method", "name": "writeFile", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `data` parameter will stringify an object with an explicit `toString` function." }, { "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": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView|Object}", "name": "data", "type": "string|Buffer|TypedArray|DataView|Object" }, { "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." } ] } ] } ], "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a buffer, or an object with an own toString function\nproperty. The promise is resolved with no arguments upon success.

\n

If options is a string, then it specifies the encoding.

\n

The <FileHandle> has to support writing.

\n

It is unsafe to use filehandle.writeFile() multiple times on the same file\nwithout waiting for the promise to be resolved (or rejected).

\n

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.

" }, { "textRaw": "`filehandle.writev(buffers[, position])`", "type": "method", "name": "writev", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`buffers` {Buffer[]|TypedArray[]|DataView[]}", "name": "buffers", "type": "Buffer[]|TypedArray[]|DataView[]" }, { "textRaw": "`position` {integer} The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current position.", "name": "position", "type": "integer", "desc": "The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current position." } ] } ], "desc": "

Write an array of <ArrayBufferView>s to the file.

\n

The promise is resolved with an object containing a two properties:

\n\n

It is unsafe to call writev() multiple times on the same file without waiting\nfor the promise to be resolved (or rejected).

\n

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.

" } ], "properties": [ { "textRaw": "`fd` {number} The numeric file descriptor managed by the {FileHandle} object.", "type": "number", "name": "fd", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "The numeric file descriptor managed by the {FileHandle} object." } ] } ], "methods": [ { "textRaw": "`fsPromises.access(path[, mode])`", "type": "method", "name": "access", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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`" } ] } ], "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. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

\n

If the accessibility check is successful, the promise is resolved 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\n/etc/passwd can be read and written by the current process.

\n
import { access } from 'fs/promises';\nimport { constants } from 'fs';\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
\n

Using 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.

" }, { "textRaw": "`fsPromises.appendFile(path, data[, options])`", "type": "method", "name": "appendFile", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL|FileHandle} filename or {FileHandle}", "name": "path", "type": "string|Buffer|URL|FileHandle", "desc": "filename or {FileHandle}" }, { "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`][]." } ] } ] } ], "desc": "

Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.

\n

If options is a string, then it specifies the encoding.

\n

The path may be specified as a <FileHandle> that has been opened\nfor appending (using fsPromises.open()).

" }, { "textRaw": "`fsPromises.chmod(path, mode)`", "type": "method", "name": "chmod", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`mode` {string|integer}", "name": "mode", "type": "string|integer" } ] } ], "desc": "

Changes the permissions of a file.

" }, { "textRaw": "`fsPromises.chown(path, uid, gid)`", "type": "method", "name": "chown", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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" } ] } ], "desc": "

Changes the ownership of a file.

" }, { "textRaw": "`fsPromises.copyFile(src, dest[, mode])`", "type": "method", "name": "copyFile", "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": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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." } ] } ] } ], "desc": "

Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists.

\n

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.

\n
import { constants } from 'fs';\nimport { copyFile } from '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.log('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.log('The file could not be copied');\n}\n
" }, { "textRaw": "`fsPromises.cp(src, dest[, options])`", "type": "method", "name": "cp", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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. 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. Can also return a `Promise` that resolves to `true` or `false`" }, { "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": "`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" } ] } ] } ], "desc": "

Asynchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.

\n

When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.

" }, { "textRaw": "`fsPromises.lchmod(path, mode)`", "type": "method", "name": "lchmod", "meta": { "deprecated": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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.

\n

This method is only implemented on macOS.

" }, { "textRaw": "`fsPromises.lchown(path, uid, gid)`", "type": "method", "name": "lchown", "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": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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" } ] } ], "desc": "

Changes the ownership on a symbolic link.

" }, { "textRaw": "`fsPromises.lutimes(path, atime, mtime)`", "type": "method", "name": "lutimes", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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" } ] } ], "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.

" }, { "textRaw": "`fsPromises.link(existingPath, newPath)`", "type": "method", "name": "link", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`existingPath` {string|Buffer|URL}", "name": "existingPath", "type": "string|Buffer|URL" }, { "textRaw": "`newPath` {string|Buffer|URL}", "name": "newPath", "type": "string|Buffer|URL" } ] } ], "desc": "

Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail.

" }, { "textRaw": "`fsPromises.lstat(path[, options])`", "type": "method", "name": "lstat", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the {fs.Stats} object for the given symbolic link `path`.", "name": "return", "type": "Promise", "desc": "Fulfills with the {fs.Stats} object for the given symbolic link `path`." }, "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.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`fsPromises.mkdir(path[, options])`", "type": "method", "name": "mkdir", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`.", "name": "return", "type": "Promise", "desc": "Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object|integer}", "name": "options", "type": "Object|integer", "options": [ { "textRaw": "`recursive` {boolean} **Default:** `false`", "name": "recursive", "type": "boolean", "default": "`false`" }, { "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", "name": "mode", "type": "string|integer", "default": "`0o777`", "desc": "Not supported on Windows." } ] } ] } ], "desc": "

Asynchronously creates a directory.

\n

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\nfsPromises.mkdir() when path is a directory that exists results in a\nrejection only when recursive is false.

" }, { "textRaw": "`fsPromises.mkdtemp(prefix[, options])`", "type": "method", "name": "mkdtemp", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v16.5.0", "pr-url": "https://github.com/nodejs/node/pull/39028", "description": "The `prefix` parameter now accepts an empty string." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with a string containing the filesystem path of the newly created temporary directory.", "name": "return", "type": "Promise", "desc": "Fulfills with a string containing the filesystem path of the newly created temporary directory." }, "params": [ { "textRaw": "`prefix` {string}", "name": "prefix", "type": "string" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" } ] } ] } ], "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.

\n

The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

\n
import { mkdtemp } from 'fs/promises';\n\ntry {\n  await mkdtemp(path.join(os.tmpdir(), 'foo-'));\n} catch (err) {\n  console.error(err);\n}\n
\n

The 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('path').sep).

" }, { "textRaw": "`fsPromises.open(path, flags[, mode])`", "type": "method", "name": "open", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v11.1.0", "pr-url": "https://github.com/nodejs/node/pull/23767", "description": "The `flags` argument is now optional and defaults to `'r'`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with a {FileHandle} object.", "name": "return", "type": "Promise", "desc": "Fulfills with a {FileHandle} object." }, "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`][]." }, { "textRaw": "`mode` {string|integer} Sets the file mode (permission and sticky bits) if the file is created. **Default:** `0o666` (readable and writable)", "name": "mode", "type": "string|integer", "default": "`0o666` (readable and writable)", "desc": "Sets the file mode (permission and sticky bits) if the file is created." } ] } ], "desc": "

Opens a <FileHandle>.

\n

Refer to the POSIX open(2) documentation for more detail.

\n

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.

" }, { "textRaw": "`fsPromises.opendir(path[, options])`", "type": "method", "name": "opendir", "meta": { "added": [ "v12.12.0" ], "changes": [ { "version": [ "v13.1.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30114", "description": "The `bufferSize` option was introduced." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with an {fs.Dir}.", "name": "return", "type": "Promise", "desc": "Fulfills with an {fs.Dir}." }, "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." } ] } ] } ], "desc": "

Asynchronously open a directory for iterative scanning. See the POSIX\nopendir(3) documentation for more detail.

\n

Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.

\n

The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

\n

Example using async iteration:

\n
import { opendir } from '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
\n

When using the async iterator, the <fs.Dir> object will be automatically\nclosed after the iterator exits.

" }, { "textRaw": "`fsPromises.readdir(path[, options])`", "type": "method", "name": "readdir", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.11.0", "pr-url": "https://github.com/nodejs/node/pull/22020", "description": "New option `withFileTypes` was added." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`.", "name": "return", "type": "Promise", "desc": "Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`." }, "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'`" }, { "textRaw": "`withFileTypes` {boolean} **Default:** `false`", "name": "withFileTypes", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Reads the contents of a directory.

\n

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. If the encoding is set to 'buffer', the filenames returned\nwill be passed as <Buffer> objects.

\n

If options.withFileTypes is set to true, the resolved array will contain\n<fs.Dirent> objects.

\n
import { readdir } from '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])`", "type": "method", "name": "readFile", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v15.2.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": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the contents of the file.", "name": "return", "type": "Promise", "desc": "Fulfills with the contents of the file." }, "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" } ] } ] } ], "desc": "

Asynchronously reads the entire contents of a file.

\n

If no encoding is specified (using options.encoding), the data is returned\nas a <Buffer> object. Otherwise, the data will be a string.

\n

If options is a string, then it specifies the encoding.

\n

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.

\n

It is possible to abort an ongoing readFile using an <AbortSignal>. If a\nrequest is aborted the promise returned is rejected with an AbortError:

\n
import { readFile } from '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
\n

Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.readFile performs.

\n

Any specified <FileHandle> has to support reading.

" }, { "textRaw": "`fsPromises.readlink(path[, options])`", "type": "method", "name": "readlink", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the `linkString` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with the `linkString` upon success." }, "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'`" } ] } ] } ], "desc": "

Reads the contents of the symbolic link referred to by path. See the POSIX\nreadlink(2) documentation for more detail. The promise is resolved with the\nlinkString upon success.

\n

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.

" }, { "textRaw": "`fsPromises.realpath(path[, options])`", "type": "method", "name": "realpath", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the resolved path upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with the resolved path upon success." }, "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'`" } ] } ] } ], "desc": "

Determines the actual location of path using the same semantics as the\nfs.realpath.native() function.

\n

Only paths that can be converted to UTF8 strings are supported.

\n

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 path. If the encoding is set to 'buffer', the path returned will be\npassed as a <Buffer> object.

\n

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.

" }, { "textRaw": "`fsPromises.rename(oldPath, newPath)`", "type": "method", "name": "rename", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`oldPath` {string|Buffer|URL}", "name": "oldPath", "type": "string|Buffer|URL" }, { "textRaw": "`newPath` {string|Buffer|URL}", "name": "newPath", "type": "string|Buffer|URL" } ] } ], "desc": "

Renames oldPath to newPath.

" }, { "textRaw": "`fsPromises.rmdir(path[, options])`", "type": "method", "name": "rmdir", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37216", "description": "Using `fsPromises.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 `fsPromises.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 `fsPromises.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." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure. **Default:** `false`. **Deprecated.**", "name": "recursive", "type": "boolean", "default": "`false`. **Deprecated.**", "desc": "If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." } ] } ] } ], "desc": "

Removes the directory identified by path.

\n

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.

\n

To get a behavior similar to the rm -rf Unix command, use\nfsPromises.rm() with options { recursive: true, force: true }.

" }, { "textRaw": "`fsPromises.rm(path[, options])`", "type": "method", "name": "rm", "meta": { "added": [ "v14.14.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. **Default:** `false`.", "name": "force", "type": "boolean", "default": "`false`", "desc": "When `true`, exceptions will be ignored if `path` does not exist." }, { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure. **Default:** `false`.", "name": "recursive", "type": "boolean", "default": "`false`", "desc": "If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." } ] } ] } ], "desc": "

Removes files and directories (modeled on the standard POSIX rm utility).

" }, { "textRaw": "`fsPromises.stat(path[, options])`", "type": "method", "name": "stat", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the {fs.Stats} object for the given `path`.", "name": "return", "type": "Promise", "desc": "Fulfills with the {fs.Stats} object for the given `path`." }, "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.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] } ] } ] }, { "textRaw": "`fsPromises.symlink(target, path[, type])`", "type": "method", "name": "symlink", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`target` {string|Buffer|URL}", "name": "target", "type": "string|Buffer|URL" }, { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`type` {string} **Default:** `'file'`", "name": "type", "type": "string", "default": "`'file'`" } ] } ], "desc": "

Creates a symbolic link.

\n

The type argument is only used on Windows platforms and can be one of 'dir',\n'file', or 'junction'. Windows junction points require the destination path\nto be absolute. When using 'junction', the target argument will\nautomatically be normalized to absolute path.

" }, { "textRaw": "`fsPromises.truncate(path[, len])`", "type": "method", "name": "truncate", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`len` {integer} **Default:** `0`", "name": "len", "type": "integer", "default": "`0`" } ] } ], "desc": "

Truncates (shortens or extends the length) of the content at path to len\nbytes.

" }, { "textRaw": "`fsPromises.unlink(path)`", "type": "method", "name": "unlink", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" } ] } ], "desc": "

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.

" }, { "textRaw": "`fsPromises.utimes(path, atime, mtime)`", "type": "method", "name": "utimes", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "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" } ] } ], "desc": "

Change the file system timestamps of the object referenced by path.

\n

The atime and mtime arguments follow these rules:

\n
    \n
  • Values can be either numbers representing Unix epoch time, Dates, or a\nnumeric string like '123456789.0'.
  • \n
  • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
  • \n
" }, { "textRaw": "`fsPromises.watch(filename[, options])`", "type": "method", "name": "watch", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator} of objects with the properties:", "name": "return", "type": "AsyncIterator", "desc": "of objects with the properties:", "options": [ { "textRaw": "`eventType` {string} The type of change", "name": "eventType", "type": "string", "desc": "The type of change" }, { "textRaw": "`filename` {string|Buffer} The name of the file changed.", "name": "filename", "type": "string|Buffer", "desc": "The name of the file changed." } ] }, "params": [ { "textRaw": "`filename` {string|Buffer|URL}", "name": "filename", "type": "string|Buffer|URL" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. **Default:** `true`.", "name": "persistent", "type": "boolean", "default": "`true`", "desc": "Indicates whether the process should continue to run as long as files are being watched." }, { "textRaw": "`recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][]). **Default:** `false`.", "name": "recursive", "type": "boolean", "default": "`false`", "desc": "Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][])." }, { "textRaw": "`encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "Specifies the character encoding to be used for the filename passed to the listener." }, { "textRaw": "`signal` {AbortSignal} An {AbortSignal} used to signal when the watcher should stop.", "name": "signal", "type": "AbortSignal", "desc": "An {AbortSignal} used to signal when the watcher should stop." } ] } ] } ], "desc": "

Returns an async iterator that watches for changes on filename, where filename\nis either a file or a directory.

\n
const { watch } = require('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
\n

On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.

\n

All the caveats for fs.watch() also apply to fsPromises.watch().

" }, { "textRaw": "`fsPromises.writeFile(file, data[, options])`", "type": "method", "name": "writeFile", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v15.14.0", "pr-url": "https://github.com/nodejs/node/pull/37490", "description": "The `data` argument supports `AsyncIterable`, `Iterable` & `Stream`." }, { "version": "v15.2.0", "pr-url": "https://github.com/nodejs/node/pull/35993", "description": "The options argument may include an AbortSignal to abort an ongoing writeFile request." }, { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `data` parameter will stringify an object with an explicit `toString` function." }, { "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": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`file` {string|Buffer|URL|FileHandle} filename or `FileHandle`", "name": "file", "type": "string|Buffer|URL|FileHandle", "desc": "filename or `FileHandle`" }, { "textRaw": "`data` {string|Buffer|TypedArray|DataView|Object|AsyncIterable|Iterable |Stream}", "name": "data", "type": "string|Buffer|TypedArray|DataView|Object|AsyncIterable|Iterable |Stream" }, { "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:** `'w'`.", "name": "flag", "type": "string", "default": "`'w'`", "desc": "See [support of file system `flags`][]." }, { "textRaw": "`signal` {AbortSignal} allows aborting an in-progress writeFile", "name": "signal", "type": "AbortSignal", "desc": "allows aborting an in-progress writeFile" } ] } ] } ], "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a <Buffer>, or, an object with an own (not inherited)\ntoString function property.

\n

The encoding option is ignored if data is a buffer.

\n

If options is a string, then it specifies the encoding.

\n

Any specified <FileHandle> has to support writing.

\n

It is unsafe to use fsPromises.writeFile() multiple times on the same file\nwithout waiting for the promise to be settled.

\n

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().

\n

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.

\n
import { writeFile } from 'fs/promises';\nimport { Buffer } from '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
\n

Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.writeFile performs.

" } ], "type": "module", "displayName": "Promises API" }, { "textRaw": "Callback API", "name": "callback_api", "desc": "

The callback APIs perform all operations asynchronously, without blocking the\nevent loop, then invoke a callback function upon completion or error.

\n

The 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)`", "type": "method", "name": "access", "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." }, { "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`" }, { "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. Check File access constants for possible values\nof mode. It is possible to create a mask consisting of the bitwise OR of\ntwo or more values (e.g. fs.constants.W_OK | fs.constants.R_OK).

\n

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.

\n
import { access, constants } from '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 exists in the current directory, and if it is writable.\naccess(file, constants.F_OK | constants.W_OK, (err) => {\n  if (err) {\n    console.error(\n      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);\n  } else {\n    console.log(`${file} exists, and it is writable`);\n  }\n});\n
\n

Do 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.

\n

write (NOT RECOMMENDED)

\n
import { access, open, close } from '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
\n

write (RECOMMENDED)

\n
import { open, close } from '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
\n

read (NOT RECOMMENDED)

\n
import { access, open, close } from '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
\n

read (RECOMMENDED)

\n
import { open, close } from '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
\n

The \"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.

\n

In 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.

\n

On 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.

" }, { "textRaw": "`fs.appendFile(path, data[, options], callback)`", "type": "method", "name": "appendFile", "meta": { "added": [ "v0.6.7" ], "changes": [ { "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." }, { "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": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.

\n
import { appendFile } from '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
\n

If options is a string, then it specifies the encoding:

\n
import { appendFile } from 'fs';\n\nappendFile('message.txt', 'data to append', 'utf8', callback);\n
\n

The 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.

\n
import { open, close, appendFile } from '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)`", "type": "method", "name": "chmod", "meta": { "added": [ "v0.1.30" ], "changes": [ { "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.

\n

See the POSIX chmod(2) documentation for more detail.

\n
import { chmod } from '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", "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:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ConstantOctalDescription
fs.constants.S_IRUSR0o400read by owner
fs.constants.S_IWUSR0o200write by owner
fs.constants.S_IXUSR0o100execute/search by owner
fs.constants.S_IRGRP0o40read by group
fs.constants.S_IWGRP0o20write by group
fs.constants.S_IXGRP0o10execute/search by group
fs.constants.S_IROTH0o4read by others
fs.constants.S_IWOTH0o2write by others
fs.constants.S_IXOTH0o1execute/search by others
\n

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.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
NumberDescription
7read, write, and execute
6read and write
5read and execute
4read only
3write and execute
2write only
1execute only
0no permission
\n

For example, the octal value 0o765 means:

\n
    \n
  • The owner may read, write and execute the file.
  • \n
  • The group may read and write the file.
  • \n
  • Others may read and execute the file.
  • \n
\n

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 not\nexposed in fs.constants.

\n

Caveats: on Windows only the write permission can be changed, and the\ndistinction among the permissions of group, owner or others is not\nimplemented.

", "type": "module", "displayName": "File modes" } ] }, { "textRaw": "`fs.chown(path, uid, gid, callback)`", "type": "method", "name": "chown", "meta": { "added": [ "v0.1.97" ], "changes": [ { "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.

\n

See the POSIX chown(2) documentation for more detail.

" }, { "textRaw": "`fs.close(fd[, callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.0.2" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37174", "description": "A default callback is now used if one is not provided." }, { "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": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Closes the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.

\n

Calling fs.close() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

\n

See the POSIX close(2) documentation for more detail.

" }, { "textRaw": "`fs.copyFile(src, dest[, mode], callback)`", "type": "method", "name": "copyFile", "meta": { "added": [ "v8.5.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} modifiers for copy operation. **Default:** `0`.", "name": "mode", "type": "integer", "default": "`0`", "desc": "modifiers for copy operation." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

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).

\n
    \n
  • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
  • \n
  • 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.
  • \n
  • 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.
  • \n
\n
import { copyFile, constants } from '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)`", "type": "method", "name": "cp", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "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. 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. Can also return a `Promise` that resolves to `true` or `false`" }, { "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": "`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": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Asynchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.

\n

When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.

" }, { "textRaw": "`fs.createReadStream(path[, options])`", "type": "method", "name": "createReadStream", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": [ "v15.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/35922", "description": "The `fd` option accepts FileHandle arguments." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31408", "description": "Change `emitClose` default to `true`." }, { "version": [ "v13.6.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29083", "description": "The `fs` options allow overriding the used `fs` implementation." }, { "version": "v12.10.0", "pr-url": "https://github.com/nodejs/node/pull/29212", "description": "Enable `emitClose` option." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/19898", "description": "Impose new restrictions on `start` and `end`, throwing more appropriate errors in cases when we cannot reasonably handle the input values." }, { "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/7831", "description": "The passed `options` object will never be modified." }, { "version": "v2.3.0", "pr-url": "https://github.com/nodejs/node/pull/1845", "description": "The passed `options` object can be a string now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.ReadStream} See [Readable Stream][].", "name": "return", "type": "fs.ReadStream", "desc": "See [Readable Stream][]." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'r'`.", "name": "flags", "type": "string", "default": "`'r'`", "desc": "See [support of file system `flags`][]." }, { "textRaw": "`encoding` {string} **Default:** `null`", "name": "encoding", "type": "string", "default": "`null`" }, { "textRaw": "`fd` {integer|FileHandle} **Default:** `null`", "name": "fd", "type": "integer|FileHandle", "default": "`null`" }, { "textRaw": "`mode` {integer} **Default:** `0o666`", "name": "mode", "type": "integer", "default": "`0o666`" }, { "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": "`fs` {Object|null} **Default:** `null`", "name": "fs", "type": "Object|null", "default": "`null`" } ] } ] } ], "desc": "

Unlike the 16 kb default highWaterMark for a readable stream, the stream\nreturned by this method has a default highWaterMark of 64 kb.

\n

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>.

\n

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>.

\n

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.

\n

By default, the stream will emit a 'close' event after it has been\ndestroyed, like most Readable streams. Set the emitClose option to\nfalse to change this behavior.

\n

By providing the fs option, it is possible to override the corresponding fs\nimplementations for open, read, and close. When providing the fs option,\noverrides for open, read, and close are required.

\n
import { createReadStream } from '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
\n

If 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.

\n

mode sets the file mode (permission and sticky bits), but only if the\nfile was created.

\n

An example to read the last 10 bytes of a file which is 100 bytes long:

\n
import { createReadStream } from 'fs';\n\ncreateReadStream('sample.txt', { start: 90, end: 99 });\n
\n

If options is a string, then it specifies the encoding.

" }, { "textRaw": "`fs.createWriteStream(path[, options])`", "type": "method", "name": "createWriteStream", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": [ "v15.4.0" ], "pr-url": "https://github.com/nodejs/node/pull/35922", "description": "The `fd` option accepts FileHandle arguments." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31408", "description": "Change `emitClose` default to `true`." }, { "version": [ "v13.6.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/29083", "description": "The `fs` options allow overriding the used `fs` implementation." }, { "version": "v12.10.0", "pr-url": "https://github.com/nodejs/node/pull/29212", "description": "Enable `emitClose` option." }, { "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/7831", "description": "The passed `options` object will never be modified." }, { "version": "v5.5.0", "pr-url": "https://github.com/nodejs/node/pull/3679", "description": "The `autoClose` option is supported now." }, { "version": "v2.3.0", "pr-url": "https://github.com/nodejs/node/pull/1845", "description": "The passed `options` object can be a string now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.WriteStream} See [Writable Stream][].", "name": "return", "type": "fs.WriteStream", "desc": "See [Writable Stream][]." }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`flags` {string} See [support of file system `flags`][]. **Default:** `'w'`.", "name": "flags", "type": "string", "default": "`'w'`", "desc": "See [support of file system `flags`][]." }, { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" }, { "textRaw": "`fd` {integer|FileHandle} **Default:** `null`", "name": "fd", "type": "integer|FileHandle", "default": "`null`" }, { "textRaw": "`mode` {integer} **Default:** `0o666`", "name": "mode", "type": "integer", "default": "`0o666`" }, { "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": "`fs` {Object|null} **Default:** `null`", "name": "fs", "type": "Object|null", "default": "`null`" } ] } ] } ], "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 replacing\nit may require the flags option to be set to r+ rather than the default w.\nThe encoding can be any one of those accepted by <Buffer>.

\n

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.

\n

By default, the stream will emit a 'close' event after it has been\ndestroyed, like most Writable streams. Set the emitClose option to\nfalse to change this behavior.

\n

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 open,\nclose, and at least one of write and writev are required.

\n

Like <fs.ReadStream>, if fd is specified, <fs.WriteStream> will ignore the\npath 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>.

\n

If options is a string, then it specifies the encoding.

" }, { "textRaw": "`fs.exists(path, callback)`", "type": "method", "name": "exists", "meta": { "added": [ "v0.0.2" ], "deprecated": [ "v1.0.0" ], "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." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`exists` {boolean}", "name": "exists", "type": "boolean" } ] } ] } ], "desc": "

Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false:

\n
import { exists } from 'fs';\n\nexists('/etc/passwd', (e) => {\n  console.log(e ? 'it exists' : 'no passwd!');\n});\n
\n

The 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().

\n

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.

\n

write (NOT RECOMMENDED)

\n
import { exists, open, close } from '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
\n

write (RECOMMENDED)

\n
import { open, close } from '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
\n

read (NOT RECOMMENDED)

\n
import { open, close, exists } from '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
\n

read (RECOMMENDED)

\n
import { open, close } from '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
\n

The \"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.

\n

In 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)`", "type": "method", "name": "fchmod", "meta": { "added": [ "v0.4.7" ], "changes": [ { "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.

\n

See the POSIX fchmod(2) documentation for more detail.

" }, { "textRaw": "`fs.fchown(fd, uid, gid, callback)`", "type": "method", "name": "fchown", "meta": { "added": [ "v0.4.7" ], "changes": [ { "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": "`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": "

Sets the owner of the file. No arguments other than a possible exception are\ngiven to the completion callback.

\n

See the POSIX fchown(2) documentation for more detail.

" }, { "textRaw": "`fs.fdatasync(fd, callback)`", "type": "method", "name": "fdatasync", "meta": { "added": [ "v0.1.96" ], "changes": [ { "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": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.fstat(fd[, options], callback)`", "type": "method", "name": "fstat", "meta": { "added": [ "v0.1.95" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." }, { "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": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats}", "name": "stats", "type": "fs.Stats" } ] } ] } ], "desc": "

Invokes the callback with the <fs.Stats> for the file descriptor.

\n

See the POSIX fstat(2) documentation for more detail.

" }, { "textRaw": "`fs.fsync(fd, callback)`", "type": "method", "name": "fsync", "meta": { "added": [ "v0.1.96" ], "changes": [ { "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": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.ftruncate(fd[, len], callback)`", "type": "method", "name": "ftruncate", "meta": { "added": [ "v0.8.6" ], "changes": [ { "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": "`len` {integer} **Default:** `0`", "name": "len", "type": "integer", "default": "`0`" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Truncates the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.

\n

See the POSIX ftruncate(2) documentation for more detail.

\n

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.

\n

For example, the following program retains only the first four bytes of the\nfile:

\n
import { open, close, ftruncate } from '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
\n

If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):

\n

If len is negative then 0 will be used.

" }, { "textRaw": "`fs.futimes(fd, atime, mtime, callback)`", "type": "method", "name": "futimes", "meta": { "added": [ "v0.4.2" ], "changes": [ { "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." }, { "version": "v4.1.0", "pr-url": "https://github.com/nodejs/node/pull/2387", "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`atime` {number|string|Date}", "name": "atime", "type": "number|string|Date" }, { "textRaw": "`mtime` {number|string|Date}", "name": "mtime", "type": "number|string|Date" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Change the file system timestamps of the object referenced by the supplied file\ndescriptor. See fs.utimes().

" }, { "textRaw": "`fs.lchmod(path, mode, callback)`", "type": "method", "name": "lchmod", "meta": { "deprecated": [ "v0.4.7" ], "changes": [ { "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": "`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.

\n

This method is only implemented on macOS.

\n

See the POSIX lchmod(2) documentation for more detail.

" }, { "textRaw": "`fs.lchown(path, uid, gid, callback)`", "type": "method", "name": "lchown", "meta": { "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/21498", "description": "This API is no longer deprecated." }, { "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." }, { "version": "v0.4.7", "description": "Documentation-only deprecation." } ] }, "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": "

Set the owner of the symbolic link. No arguments other than a possible\nexception are given to the completion callback.

\n

See the POSIX lchown(2) documentation for more detail.

" }, { "textRaw": "`fs.lutimes(path, atime, mtime, callback)`", "type": "method", "name": "lutimes", "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" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

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.

\n

No arguments other than a possible exception are given to the completion\ncallback.

" }, { "textRaw": "`fs.link(existingPath, newPath, callback)`", "type": "method", "name": "link", "meta": { "added": [ "v0.1.31" ], "changes": [ { "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.

" }, { "textRaw": "`fs.lstat(path[, options], callback)`", "type": "method", "name": "lstat", "meta": { "added": [ "v0.1.30" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." }, { "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": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats}", "name": "stats", "type": "fs.Stats" } ] } ] } ], "desc": "

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.

\n

See the POSIX lstat(2) documentation for more details.

" }, { "textRaw": "`fs.mkdir(path[, options], callback)`", "type": "method", "name": "mkdir", "meta": { "added": [ "v0.1.8" ], "changes": [ { "version": [ "v13.11.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31530", "description": "In `recursive` mode, the callback now receives the first created path as an argument." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/21875", "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." }, { "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": "`options` {Object|integer}", "name": "options", "type": "Object|integer", "options": [ { "textRaw": "`recursive` {boolean} **Default:** `false`", "name": "recursive", "type": "boolean", "default": "`false`" }, { "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", "name": "mode", "type": "string|integer", "default": "`0o777`", "desc": "Not supported on Windows." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Asynchronously creates a directory.

\n

The 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.

\n

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.

\n
import { mkdir } from 'fs';\n\n// Creates /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
\n

On Windows, using fs.mkdir() on the root directory even with recursion will\nresult in an error:

\n
import { mkdir } from 'fs';\n\nmkdir('/', { recursive: true }, (err) => {\n  // => [Error: EPERM: operation not permitted, mkdir 'C:\\']\n});\n
\n

See the POSIX mkdir(2) documentation for more details.

" }, { "textRaw": "`fs.mkdtemp(prefix[, options], callback)`", "type": "method", "name": "mkdtemp", "meta": { "added": [ "v5.10.0" ], "changes": [ { "version": "v16.5.0", "pr-url": "https://github.com/nodejs/node/pull/39028", "description": "The `prefix` parameter now accepts an empty string." }, { "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." }, { "version": "v6.2.1", "pr-url": "https://github.com/nodejs/node/pull/6828", "description": "The `callback` parameter is optional now." } ] }, "signatures": [ { "params": [ { "textRaw": "`prefix` {string}", "name": "prefix", "type": "string" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`directory` {string}", "name": "directory", "type": "string" } ] } ] } ], "desc": "

Creates a unique temporary directory.

\n

Generates 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.

\n

The created directory path is passed as a string to the callback's second\nparameter.

\n

The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

\n
import { mkdtemp } from 'fs';\n\nmkdtemp(path.join(os.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
\n

The 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('path').sep).

\n
import { tmpdir } from 'os';\nimport { mkdtemp } from '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 '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)`", "type": "method", "name": "open", "meta": { "added": [ "v0.0.2" ], "changes": [ { "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`][]." }, { "textRaw": "`mode` {string|integer} **Default:** `0o666` (readable and writable)", "name": "mode", "type": "string|integer", "default": "`0o666` (readable and writable)" }, { "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.

\n

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().

\n

The callback gets two arguments (err, fd).

\n

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.

\n

Functions based on fs.open() exhibit this behavior as well:\nfs.writeFile(), fs.readFile(), etc.

" }, { "textRaw": "`fs.opendir(path[, options], callback)`", "type": "method", "name": "opendir", "meta": { "added": [ "v12.12.0" ], "changes": [ { "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": "`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.

\n

Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.

\n

The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

" }, { "textRaw": "`fs.read(fd, buffer, offset, length, position, callback)`", "type": "method", "name": "read", "meta": { "added": [ "v0.0.2" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `buffer` parameter can now be any `TypedArray`, or a `DataView`." }, { "version": "v7.4.0", "pr-url": "https://github.com/nodejs/node/pull/10382", "description": "The `buffer` parameter can now be a `Uint8Array`." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4518", "description": "The `length` parameter can now be `0`." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView} The buffer that the data will be written to. **Default:** `Buffer.alloc(16384)`", "name": "buffer", "type": "Buffer|TypedArray|DataView", "default": "`Buffer.alloc(16384)`", "desc": "The buffer that the data will be written to." }, { "textRaw": "`offset` {integer} The position in `buffer` to write the data to. **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`", "desc": "The position in `buffer` to write the data to." }, { "textRaw": "`length` {integer} The number of bytes to read. **Default:** `buffer.byteLength`", "name": "length", "type": "integer", "default": "`buffer.byteLength`", "desc": "The number of bytes to read." }, { "textRaw": "`position` {integer|bigint} Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If `position` is an integer, the file position will be unchanged.", "name": "position", "type": "integer|bigint", "desc": "Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If `position` is an integer, the file position will be unchanged." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`bytesRead` {integer}", "name": "bytesRead", "type": "integer" }, { "textRaw": "`buffer` {Buffer}", "name": "buffer", "type": "Buffer" } ] } ] } ], "desc": "

Read data from the file specified by fd.

\n

The callback is given the three arguments, (err, bytesRead, buffer).

\n

If the file is not modified concurrently, the end-of-file is reached when the\nnumber of bytes read is zero.

\n

If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffer properties.

" }, { "textRaw": "`fs.read(fd, [options,] callback)`", "type": "method", "name": "read", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [ { "version": [ "v13.11.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31402", "description": "Options object can be passed in to make Buffer, offset, length and position optional." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`", "name": "buffer", "type": "Buffer|TypedArray|DataView", "default": "`Buffer.alloc(16384)`" }, { "textRaw": "`offset` {integer} **Default:** `0`", "name": "offset", "type": "integer", "default": "`0`" }, { "textRaw": "`length` {integer} **Default:** `buffer.byteLength`", "name": "length", "type": "integer", "default": "`buffer.byteLength`" }, { "textRaw": "`position` {integer|bigint} **Default:** `null`", "name": "position", "type": "integer|bigint", "default": "`null`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`bytesRead` {integer}", "name": "bytesRead", "type": "integer" }, { "textRaw": "`buffer` {Buffer}", "name": "buffer", "type": "Buffer" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.readdir(path[, options], callback)`", "type": "method", "name": "readdir", "meta": { "added": [ "v0.1.8" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22020", "description": "New option `withFileTypes` was added." }, { "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." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5616", "description": "The `options` parameter was added." } ] }, "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'`" }, { "textRaw": "`withFileTypes` {boolean} **Default:** `false`", "name": "withFileTypes", "type": "boolean", "default": "`false`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`files` {string[]|Buffer[]|fs.Dirent[]}", "name": "files", "type": "string[]|Buffer[]|fs.Dirent[]" } ] } ] } ], "desc": "

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 '..'.

\n

See the POSIX readdir(3) documentation for more details.

\n

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.

\n

If options.withFileTypes is set to true, the files array will contain\n<fs.Dirent> objects.

" }, { "textRaw": "`fs.readFile(path[, options], callback)`", "type": "method", "name": "readFile", "meta": { "added": [ "v0.1.29" ], "changes": [ { "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": "v15.2.0", "pr-url": "https://github.com/nodejs/node/pull/35911", "description": "The options argument may include an AbortSignal to abort an ongoing readFile request." }, { "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." }, { "version": "v5.1.0", "pr-url": "https://github.com/nodejs/node/pull/3740", "description": "The `callback` will always be called with `null` as the `error` parameter in case of success." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/3163", "description": "The `path` parameter can be a file descriptor now." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", "name": "path", "type": "string|Buffer|URL|integer", "desc": "filename or file descriptor" }, { "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" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error|AggregateError}", "name": "err", "type": "Error|AggregateError" }, { "textRaw": "`data` {string|Buffer}", "name": "data", "type": "string|Buffer" } ] } ] } ], "desc": "

Asynchronously reads the entire contents of a file.

\n
import { readFile } from 'fs';\n\nreadFile('/etc/passwd', (err, data) => {\n  if (err) throw err;\n  console.log(data);\n});\n
\n

The callback is passed two arguments (err, data), where data is the\ncontents of the file.

\n

If no encoding is specified, then the raw buffer is returned.

\n

If options is a string, then it specifies the encoding:

\n
import { readFile } from 'fs';\n\nreadFile('/etc/passwd', 'utf8', callback);\n
\n

When 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.

\n
import { readFile } from '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
\n

It is possible to abort an ongoing request using an AbortSignal. If a\nrequest is aborted the callback is called with an AbortError:

\n
import { readFile } from '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
\n

The fs.readFile() function buffers the entire file. To minimize memory costs,\nwhen possible prefer streaming via fs.createReadStream().

\n

Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.readFile performs.

", "modules": [ { "textRaw": "File descriptors", "name": "file_descriptors", "desc": "
    \n
  1. Any specified file descriptor has to support reading.
  2. \n
  3. If a file descriptor is specified as the path, it will not be closed\nautomatically.
  4. \n
  5. The reading will begin at the current position. For example, if the file\nalready had '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'.
  6. \n
", "type": "module", "displayName": "File descriptors" }, { "textRaw": "Performance Considerations", "name": "performance_considerations", "desc": "

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.

\n

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 KB of data. For regular files, each read will process\n512 KB of data.

\n

For 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.

\n

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.

", "type": "module", "displayName": "Performance Considerations" } ] }, { "textRaw": "`fs.readlink(path[, options], callback)`", "type": "method", "name": "readlink", "meta": { "added": [ "v0.1.31" ], "changes": [ { "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": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`linkString` {string|Buffer}", "name": "linkString", "type": "string|Buffer" } ] } ] } ], "desc": "

Reads the contents of the symbolic link referred to by path. The callback gets\ntwo arguments (err, linkString).

\n

See the POSIX readlink(2) documentation for more details.

\n

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.

" }, { "textRaw": "`fs.readv(fd, buffers[, position], callback)`", "type": "method", "name": "readv", "meta": { "added": [ "v13.13.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`bytesRead` {integer}", "name": "bytesRead", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" } ] } ] } ], "desc": "

Read from a file specified by fd and write to an array of ArrayBufferViews\nusing readv().

\n

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.

\n

The callback will be given three arguments: err, bytesRead, and\nbuffers. bytesRead is how many bytes were read from the file.

\n

If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffers properties.

" }, { "textRaw": "`fs.realpath(path[, options], callback)`", "type": "method", "name": "realpath", "meta": { "added": [ "v0.1.31" ], "changes": [ { "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": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/13028", "description": "Pipe/Socket resolve support was added." }, { "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." }, { "version": "v6.4.0", "pr-url": "https://github.com/nodejs/node/pull/7899", "description": "Calling `realpath` now works again for various edge cases on Windows." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/3594", "description": "The `cache` parameter was removed." } ] }, "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'`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`resolvedPath` {string|Buffer}", "name": "resolvedPath", "type": "string|Buffer" } ] } ] } ], "desc": "

Asynchronously computes the canonical pathname by resolving ., .. and\nsymbolic links.

\n

A canonical pathname is not necessarily unique. Hard links and bind mounts can\nexpose a file system entity through many pathnames.

\n

This function behaves like realpath(3), with some exceptions:

\n
    \n
  1. \n

    No case conversion is performed on case-insensitive file systems.

    \n
  2. \n
  3. \n

    The maximum number of symbolic links is platform-independent and generally\n(much) higher than what the native realpath(3) implementation supports.

    \n
  4. \n
\n

The callback gets two arguments (err, resolvedPath). May use process.cwd\nto resolve relative paths.

\n

Only paths that can be converted to UTF8 strings are supported.

\n

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 path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.

\n

If path resolves to a socket or a pipe, the function will return a system\ndependent name for that object.

" }, { "textRaw": "`fs.realpath.native(path[, options], callback)`", "type": "method", "name": "native", "meta": { "added": [ "v9.2.0" ], "changes": [] }, "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'`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`resolvedPath` {string|Buffer}", "name": "resolvedPath", "type": "string|Buffer" } ] } ] } ], "desc": "

Asynchronous realpath(3).

\n

The callback gets two arguments (err, resolvedPath).

\n

Only paths that can be converted to UTF8 strings are supported.

\n

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 path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.

\n

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.

" }, { "textRaw": "`fs.rename(oldPath, newPath, callback)`", "type": "method", "name": "rename", "meta": { "added": [ "v0.0.2" ], "changes": [ { "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 `oldPath` 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": "`oldPath` {string|Buffer|URL}", "name": "oldPath", "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": "

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.

\n

See also: rename(2).

\n
import { rename } from '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)`", "type": "method", "name": "rmdir", "meta": { "added": [ "v0.0.2" ], "changes": [ { "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}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure. **Default:** `false`. **Deprecated.**", "name": "recursive", "type": "boolean", "default": "`false`. **Deprecated.**", "desc": "If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `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.

\n

Using fs.rmdir() on a file (not a directory) results in an ENOENT error on\nWindows and an ENOTDIR error on POSIX.

\n

To get a behavior similar to the rm -rf Unix command, use fs.rm()\nwith options { recursive: true, force: true }.

" }, { "textRaw": "`fs.rm(path[, options], callback)`", "type": "method", "name": "rm", "meta": { "added": [ "v14.14.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. **Default:** `false`.", "name": "force", "type": "boolean", "default": "`false`", "desc": "When `true`, exceptions will be ignored if `path` does not exist." }, { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive removal. In recursive mode operations are retried on failure. **Default:** `false`.", "name": "recursive", "type": "boolean", "default": "`false`", "desc": "If `true`, perform a recursive removal. In recursive mode operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.stat(path[, options], callback)`", "type": "method", "name": "stat", "meta": { "added": [ "v0.0.2" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." }, { "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": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats}", "name": "stats", "type": "fs.Stats" } ] } ] } ], "desc": "

Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is an <fs.Stats> object.

\n

In case of an error, the err.code will be one of Common System Errors.

\n

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.

\n

To check if a file exists without manipulating it afterwards, fs.access()\nis recommended.

\n

For example, given the following directory structure:

\n
- txtDir\n-- file.txt\n- app.js\n
\n

The next program will check for the stats of the given paths:

\n
import { stat } from '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
\n

The resulting output will resemble:

\n
true\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.symlink(target, path[, type], callback)`", "type": "method", "name": "symlink", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23724", "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`." }, { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." } ] }, "signatures": [ { "params": [ { "textRaw": "`target` {string|Buffer|URL}", "name": "target", "type": "string|Buffer|URL" }, { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`type` {string}", "name": "type", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Creates the link called path pointing to target. No arguments other than a\npossible exception are given to the completion callback.

\n

See the POSIX symlink(2) documentation for more details.

\n

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\nnot set, Node.js will autodetect target type and use 'file' or 'dir'. If\nthe 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.

\n

Relative targets are relative to the link’s parent directory.

\n
import { symlink } from 'fs';\n\nsymlink('./mew', './example/mewtwo', callback);\n
\n

The above example creates a symbolic link mewtwo in the example which points\nto mew in the same directory:

\n
$ tree example/\nexample/\n├── mew\n└── mewtwo -> ./mew\n
" }, { "textRaw": "`fs.truncate(path[, len], callback)`", "type": "method", "name": "truncate", "meta": { "added": [ "v0.8.6" ], "changes": [ { "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`" }, { "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.

\n
import { truncate } from '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
\n
const { truncate } = require('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
\n

Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

\n

See the POSIX truncate(2) documentation for more details.

" }, { "textRaw": "`fs.unlink(path, callback)`", "type": "method", "name": "unlink", "meta": { "added": [ "v0.0.2" ], "changes": [ { "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": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Asynchronously removes a file or symbolic link. No arguments other than a\npossible exception are given to the completion callback.

\n
import { unlink } from '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
\n

fs.unlink() will not work on a directory, empty or otherwise. To remove a\ndirectory, use fs.rmdir().

\n

See the POSIX unlink(2) documentation for more details.

" }, { "textRaw": "`fs.unwatchFile(filename[, listener])`", "type": "method", "name": "unwatchFile", "meta": { "added": [ "v0.1.31" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`filename` {string|Buffer|URL}", "name": "filename", "type": "string|Buffer|URL" }, { "textRaw": "`listener` {Function} Optional, a listener previously attached using `fs.watchFile()`", "name": "listener", "type": "Function", "desc": "Optional, a listener previously attached using `fs.watchFile()`" } ] } ], "desc": "

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.

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.

\n

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.

" }, { "textRaw": "`fs.utimes(path, atime, mtime, callback)`", "type": "method", "name": "utimes", "meta": { "added": [ "v0.4.2" ], "changes": [ { "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": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11919", "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." }, { "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." }, { "version": "v4.1.0", "pr-url": "https://github.com/nodejs/node/pull/2387", "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." } ] }, "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" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Change the file system timestamps of the object referenced by path.

\n

The atime and mtime arguments follow these rules:

\n
    \n
  • Values can be either numbers representing Unix epoch time in seconds,\nDates, or a numeric string like '123456789.0'.
  • \n
  • If the value can not be converted to a number, or is NaN, Infinity or\n-Infinity, an Error will be thrown.
  • \n
" }, { "textRaw": "`fs.watch(filename[, options][, listener])`", "type": "method", "name": "watch", "meta": { "added": [ "v0.5.10" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37190", "description": "Added support for closing the watcher with an AbortSignal." }, { "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." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7831", "description": "The passed `options` object will never be modified." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.FSWatcher}", "name": "return", "type": "fs.FSWatcher" }, "params": [ { "textRaw": "`filename` {string|Buffer|URL}", "name": "filename", "type": "string|Buffer|URL" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`persistent` {boolean} Indicates whether the process should continue to run as long as files are being watched. **Default:** `true`.", "name": "persistent", "type": "boolean", "default": "`true`", "desc": "Indicates whether the process should continue to run as long as files are being watched." }, { "textRaw": "`recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][]). **Default:** `false`.", "name": "recursive", "type": "boolean", "default": "`false`", "desc": "Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See [caveats][])." }, { "textRaw": "`encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "Specifies the character encoding to be used for the filename passed to the listener." }, { "textRaw": "`signal` {AbortSignal} allows closing the watcher with an AbortSignal.", "name": "signal", "type": "AbortSignal", "desc": "allows closing the watcher with an AbortSignal." } ] }, { "textRaw": "`listener` {Function|undefined} **Default:** `undefined`", "name": "listener", "type": "Function|undefined", "default": "`undefined`", "options": [ { "textRaw": "`eventType` {string}", "name": "eventType", "type": "string" }, { "textRaw": "`filename` {string|Buffer}", "name": "filename", "type": "string|Buffer" } ] } ] } ], "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory.

\n

The second argument is optional. If options is provided as a string, it\nspecifies the encoding. Otherwise options should be passed as an object.

\n

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.

\n

On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.

\n

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.

\n

If a signal is passed, aborting the corresponding AbortController will close\nthe returned <fs.FSWatcher>.

", "miscs": [ { "textRaw": "Caveats", "name": "Caveats", "type": "misc", "desc": "

The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.

\n

The recursive 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.

\n

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.

", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "

This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.

\n
    \n
  • On Linux systems, this uses inotify(7).
  • \n
  • On BSD systems, this uses kqueue(2).
  • \n
  • On macOS, this uses kqueue(2) for files and FSEvents for\ndirectories.
  • \n
  • On SunOS systems (including Solaris and SmartOS), this uses event ports.
  • \n
  • On Windows systems, this feature depends on ReadDirectoryChangesW.
  • \n
  • On AIX systems, this feature depends on AHAFS, which must be enabled.
  • \n
  • On IBM i systems, this feature is not supported.
  • \n
\n

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.

\n

It is still possible to use fs.watchFile(), which uses stat polling, but\nthis method is slower and less reliable.

" }, { "textRaw": "Inodes", "name": "Inodes", "type": "misc", "desc": "

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.

\n

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.

\n
import { watch } from '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)`", "type": "method", "name": "watchFile", "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": [ { "return": { "textRaw": "Returns: {fs.StatWatcher}", "name": "return", "type": "fs.StatWatcher" }, "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`" } ] }, { "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" } ] } ] } ], "desc": "

Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.

\n

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.

\n

The listener gets two arguments the current stat object and the previous\nstat object:

\n
import { watchFile } from '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
\n

These stat objects are instances of fs.Stat. If the bigint option is true,\nthe numeric values in these objects are specified as BigInts.

\n

To be notified when the file was modified, not just accessed, it is necessary\nto compare curr.mtime and prev.mtime.

\n

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.

\n

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.

\n

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).

\n

This happens when:

\n
    \n
  • the file is deleted, followed by a restore
  • \n
  • the file is renamed and then renamed a second time back to its original name
  • \n
" }, { "textRaw": "`fs.write(fd, buffer[, offset[, length[, position]]], callback)`", "type": "method", "name": "write", "meta": { "added": [ "v0.0.2" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `buffer` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `buffer` parameter won't coerce unsupported input to strings anymore." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." }, { "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.4.0", "pr-url": "https://github.com/nodejs/node/pull/10382", "description": "The `buffer` parameter can now be a `Uint8Array`." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/7856", "description": "The `offset` and `length` parameters are optional now." }, { "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": "`buffer` {Buffer|TypedArray|DataView|string|Object}", "name": "buffer", "type": "Buffer|TypedArray|DataView|string|Object" }, { "textRaw": "`offset` {integer}", "name": "offset", "type": "integer" }, { "textRaw": "`length` {integer}", "name": "length", "type": "integer" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" }, { "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. If buffer is a normal object, it\nmust have an own toString function property.

\n

offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.

\n

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).

\n

The callback will be given three arguments (err, bytesWritten, buffer) where\nbytesWritten specifies how many bytes were written from buffer.

\n

If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesWritten and buffer properties.

\n

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.

\n

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, string[, position[, encoding]], callback)`", "type": "method", "name": "write", "meta": { "added": [ "v0.11.5" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `string` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `string` parameter won't coerce unsupported input to strings anymore." }, { "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.2.0", "pr-url": "https://github.com/nodejs/node/pull/7856", "description": "The `position` parameter is optional now." }, { "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": "`string` {string|Object}", "name": "string", "type": "string|Object" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" }, { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`written` {integer}", "name": "written", "type": "integer" }, { "textRaw": "`string` {string}", "name": "string", "type": "string" } ] } ] } ], "desc": "

Write string to the file specified by fd. If string is not a string, or an\nobject with an own toString function property, then an exception is thrown.

\n

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).

\n

encoding is the expected string encoding.

\n

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.

\n

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.

\n

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.

\n

On 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.

" }, { "textRaw": "`fs.writeFile(file, data[, options], callback)`", "type": "method", "name": "writeFile", "meta": { "added": [ "v0.1.29" ], "changes": [ { "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": "v15.2.0", "pr-url": "https://github.com/nodejs/node/pull/35993", "description": "The options argument may include an AbortSignal to abort an ongoing writeFile request." }, { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `data` parameter will stringify an object with an explicit `toString` function." }, { "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." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." }, { "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.4.0", "pr-url": "https://github.com/nodejs/node/pull/10382", "description": "The `data` parameter can now be a `Uint8Array`." }, { "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." }, { "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": "`file` {string|Buffer|URL|integer} filename or file descriptor", "name": "file", "type": "string|Buffer|URL|integer", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string|Buffer|TypedArray|DataView|Object}", "name": "data", "type": "string|Buffer|TypedArray|DataView|Object" }, { "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:** `'w'`.", "name": "flag", "type": "string", "default": "`'w'`", "desc": "See [support of file system `flags`][]." }, { "textRaw": "`signal` {AbortSignal} allows aborting an in-progress writeFile", "name": "signal", "type": "AbortSignal", "desc": "allows aborting an in-progress writeFile" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error|AggregateError}", "name": "err", "type": "Error|AggregateError" } ] } ] } ], "desc": "

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.

\n

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.

\n

The encoding option is ignored if data is a buffer.

\n

If data is a plain object, it must have an own (not inherited) toString\nfunction property.

\n
import { writeFile } from 'fs';\nimport { Buffer } from '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
\n

If options is a string, then it specifies the encoding:

\n
import { writeFile } from 'fs';\n\nwriteFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
\n

It is unsafe to use fs.writeFile() multiple times on the same file without\nwaiting for the callback. For this scenario, fs.createWriteStream() is\nrecommended.

\n

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().

\n

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.

\n
import { writeFile } from 'fs';\nimport { Buffer } from '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
\n

Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.writeFile performs.

", "modules": [ { "textRaw": "Using `fs.writeFile()` with file descriptors", "name": "using_`fs.writefile()`_with_file_descriptors", "desc": "

When file is a file descriptor, the behavior is almost identical to directly\ncalling fs.write() like:

\n
import { write } from 'fs';\nimport { Buffer } from 'buffer';\n\nwrite(fd, Buffer.from(data, options.encoding), callback);\n
\n

The 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).

\n

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.

\n

For 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'.

", "type": "module", "displayName": "Using `fs.writeFile()` with file descriptors" } ] }, { "textRaw": "`fs.writev(fd, buffers[, position], callback)`", "type": "method", "name": "writev", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`bytesWritten` {integer}", "name": "bytesWritten", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" } ] } ] } ], "desc": "

Write an array of ArrayBufferViews to the file specified by fd using\nwritev().

\n

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.

\n

The callback will be given three arguments: err, bytesWritten, and\nbuffers. bytesWritten is how many bytes were written from buffers.

\n

If this method is util.promisify()ed, it returns a promise for an\nObject with bytesWritten and buffers properties.

\n

It is unsafe to use fs.writev() multiple times on the same file without\nwaiting for the callback. For this scenario, use fs.createWriteStream().

\n

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.

" } ], "type": "module", "displayName": "Callback API" }, { "textRaw": "Synchronous API", "name": "synchronous_api", "desc": "

The synchronous APIs perform all operations synchronously, blocking the\nevent loop until the operation completes or fails.

", "methods": [ { "textRaw": "`fs.accessSync(path[, mode])`", "type": "method", "name": "accessSync", "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`" } ] } ], "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. Check File access constants for\npossible values of mode. It is possible to create a mask consisting of\nthe bitwise OR of two or more values\n(e.g. fs.constants.W_OK | fs.constants.R_OK).

\n

If any of the accessibility checks fail, an Error will be thrown. Otherwise,\nthe method will return undefined.

\n
import { accessSync, constants } from '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])`", "type": "method", "name": "appendFileSync", "meta": { "added": [ "v0.6.7" ], "changes": [ { "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`][]." } ] } ] } ], "desc": "

Synchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.

\n
import { appendFileSync } from '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
\n

If options is a string, then it specifies the encoding:

\n
import { appendFileSync } from 'fs';\n\nappendFileSync('message.txt', 'data to append', 'utf8');\n
\n

The 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.

\n
import { openSync, closeSync, appendFileSync } from '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)`", "type": "method", "name": "chmodSync", "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().

\n

See the POSIX chmod(2) documentation for more detail.

" }, { "textRaw": "`fs.chownSync(path, uid, gid)`", "type": "method", "name": "chownSync", "meta": { "added": [ "v0.1.97" ], "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": "`uid` {integer}", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer}", "name": "gid", "type": "integer" } ] } ], "desc": "

Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().

\n

See the POSIX chown(2) documentation for more detail.

" }, { "textRaw": "`fs.closeSync(fd)`", "type": "method", "name": "closeSync", "meta": { "added": [ "v0.1.21" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" } ] } ], "desc": "

Closes the file descriptor. Returns undefined.

\n

Calling fs.closeSync() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.

\n

See the POSIX close(2) documentation for more detail.

" }, { "textRaw": "`fs.copyFileSync(src, dest[, mode])`", "type": "method", "name": "copyFileSync", "meta": { "added": [ "v8.5.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} modifiers for copy operation. **Default:** `0`.", "name": "mode", "type": "integer", "default": "`0`", "desc": "modifiers for copy operation." } ] } ], "desc": "

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.

\n

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).

\n
    \n
  • fs.constants.COPYFILE_EXCL: The copy operation will fail if dest already\nexists.
  • \n
  • 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.
  • \n
  • 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.
  • \n
\n
import { copyFileSync, constants } from '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])`", "type": "method", "name": "cpSync", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "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. **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." }, { "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": "`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" } ] } ] } ], "desc": "

Synchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.

\n

When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.

" }, { "textRaw": "`fs.existsSync(path)`", "type": "method", "name": "existsSync", "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": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" } ] } ], "desc": "

Returns true if the path exists, false otherwise.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.exists().

\n

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.

\n
import { existsSync } from 'fs';\n\nif (existsSync('/etc/passwd'))\n  console.log('The path exists.');\n
" }, { "textRaw": "`fs.fchmodSync(fd, mode)`", "type": "method", "name": "fchmodSync", "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.

\n

See the POSIX fchmod(2) documentation for more detail.

" }, { "textRaw": "`fs.fchownSync(fd, uid, gid)`", "type": "method", "name": "fchownSync", "meta": { "added": [ "v0.4.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`uid` {integer} The file's new owner's user id.", "name": "uid", "type": "integer", "desc": "The file's new owner's user id." }, { "textRaw": "`gid` {integer} The file's new group's group id.", "name": "gid", "type": "integer", "desc": "The file's new group's group id." } ] } ], "desc": "

Sets the owner of the file. Returns undefined.

\n

See the POSIX fchown(2) documentation for more detail.

" }, { "textRaw": "`fs.fdatasyncSync(fd)`", "type": "method", "name": "fdatasyncSync", "meta": { "added": [ "v0.1.96" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.fstatSync(fd[, options])`", "type": "method", "name": "fstatSync", "meta": { "added": [ "v0.1.95" ], "changes": [ { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.Stats}", "name": "return", "type": "fs.Stats" }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`bigint` {boolean} Whether the numeric values in the returned {fs.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." } ] } ] } ], "desc": "

Retrieves the <fs.Stats> for the file descriptor.

\n

See the POSIX fstat(2) documentation for more detail.

" }, { "textRaw": "`fs.fsyncSync(fd)`", "type": "method", "name": "fsyncSync", "meta": { "added": [ "v0.1.96" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" } ] } ], "desc": "

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.

" }, { "textRaw": "`fs.ftruncateSync(fd[, len])`", "type": "method", "name": "ftruncateSync", "meta": { "added": [ "v0.8.6" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`len` {integer} **Default:** `0`", "name": "len", "type": "integer", "default": "`0`" } ] } ], "desc": "

Truncates the file descriptor. Returns undefined.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.ftruncate().

" }, { "textRaw": "`fs.futimesSync(fd, atime, mtime)`", "type": "method", "name": "futimesSync", "meta": { "added": [ "v0.4.2" ], "changes": [ { "version": "v4.1.0", "pr-url": "https://github.com/nodejs/node/pull/2387", "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`atime` {number|string|Date}", "name": "atime", "type": "number|string|Date" }, { "textRaw": "`mtime` {number|string|Date}", "name": "mtime", "type": "number|string|Date" } ] } ], "desc": "

Synchronous version of fs.futimes(). Returns undefined.

" }, { "textRaw": "`fs.lchmodSync(path, mode)`", "type": "method", "name": "lchmodSync", "meta": { "deprecated": [ "v0.4.7" ], "changes": [] }, "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.

\n

This method is only implemented on macOS.

\n

See the POSIX lchmod(2) documentation for more detail.

" }, { "textRaw": "`fs.lchownSync(path, uid, gid)`", "type": "method", "name": "lchownSync", "meta": { "changes": [ { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/21498", "description": "This API is no longer deprecated." }, { "version": "v0.4.7", "description": "Documentation-only deprecation." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`uid` {integer} The file's new owner's user id.", "name": "uid", "type": "integer", "desc": "The file's new owner's user id." }, { "textRaw": "`gid` {integer} The file's new group's group id.", "name": "gid", "type": "integer", "desc": "The file's new group's group id." } ] } ], "desc": "

Set the owner for the path. Returns undefined.

\n

See the POSIX lchown(2) documentation for more details.

" }, { "textRaw": "`fs.lutimesSync(path, atime, mtime)`", "type": "method", "name": "lutimesSync", "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" } ] } ], "desc": "

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().

" }, { "textRaw": "`fs.linkSync(existingPath, newPath)`", "type": "method", "name": "linkSync", "meta": { "added": [ "v0.1.31" ], "changes": [ { "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*." } ] }, "signatures": [ { "params": [ { "textRaw": "`existingPath` {string|Buffer|URL}", "name": "existingPath", "type": "string|Buffer|URL" }, { "textRaw": "`newPath` {string|Buffer|URL}", "name": "newPath", "type": "string|Buffer|URL" } ] } ], "desc": "

Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail. Returns undefined.

" }, { "textRaw": "`fs.lstatSync(path[, options])`", "type": "method", "name": "lstatSync", "meta": { "added": [ "v0.1.30" ], "changes": [ { "version": "v15.3.0", "pr-url": "https://github.com/nodejs/node/pull/33716", "description": "Accepts a `throwIfNoEntry` option to specify whether an exception should be thrown if the entry does not exist." }, { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." }, { "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": [ { "return": { "textRaw": "Returns: {fs.Stats}", "name": "return", "type": "fs.Stats" }, "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.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." }, { "textRaw": "`throwIfNoEntry` {boolean} Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`. **Default:** `true`.", "name": "throwIfNoEntry", "type": "boolean", "default": "`true`", "desc": "Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`." } ] } ] } ], "desc": "

Retrieves the <fs.Stats> for the symbolic link referred to by path.

\n

See the POSIX lstat(2) documentation for more details.

" }, { "textRaw": "`fs.mkdirSync(path[, options])`", "type": "method", "name": "mkdirSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": [ "v13.11.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31530", "description": "In `recursive` mode, the first created path is returned now." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/21875", "description": "The second argument can now be an `options` object with `recursive` and `mode` properties." }, { "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": [ { "return": { "textRaw": "Returns: {string|undefined}", "name": "return", "type": "string|undefined" }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object|integer}", "name": "options", "type": "Object|integer", "options": [ { "textRaw": "`recursive` {boolean} **Default:** `false`", "name": "recursive", "type": "boolean", "default": "`false`" }, { "textRaw": "`mode` {string|integer} Not supported on Windows. **Default:** `0o777`.", "name": "mode", "type": "string|integer", "default": "`0o777`", "desc": "Not supported on Windows." } ] } ] } ], "desc": "

Synchronously creates a directory. Returns undefined, or if recursive is\ntrue, the first directory path created.\nThis is the synchronous version of fs.mkdir().

\n

See the POSIX mkdir(2) documentation for more details.

" }, { "textRaw": "`fs.mkdtempSync(prefix[, options])`", "type": "method", "name": "mkdtempSync", "meta": { "added": [ "v5.10.0" ], "changes": [ { "version": "v16.5.0", "pr-url": "https://github.com/nodejs/node/pull/39028", "description": "The `prefix` parameter now accepts an empty string." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`prefix` {string}", "name": "prefix", "type": "string" }, { "textRaw": "`options` {string|Object}", "name": "options", "type": "string|Object", "options": [ { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" } ] } ] } ], "desc": "

Returns the created directory path.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.mkdtemp().

\n

The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.

" }, { "textRaw": "`fs.opendirSync(path[, options])`", "type": "method", "name": "opendirSync", "meta": { "added": [ "v12.12.0" ], "changes": [ { "version": [ "v13.1.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30114", "description": "The `bufferSize` option was introduced." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.Dir}", "name": "return", "type": "fs.Dir" }, "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." } ] } ] } ], "desc": "

Synchronously open a directory. See opendir(3).

\n

Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.

\n

The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.

" }, { "textRaw": "`fs.openSync(path[, flags[, mode]])`", "type": "method", "name": "openSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`flags` {string|number} **Default:** `'r'`. See [support of file system `flags`][].", "name": "flags", "type": "string|number", "default": "`'r'`. See [support of file system `flags`][]" }, { "textRaw": "`mode` {string|integer} **Default:** `0o666`", "name": "mode", "type": "string|integer", "default": "`0o666`" } ] } ], "desc": "

Returns an integer representing the file descriptor.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.open().

" }, { "textRaw": "`fs.readdirSync(path[, options])`", "type": "method", "name": "readdirSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22020", "description": "New option `withFileTypes` was added." }, { "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": [ { "return": { "textRaw": "Returns: {string[]|Buffer[]|fs.Dirent[]}", "name": "return", "type": "string[]|Buffer[]|fs.Dirent[]" }, "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'`" }, { "textRaw": "`withFileTypes` {boolean} **Default:** `false`", "name": "withFileTypes", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Reads the contents of the directory.

\n

See the POSIX readdir(3) documentation for more details.

\n

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.

\n

If options.withFileTypes is set to true, the result will contain\n<fs.Dirent> objects.

" }, { "textRaw": "`fs.readFileSync(path[, options])`", "type": "method", "name": "readFileSync", "meta": { "added": [ "v0.1.8" ], "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." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/3163", "description": "The `path` parameter can be a file descriptor now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer}", "name": "return", "type": "string|Buffer" }, "params": [ { "textRaw": "`path` {string|Buffer|URL|integer} filename or file descriptor", "name": "path", "type": "string|Buffer|URL|integer", "desc": "filename or file descriptor" }, { "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`][]." } ] } ] } ], "desc": "

Returns the contents of the path.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readFile().

\n

If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.

\n

Similar to fs.readFile(), when the path is a directory, the behavior of\nfs.readFileSync() is platform-specific.

\n
import { readFileSync } from '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])`", "type": "method", "name": "readlinkSync", "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": [ { "return": { "textRaw": "Returns: {string|Buffer}", "name": "return", "type": "string|Buffer" }, "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'`" } ] } ] } ], "desc": "

Returns the symbolic link's string value.

\n

See the POSIX readlink(2) documentation for more details.

\n

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.

" }, { "textRaw": "`fs.readSync(fd, buffer, offset, length, position)`", "type": "method", "name": "readSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4518", "description": "The `length` parameter can now be `0`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView}", "name": "buffer", "type": "Buffer|TypedArray|DataView" }, { "textRaw": "`offset` {integer}", "name": "offset", "type": "integer" }, { "textRaw": "`length` {integer}", "name": "length", "type": "integer" }, { "textRaw": "`position` {integer|bigint}", "name": "position", "type": "integer|bigint" } ] } ], "desc": "

Returns the number of bytesRead.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

" }, { "textRaw": "`fs.readSync(fd, buffer, [options])`", "type": "method", "name": "readSync", "meta": { "added": [ "v13.13.0", "v12.17.0" ], "changes": [ { "version": [ "v13.13.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32460", "description": "Options object can be passed in to make offset, length and position optional." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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`", "name": "length", "type": "integer", "default": "`buffer.byteLength`" }, { "textRaw": "`position` {integer|bigint} **Default:** `null`", "name": "position", "type": "integer|bigint", "default": "`null`" } ] } ] } ], "desc": "

Returns the number of bytesRead.

\n

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.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().

" }, { "textRaw": "`fs.readvSync(fd, buffers[, position])`", "type": "method", "name": "readvSync", "meta": { "added": [ "v13.13.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number} The number of bytes read.", "name": "return", "type": "number", "desc": "The number of bytes read." }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" } ] } ], "desc": "

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readv().

" }, { "textRaw": "`fs.realpathSync(path[, options])`", "type": "method", "name": "realpathSync", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/13028", "description": "Pipe/Socket resolve support was added." }, { "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.4.0", "pr-url": "https://github.com/nodejs/node/pull/7899", "description": "Calling `realpathSync` now works again for various edge cases on Windows." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/3594", "description": "The `cache` parameter was removed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer}", "name": "return", "type": "string|Buffer" }, "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'`" } ] } ] } ], "desc": "

Returns the resolved pathname.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.realpath().

" }, { "textRaw": "`fs.realpathSync.native(path[, options])`", "type": "method", "name": "native", "meta": { "added": [ "v9.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer}", "name": "return", "type": "string|Buffer" }, "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'`" } ] } ] } ], "desc": "

Synchronous realpath(3).

\n

Only paths that can be converted to UTF8 strings are supported.

\n

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 path returned. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.

\n

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.

" }, { "textRaw": "`fs.renameSync(oldPath, newPath)`", "type": "method", "name": "renameSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `oldPath` and `newPath` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." } ] }, "signatures": [ { "params": [ { "textRaw": "`oldPath` {string|Buffer|URL}", "name": "oldPath", "type": "string|Buffer|URL" }, { "textRaw": "`newPath` {string|Buffer|URL}", "name": "newPath", "type": "string|Buffer|URL" } ] } ], "desc": "

Renames the file from oldPath to newPath. Returns undefined.

\n

See the POSIX rename(2) documentation for more details.

" }, { "textRaw": "`fs.rmdirSync(path[, options])`", "type": "method", "name": "rmdirSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37216", "description": "Using `fs.rmdirSync(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.rmdirSync(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.rmSync` 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": "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." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js retries the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure. **Default:** `false`. **Deprecated.**", "name": "recursive", "type": "boolean", "default": "`false`. **Deprecated.**", "desc": "If `true`, perform a recursive directory removal. In recursive mode, operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." } ] } ] } ], "desc": "

Synchronous rmdir(2). Returns undefined.

\n

Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error\non Windows and an ENOTDIR error on POSIX.

\n

To get a behavior similar to the rm -rf Unix command, use fs.rmSync()\nwith options { recursive: true, force: true }.

" }, { "textRaw": "`fs.rmSync(path[, options])`", "type": "method", "name": "rmSync", "meta": { "added": [ "v14.14.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`force` {boolean} When `true`, exceptions will be ignored if `path` does not exist. **Default:** `false`.", "name": "force", "type": "boolean", "default": "`false`", "desc": "When `true`, exceptions will be ignored if `path` does not exist." }, { "textRaw": "`maxRetries` {integer} If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`. **Default:** `0`.", "name": "maxRetries", "type": "integer", "default": "`0`", "desc": "If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or `EPERM` error is encountered, Node.js will retry the operation with a linear backoff wait of `retryDelay` milliseconds longer on each try. This option represents the number of retries. This option is ignored if the `recursive` option is not `true`." }, { "textRaw": "`recursive` {boolean} If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure. **Default:** `false`.", "name": "recursive", "type": "boolean", "default": "`false`", "desc": "If `true`, perform a recursive directory removal. In recursive mode operations are retried on failure." }, { "textRaw": "`retryDelay` {integer} The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`. **Default:** `100`.", "name": "retryDelay", "type": "integer", "default": "`100`", "desc": "The amount of time in milliseconds to wait between retries. This option is ignored if the `recursive` option is not `true`." } ] } ] } ], "desc": "

Synchronously removes files and directories (modeled on the standard POSIX rm\nutility). Returns undefined.

" }, { "textRaw": "`fs.statSync(path[, options])`", "type": "method", "name": "statSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v15.3.0", "pr-url": "https://github.com/nodejs/node/pull/33716", "description": "Accepts a `throwIfNoEntry` option to specify whether an exception should be thrown if the entry does not exist." }, { "version": "v10.5.0", "pr-url": "https://github.com/nodejs/node/pull/20220", "description": "Accepts an additional `options` object to specify whether the numeric values returned should be bigint." }, { "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": [ { "return": { "textRaw": "Returns: {fs.Stats}", "name": "return", "type": "fs.Stats" }, "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.Stats} object should be `bigint`. **Default:** `false`.", "name": "bigint", "type": "boolean", "default": "`false`", "desc": "Whether the numeric values in the returned {fs.Stats} object should be `bigint`." }, { "textRaw": "`throwIfNoEntry` {boolean} Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`. **Default:** `true`.", "name": "throwIfNoEntry", "type": "boolean", "default": "`true`", "desc": "Whether an exception will be thrown if no file system entry exists, rather than returning `undefined`." } ] } ] } ], "desc": "

Retrieves the <fs.Stats> for the path.

" }, { "textRaw": "`fs.symlinkSync(target, path[, type])`", "type": "method", "name": "symlinkSync", "meta": { "added": [ "v0.1.31" ], "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23724", "description": "If the `type` argument is left undefined, Node will autodetect `target` type and automatically select `dir` or `file`." }, { "version": "v7.6.0", "pr-url": "https://github.com/nodejs/node/pull/10739", "description": "The `target` and `path` parameters can be WHATWG `URL` objects using `file:` protocol. Support is currently still *experimental*." } ] }, "signatures": [ { "params": [ { "textRaw": "`target` {string|Buffer|URL}", "name": "target", "type": "string|Buffer|URL" }, { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Returns undefined.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.symlink().

" }, { "textRaw": "`fs.truncateSync(path[, len])`", "type": "method", "name": "truncateSync", "meta": { "added": [ "v0.8.6" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer|URL}", "name": "path", "type": "string|Buffer|URL" }, { "textRaw": "`len` {integer} **Default:** `0`", "name": "len", "type": "integer", "default": "`0`" } ] } ], "desc": "

Truncates the file. Returns undefined. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync() is called.

\n

Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.

" }, { "textRaw": "`fs.unlinkSync(path)`", "type": "method", "name": "unlinkSync", "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.

" }, { "textRaw": "`fs.utimesSync(path, atime, mtime)`", "type": "method", "name": "utimesSync", "meta": { "added": [ "v0.4.2" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11919", "description": "`NaN`, `Infinity`, and `-Infinity` are no longer valid time specifiers." }, { "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": "v4.1.0", "pr-url": "https://github.com/nodejs/node/pull/2387", "description": "Numeric strings, `NaN` and `Infinity` are now allowed time specifiers." } ] }, "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" } ] } ], "desc": "

Returns undefined.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.utimes().

" }, { "textRaw": "`fs.writeFileSync(file, data[, options])`", "type": "method", "name": "writeFileSync", "meta": { "added": [ "v0.1.29" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `data` parameter will stringify an object with an explicit `toString` function." }, { "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." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `data` parameter can now be any `TypedArray` or a `DataView`." }, { "version": "v7.4.0", "pr-url": "https://github.com/nodejs/node/pull/10382", "description": "The `data` parameter can now be a `Uint8Array`." }, { "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": "`file` {string|Buffer|URL|integer} filename or file descriptor", "name": "file", "type": "string|Buffer|URL|integer", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string|Buffer|TypedArray|DataView|Object}", "name": "data", "type": "string|Buffer|TypedArray|DataView|Object" }, { "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:** `'w'`.", "name": "flag", "type": "string", "default": "`'w'`", "desc": "See [support of file system `flags`][]." } ] } ] } ], "desc": "

Returns undefined.

\n

If data is a plain object, it must have an own (not inherited) toString\nfunction property.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writeFile().

" }, { "textRaw": "`fs.writeSync(fd, buffer[, offset[, length[, position]]])`", "type": "method", "name": "writeSync", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `buffer` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `buffer` parameter won't coerce unsupported input to strings anymore." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/22150", "description": "The `buffer` parameter can now be any `TypedArray` or a `DataView`." }, { "version": "v7.4.0", "pr-url": "https://github.com/nodejs/node/pull/10382", "description": "The `buffer` parameter can now be a `Uint8Array`." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/7856", "description": "The `offset` and `length` parameters are optional now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {number} The number of bytes written.", "name": "return", "type": "number", "desc": "The number of bytes written." }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer|TypedArray|DataView|string|Object}", "name": "buffer", "type": "Buffer|TypedArray|DataView|string|Object" }, { "textRaw": "`offset` {integer}", "name": "offset", "type": "integer" }, { "textRaw": "`length` {integer}", "name": "length", "type": "integer" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" } ] } ], "desc": "

If buffer is a plain object, it must have an own (not inherited) toString\nfunction property.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).

" }, { "textRaw": "`fs.writeSync(fd, string[, position[, encoding]])`", "type": "method", "name": "writeSync", "meta": { "added": [ "v0.11.5" ], "changes": [ { "version": "v14.12.0", "pr-url": "https://github.com/nodejs/node/pull/34993", "description": "The `string` parameter will stringify an object with an explicit `toString` function." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/31030", "description": "The `string` parameter won't coerce unsupported input to strings anymore." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/7856", "description": "The `position` parameter is optional now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {number} The number of bytes written.", "name": "return", "type": "number", "desc": "The number of bytes written." }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`string` {string|Object}", "name": "string", "type": "string|Object" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" } ] } ], "desc": "

If string is a plain object, it must have an own (not inherited) toString\nfunction property.

\n

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, string...).

" }, { "textRaw": "`fs.writevSync(fd, buffers[, position])`", "type": "method", "name": "writevSync", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number} The number of bytes written.", "name": "return", "type": "number", "desc": "The number of bytes written." }, "params": [ { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" }, { "textRaw": "`buffers` {ArrayBufferView[]}", "name": "buffers", "type": "ArrayBufferView[]" }, { "textRaw": "`position` {integer}", "name": "position", "type": "integer" } ] } ], "desc": "

For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writev().

" } ], "type": "module", "displayName": "Synchronous API" }, { "textRaw": "Common Objects", "name": "common_objects", "desc": "

The common objects are shared by all of the file system API variants\n(promise, callback, and synchronous).

", "classes": [ { "textRaw": "Class: `fs.Dir`", "type": "class", "name": "fs.Dir", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "desc": "

A class representing a directory stream.

\n

Created by fs.opendir(), fs.opendirSync(), or\nfsPromises.opendir().

\n
import { opendir } from '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
\n

When using the async iterator, the <fs.Dir> object will be automatically\nclosed after the iterator exits.

", "methods": [ { "textRaw": "`dir.close()`", "type": "method", "name": "close", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [] } ], "desc": "

Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

\n

A promise is returned that will be resolved after the resource has been\nclosed.

" }, { "textRaw": "`dir.close(callback)`", "type": "method", "name": "close", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "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.

\n

The callback will be called after the resource handle has been closed.

" }, { "textRaw": "`dir.closeSync()`", "type": "method", "name": "closeSync", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Synchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.

" }, { "textRaw": "`dir.read()`", "type": "method", "name": "read", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {fs.Dirent|null}", "name": "return", "type": "Promise", "desc": "containing {fs.Dirent|null}" }, "params": [] } ], "desc": "

Asynchronously read the next directory entry via readdir(3) as an\n<fs.Dirent>.

\n

A promise is returned that will be resolved with an <fs.Dirent>, or null\nif there are no more directory entries to read.

\n

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)`", "type": "method", "name": "read", "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\n<fs.Dirent>.

\n

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.

\n

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()`", "type": "method", "name": "readSync", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.Dirent|null}", "name": "return", "type": "fs.Dirent|null" }, "params": [] } ], "desc": "

Synchronously read the next directory entry as an <fs.Dirent>. See the\nPOSIX readdir(3) documentation for more detail.

\n

If there are no more directory entries to read, null will be returned.

\n

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]()`", "type": "method", "name": "[Symbol.asyncIterator]", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator} of {fs.Dirent}", "name": "return", "type": "AsyncIterator", "desc": "of {fs.Dirent}" }, "params": [] } ], "desc": "

Asynchronously iterates over the directory until all entries have\nbeen read. Refer to the POSIX readdir(3) documentation for more detail.

\n

Entries returned by the async iterator are always an <fs.Dirent>.\nThe null case from dir.read() is handled internally.

\n

See <fs.Dir> for an example.

\n

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.

" } ], "properties": [ { "textRaw": "`path` {string}", "type": "string", "name": "path", "meta": { "added": [ "v12.12.0" ], "changes": [] }, "desc": "

The read-only path of this directory as was provided to fs.opendir(),\nfs.opendirSync(), or fsPromises.opendir().

" } ] }, { "textRaw": "Class: `fs.Dirent`", "type": "class", "name": "fs.Dirent", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "desc": "

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.

\n

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.

", "methods": [ { "textRaw": "`dirent.isBlockDevice()`", "type": "method", "name": "isBlockDevice", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a block device.

" }, { "textRaw": "`dirent.isCharacterDevice()`", "type": "method", "name": "isCharacterDevice", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a character device.

" }, { "textRaw": "`dirent.isDirectory()`", "type": "method", "name": "isDirectory", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a file system\ndirectory.

" }, { "textRaw": "`dirent.isFIFO()`", "type": "method", "name": "isFIFO", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a first-in-first-out\n(FIFO) pipe.

" }, { "textRaw": "`dirent.isFile()`", "type": "method", "name": "isFile", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a regular file.

" }, { "textRaw": "`dirent.isSocket()`", "type": "method", "name": "isSocket", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a socket.

" }, { "textRaw": "`dirent.isSymbolicLink()`", "type": "method", "name": "isSymbolicLink", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Dirent> object describes a symbolic link.

" } ], "properties": [ { "textRaw": "`name` {string|Buffer}", "type": "string|Buffer", "name": "name", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "desc": "

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().

" } ] }, { "textRaw": "Class: `fs.FSWatcher`", "type": "class", "name": "fs.FSWatcher", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "\n

A successful call to fs.watch() method will return a new <fs.FSWatcher>\nobject.

\n

All <fs.FSWatcher> objects emit a 'change' event whenever a specific watched\nfile is modified.

", "events": [ { "textRaw": "Event: `'change'`", "type": "event", "name": "change", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "params": [ { "textRaw": "`eventType` {string} The type of change event that has occurred", "name": "eventType", "type": "string", "desc": "The type of change event that has occurred" }, { "textRaw": "`filename` {string|Buffer} The filename that changed (if relevant/available)", "name": "filename", "type": "string|Buffer", "desc": "The filename that changed (if relevant/available)" } ], "desc": "

Emitted when something changes in a watched directory or file.\nSee more details in fs.watch().

\n

The filename argument may not be provided depending on operating system\nsupport. If filename is provided, it will be provided as a <Buffer> if\nfs.watch() is called with its encoding option set to 'buffer', otherwise\nfilename will be a UTF-8 string.

\n
import { watch } from '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'`", "type": "event", "name": "close", "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.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "

Emitted when an error occurs while watching the file. The errored\n<fs.FSWatcher> object is no longer usable in the event handler.

" } ], "methods": [ { "textRaw": "`watcher.close()`", "type": "method", "name": "close", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the\n<fs.FSWatcher> object is no longer usable.

" }, { "textRaw": "`watcher.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v14.3.0", "v12.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.FSWatcher}", "name": "return", "type": "fs.FSWatcher" }, "params": [] } ], "desc": "

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.

\n

By default, all <fs.FSWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

" }, { "textRaw": "`watcher.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v14.3.0", "v12.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.FSWatcher}", "name": "return", "type": "fs.FSWatcher" }, "params": [] } ], "desc": "

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.

" } ] }, { "textRaw": "Class: `fs.StatWatcher`", "type": "class", "name": "fs.StatWatcher", "meta": { "added": [ "v14.3.0", "v12.20.0" ], "changes": [] }, "desc": "\n

A successful call to fs.watchFile() method will return a new <fs.StatWatcher>\nobject.

", "methods": [ { "textRaw": "`watcher.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v14.3.0", "v12.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.StatWatcher}", "name": "return", "type": "fs.StatWatcher" }, "params": [] } ], "desc": "

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.

\n

By default, all <fs.StatWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.

" }, { "textRaw": "`watcher.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v14.3.0", "v12.20.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {fs.StatWatcher}", "name": "return", "type": "fs.StatWatcher" }, "params": [] } ], "desc": "

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.

" } ] }, { "textRaw": "Class: `fs.ReadStream`", "type": "class", "name": "fs.ReadStream", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "desc": "\n

Instances of <fs.ReadStream> are created and returned using the\nfs.createReadStream() function.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "params": [], "desc": "

Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.

" }, { "textRaw": "Event: `'open'`", "type": "event", "name": "open", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "params": [ { "textRaw": "`fd` {integer} Integer file descriptor used by the {fs.ReadStream}.", "name": "fd", "type": "integer", "desc": "Integer file descriptor used by the {fs.ReadStream}." } ], "desc": "

Emitted when the <fs.ReadStream>'s file descriptor has been opened.

" }, { "textRaw": "Event: `'ready'`", "type": "event", "name": "ready", "meta": { "added": [ "v9.11.0" ], "changes": [] }, "params": [], "desc": "

Emitted when the <fs.ReadStream> is ready to be used.

\n

Fires immediately after 'open'.

" } ], "properties": [ { "textRaw": "`bytesRead` {number}", "type": "number", "name": "bytesRead", "meta": { "added": [ "v6.4.0" ], "changes": [] }, "desc": "

The number of bytes that have been read so far.

" }, { "textRaw": "`path` {string|Buffer}", "type": "string|Buffer", "name": "path", "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\nreadStream.path will be a <Buffer>.

" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v11.2.0", "v10.16.0" ], "changes": [] }, "desc": "

This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

" } ] }, { "textRaw": "Class: `fs.Stats`", "type": "class", "name": "fs.Stats", "meta": { "added": [ "v0.1.21" ], "changes": [ { "version": "v8.1.0", "pr-url": "https://github.com/nodejs/node/pull/13173", "description": "Added times as numbers." } ] }, "desc": "

A <fs.Stats> object provides information about a file.

\n

Objects returned from fs.stat(), fs.lstat() and 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.

\n
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
\n

bigint version:

\n
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()`", "type": "method", "name": "isBlockDevice", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a block device.

" }, { "textRaw": "`stats.isCharacterDevice()`", "type": "method", "name": "isCharacterDevice", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a character device.

" }, { "textRaw": "`stats.isDirectory()`", "type": "method", "name": "isDirectory", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a file system directory.

\n

If the <fs.Stats> object was obtained from fs.lstat(), this method will\nalways return false. This is because fs.lstat() returns information\nabout a symbolic link itself and not the path it resolves to.

" }, { "textRaw": "`stats.isFIFO()`", "type": "method", "name": "isFIFO", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a first-in-first-out (FIFO)\npipe.

" }, { "textRaw": "`stats.isFile()`", "type": "method", "name": "isFile", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a regular file.

" }, { "textRaw": "`stats.isSocket()`", "type": "method", "name": "isSocket", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a socket.

" }, { "textRaw": "`stats.isSymbolicLink()`", "type": "method", "name": "isSymbolicLink", "meta": { "added": [ "v0.1.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Returns true if the <fs.Stats> object describes a symbolic link.

\n

This method is only valid when using fs.lstat().

" } ], "properties": [ { "textRaw": "`dev` {number|bigint}", "type": "number|bigint", "name": "dev", "desc": "

The numeric identifier of the device containing the file.

" }, { "textRaw": "`ino` {number|bigint}", "type": "number|bigint", "name": "ino", "desc": "

The file system specific \"Inode\" number for the file.

" }, { "textRaw": "`mode` {number|bigint}", "type": "number|bigint", "name": "mode", "desc": "

A bit-field describing the file type and mode.

" }, { "textRaw": "`nlink` {number|bigint}", "type": "number|bigint", "name": "nlink", "desc": "

The number of hard-links that exist for the file.

" }, { "textRaw": "`uid` {number|bigint}", "type": "number|bigint", "name": "uid", "desc": "

The numeric user identifier of the user that owns the file (POSIX).

" }, { "textRaw": "`gid` {number|bigint}", "type": "number|bigint", "name": "gid", "desc": "

The numeric group identifier of the group that owns the file (POSIX).

" }, { "textRaw": "`rdev` {number|bigint}", "type": "number|bigint", "name": "rdev", "desc": "

A numeric device identifier if the file represents a device.

" }, { "textRaw": "`size` {number|bigint}", "type": "number|bigint", "name": "size", "desc": "

The size of the file in bytes.

" }, { "textRaw": "`blksize` {number|bigint}", "type": "number|bigint", "name": "blksize", "desc": "

The file system block size for i/o operations.

" }, { "textRaw": "`blocks` {number|bigint}", "type": "number|bigint", "name": "blocks", "desc": "

The number of blocks allocated for this file.

" }, { "textRaw": "`atimeMs` {number|bigint}", "type": "number|bigint", "name": "atimeMs", "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": "`mtimeMs` {number|bigint}", "type": "number|bigint", "name": "mtimeMs", "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": "`ctimeMs` {number|bigint}", "type": "number|bigint", "name": "ctimeMs", "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": "`birthtimeMs` {number|bigint}", "type": "number|bigint", "name": "birthtimeMs", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "desc": "

The timestamp indicating the creation time of this file expressed in\nmilliseconds since the POSIX Epoch.

" }, { "textRaw": "`atimeNs` {bigint}", "type": "bigint", "name": "atimeNs", "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.

" }, { "textRaw": "`mtimeNs` {bigint}", "type": "bigint", "name": "mtimeNs", "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 modified expressed in\nnanoseconds since the POSIX Epoch.

" }, { "textRaw": "`ctimeNs` {bigint}", "type": "bigint", "name": "ctimeNs", "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 the file status was changed expressed\nin nanoseconds since the POSIX Epoch.

" }, { "textRaw": "`birthtimeNs` {bigint}", "type": "bigint", "name": "birthtimeNs", "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 creation time of this file expressed in\nnanoseconds since the POSIX Epoch.

" }, { "textRaw": "`atime` {Date}", "type": "Date", "name": "atime", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "

The timestamp indicating the last time this file was accessed.

" }, { "textRaw": "`mtime` {Date}", "type": "Date", "name": "mtime", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "

The timestamp indicating the last time this file was modified.

" }, { "textRaw": "`ctime` {Date}", "type": "Date", "name": "ctime", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "desc": "

The timestamp indicating the last time the file status was changed.

" }, { "textRaw": "`birthtime` {Date}", "type": "Date", "name": "birthtime", "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", "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.

\n

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.

\n

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.

\n

The times in the stat object have the following semantics:

\n
    \n
  • atime \"Access Time\": Time when file data last accessed. Changed\nby the mknod(2), utimes(2), and read(2) system calls.
  • \n
  • mtime \"Modified Time\": Time when file data last modified.\nChanged by the mknod(2), utimes(2), and write(2) system calls.
  • \n
  • 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.
  • \n
  • birthtime \"Birth Time\": Time of file creation. Set once when the\nfile is created. On filesystems 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.
  • \n
\n

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.

", "type": "module", "displayName": "Stat time values" } ] }, { "textRaw": "Class: `fs.WriteStream`", "type": "class", "name": "fs.WriteStream", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "desc": "\n

Instances of <fs.WriteStream> are created and returned using the\nfs.createWriteStream() function.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "params": [], "desc": "

Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.

" }, { "textRaw": "Event: `'open'`", "type": "event", "name": "open", "meta": { "added": [ "v0.1.93" ], "changes": [] }, "params": [ { "textRaw": "`fd` {integer} Integer file descriptor used by the {fs.WriteStream}.", "name": "fd", "type": "integer", "desc": "Integer file descriptor used by the {fs.WriteStream}." } ], "desc": "

Emitted when the <fs.WriteStream>'s file is opened.

" }, { "textRaw": "Event: `'ready'`", "type": "event", "name": "ready", "meta": { "added": [ "v9.11.0" ], "changes": [] }, "params": [], "desc": "

Emitted when the <fs.WriteStream> is ready to be used.

\n

Fires immediately after 'open'.

" } ], "properties": [ { "textRaw": "`writeStream.bytesWritten`", "name": "bytesWritten", "meta": { "added": [ "v0.4.7" ], "changes": [] }, "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.

" }, { "textRaw": "`writeStream.path`", "name": "path", "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\nwriteStream.path will be a <Buffer>.

" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v11.2.0" ], "changes": [] }, "desc": "

This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.

" } ], "methods": [ { "textRaw": "`writeStream.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ] } ] } ], "desc": "

Closes writeStream. Optionally accepts a\ncallback that will be executed once the writeStream\nis closed.

" } ] } ], "properties": [ { "textRaw": "`constants` {Object}", "type": "Object", "name": "constants", "desc": "

Returns an object containing commonly used constants for file system\noperations.

", "modules": [ { "textRaw": "FS constants", "name": "fs_constants", "desc": "

The following constants are exported by fs.constants.

\n

Not every constant will be available on every operating system.

\n

To use more than one constant, use the bitwise OR | operator.

\n

Example:

\n
import { open, constants } from '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", "desc": "

The following constants are meant for use with fs.access().

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
F_OKFlag 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_OKFlag indicating that the file can be read by the calling process.
W_OKFlag indicating that the file can be written by the calling\n process.
X_OKFlag 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).
", "type": "module", "displayName": "File access constants" }, { "textRaw": "File copy constants", "name": "file_copy_constants", "desc": "

The following constants are meant for use with fs.copyFile().

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
COPYFILE_EXCLIf present, the copy operation will fail with an error if the\n destination path already exists.
COPYFILE_FICLONEIf 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_FORCEIf 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.
", "type": "module", "displayName": "File copy constants" }, { "textRaw": "File open constants", "name": "file_open_constants", "desc": "

The following constants are meant for use with fs.open().

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
O_RDONLYFlag indicating to open a file for read-only access.
O_WRONLYFlag indicating to open a file for write-only access.
O_RDWRFlag indicating to open a file for read-write access.
O_CREATFlag indicating to create the file if it does not already exist.
O_EXCLFlag indicating that opening a file should fail if the\n O_CREAT flag is set and the file already exists.
O_NOCTTYFlag 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_TRUNCFlag 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_APPENDFlag indicating that data will be appended to the end of the file.
O_DIRECTORYFlag indicating that the open should fail if the path is not a\n directory.
O_NOATIMEFlag 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_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic\n link.
O_SYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for file integrity.
O_DSYNCFlag indicating that the file is opened for synchronized I/O with write\n operations waiting for data integrity.
O_SYMLINKFlag indicating to open the symbolic link itself rather than the\n resource it is pointing to.
O_DIRECTWhen set, an attempt will be made to minimize caching effects of file\n I/O.
O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
UV_FS_O_FILEMAPWhen 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.
", "type": "module", "displayName": "File open constants" }, { "textRaw": "File type constants", "name": "file_type_constants", "desc": "

The following constants are meant for use with the <fs.Stats> object's\nmode property for determining a file's type.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
S_IFMTBit mask used to extract the file type code.
S_IFREGFile type constant for a regular file.
S_IFDIRFile type constant for a directory.
S_IFCHRFile type constant for a character-oriented device file.
S_IFBLKFile type constant for a block-oriented device file.
S_IFIFOFile type constant for a FIFO/pipe.
S_IFLNKFile type constant for a symbolic link.
S_IFSOCKFile type constant for a socket.
", "type": "module", "displayName": "File type constants" }, { "textRaw": "File mode constants", "name": "file_mode_constants", "desc": "

The following constants are meant for use with the <fs.Stats> object's\nmode property for determining the access permissions for a file.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
S_IRWXUFile mode indicating readable, writable, and executable by owner.
S_IRUSRFile mode indicating readable by owner.
S_IWUSRFile mode indicating writable by owner.
S_IXUSRFile mode indicating executable by owner.
S_IRWXGFile mode indicating readable, writable, and executable by group.
S_IRGRPFile mode indicating readable by group.
S_IWGRPFile mode indicating writable by group.
S_IXGRPFile mode indicating executable by group.
S_IRWXOFile mode indicating readable, writable, and executable by others.
S_IROTHFile mode indicating readable by others.
S_IWOTHFile mode indicating writable by others.
S_IXOTHFile mode indicating executable by others.
", "type": "module", "displayName": "File mode constants" } ], "type": "module", "displayName": "FS constants" } ] } ], "type": "module", "displayName": "Common Objects" }, { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Ordering of callback and promise-based operations", "name": "ordering_of_callback_and_promise-based_operations", "desc": "

Because they are executed asynchronously by the underlying thread pool,\nthere is no guaranteed ordering when using either the callback or\npromise-based methods.

\n

For example, the following is prone to error because the fs.stat()\noperation might complete before the fs.rename() operation:

\n
fs.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
\n

It is important to correctly order the operations by awaiting the results\nof one before invoking the other:

\n
import { rename, stat } from 'fs/promises';\n\nconst from = '/tmp/hello';\nconst to = '/tmp/world';\n\ntry {\n  await rename(from, to);\n  const stats = await stat(to);\n  console.log(`stats: ${JSON.stringify(stats)}`);\n} catch (error) {\n  console.error('there was an error:', error.message);\n}\n
\n
const { rename, stat } = require('fs/promises');\n\n(async function(from, to) {\n  try {\n    await rename(from, to);\n    const stats = await stat(to);\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
\n

Or, when using the callback APIs, move the fs.stat() call into the callback\nof the fs.rename() operation:

\n
import { rename, stat } from '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
\n
const { rename, stat } = require('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
", "type": "module", "displayName": "Ordering of callback and promise-based operations" }, { "textRaw": "File paths", "name": "file_paths", "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.

", "modules": [ { "textRaw": "String paths", "name": "string_paths", "desc": "

String form 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().

\n

Example using an absolute path on POSIX:

\n
import { open } from '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
\n

Example using a relative path on POSIX (relative to process.cwd()):

\n
import { open } from '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
", "type": "module", "displayName": "String paths" }, { "textRaw": "File URL paths", "name": "file_url_paths", "meta": { "added": [ "v7.6.0" ], "changes": [] }, "desc": "

For most fs module functions, the path or filename argument may be passed\nas a <URL> object using the file: protocol.

\n
import { readFileSync } from 'fs';\n\nreadFileSync(new URL('file:///tmp/hello'));\n
\n

file: URLs are always absolute paths.

", "modules": [ { "textRaw": "Platform-specific considerations", "name": "platform-specific_considerations", "desc": "

On Windows, file: <URL>s with a host name convert to UNC paths, while file:\n<URL>s with drive letters convert to local absolute paths. file: <URL>s\nwithout a host name nor a drive letter will result in an error:

\n
import { readFileSync } from '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
\n

file: <URL>s with drive letters must use : as a separator just after\nthe drive letter. Using another separator will result in an error.

\n

On all other platforms, file: <URL>s with a host name are unsupported and\nwill result in an error:

\n
import { readFileSync } from '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
\n

A file: <URL> having encoded slash characters will result in an error on all\nplatforms:

\n
import { readFileSync } from '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
\n

On Windows, file: <URL>s having encoded backslash will result in an error:

\n
import { readFileSync } from '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
", "type": "module", "displayName": "Platform-specific considerations" } ], "type": "module", "displayName": "File URL paths" }, { "textRaw": "Buffer paths", "name": "buffer_paths", "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:

\n

Example using an absolute path on POSIX:

\n
import { open } from 'fs/promises';\nimport { Buffer } from '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
", "type": "module", "displayName": "Buffer paths" }, { "textRaw": "Per-drive working directories on Windows", "name": "per-drive_working_directories_on_windows", "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.

", "type": "module", "displayName": "Per-drive working directories on Windows" } ], "type": "module", "displayName": "File paths" }, { "textRaw": "File descriptors", "name": "file_descriptors", "desc": "

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.

\n

The 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.

\n

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.

\n
import { open, close, fstat } from '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
\n

The 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:

\n
import { open } from '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
", "type": "module", "displayName": "File descriptors" }, { "textRaw": "Threadpool usage", "name": "threadpool_usage", "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.

", "type": "module", "displayName": "Threadpool usage" }, { "textRaw": "File system flags", "name": "file_system_flags", "desc": "

The following flags are available wherever the flag option takes a\nstring.

\n
    \n
  • \n

    'a': Open file for appending.\nThe file is created if it does not exist.

    \n
  • \n
  • \n

    'ax': Like 'a' but fails if the path exists.

    \n
  • \n
  • \n

    'a+': Open file for reading and appending.\nThe file is created if it does not exist.

    \n
  • \n
  • \n

    'ax+': Like 'a+' but fails if the path exists.

    \n
  • \n
  • \n

    'as': Open file for appending in synchronous mode.\nThe file is created if it does not exist.

    \n
  • \n
  • \n

    'as+': Open file for reading and appending in synchronous mode.\nThe file is created if it does not exist.

    \n
  • \n
  • \n

    'r': Open file for reading.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • \n

    'r+': Open file for reading and writing.\nAn exception occurs if the file does not exist.

    \n
  • \n
  • \n

    'rs+': Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.

    \n

    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.

    \n

    This 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.

    \n
  • \n
  • \n

    'w': Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • \n

    'wx': Like 'w' but fails if the path exists.

    \n
  • \n
  • \n

    'w+': Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).

    \n
  • \n
  • \n

    'wx+': Like 'w+' but fails if the path exists.

    \n
  • \n
\n

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.

\n

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.

\n

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.

\n

Modifying a file rather than replacing it may require the flag option to be\nset to 'r+' rather than the default 'w'.

\n

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.

\n
// 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
\n

On Windows, opening an existing hidden file using the 'w' flag (either\nthrough fs.open() or fs.writeFile() or fsPromises.open()) will fail with\nEPERM. Existing hidden files can be opened for writing with the 'r+' flag.

\n

A call to fs.ftruncate() or filehandle.truncate() can be used to reset\nthe file contents.

", "type": "module", "displayName": "File system flags" } ], "type": "module", "displayName": "Notes" } ], "type": "module", "displayName": "fs", "source": "doc/api/fs.md" }, { "textRaw": "HTTP", "name": "http", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/http.js

\n

To use the HTTP server and client one must require('http').

\n

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.

\n

HTTP message headers are represented by an object like this:

\n\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'host': 'mysite.com',\n  'accept': '*/*' }\n
\n

Keys are lowercased. Values are not modified.

\n

In 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.

\n

See message.headers for details on how duplicate headers are handled.

\n

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:

\n\n
[ 'ConTent-Length', '123456',\n  'content-LENGTH', '123',\n  'content-type', 'text/plain',\n  'CONNECTION', 'keep-alive',\n  'Host', 'mysite.com',\n  'accepT', '*/*' ]\n
", "classes": [ { "textRaw": "Class: `http.Agent`", "type": "class", "name": "http.Agent", "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.

\n

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.

\n

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()).

\n

It is good practice, to destroy() an Agent instance when it is no\nlonger in use, because unused sockets consume OS resources.

\n

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:

\n
http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});\n
\n

An 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.

\n

agent:false:

\n
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
", "methods": [ { "textRaw": "`agent.createConnection(options[, callback])`", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Duplex}", "name": "return", "type": "stream.Duplex" }, "params": [ { "textRaw": "`options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options", "name": "options", "type": "Object", "desc": "Options containing connection details. Check [`net.createConnection()`][] for the format of the options" }, { "textRaw": "`callback` {Function} Callback function that receives the created socket", "name": "callback", "type": "Function", "desc": "Callback function that receives the created socket" } ] } ], "desc": "

Produces a socket/stream to be used for HTTP requests.

\n

By default, this function is the same as net.createConnection(). However,\ncustom agents may override this method in case greater flexibility is desired.

\n

A socket/stream can be supplied in one of two ways: by returning the\nsocket/stream from this function, or by passing the socket/stream to callback.

\n

This method is guaranteed to return an instance of the <net.Socket> class,\na subclass of <stream.Duplex>, unless the user specifies a socket\ntype other than <net.Socket>.

\n

callback has a signature of (err, stream).

" }, { "textRaw": "`agent.keepSocketAlive(socket)`", "type": "method", "name": "keepSocketAlive", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ] } ], "desc": "

Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:

\n
socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n
\n

This 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.

\n

The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

" }, { "textRaw": "`agent.reuseSocket(socket, request)`", "type": "method", "name": "reuseSocket", "meta": { "added": [ "v8.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" }, { "textRaw": "`request` {http.ClientRequest}", "name": "request", "type": "http.ClientRequest" } ] } ], "desc": "

Called when socket is attached to request after being persisted because of\nthe keep-alive options. Default behavior is to:

\n
socket.ref();\n
\n

This method can be overridden by a particular Agent subclass.

\n

The socket argument can be an instance of <net.Socket>, a subclass of\n<stream.Duplex>.

" }, { "textRaw": "`agent.destroy()`", "type": "method", "name": "destroy", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Destroy any sockets that are currently in use by the agent.

\n

It 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.

" }, { "textRaw": "`agent.getName(options)`", "type": "method", "name": "getName", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`options` {Object} A set of options providing information for name generation", "name": "options", "type": "Object", "desc": "A set of options providing information for name generation", "options": [ { "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to", "name": "host", "type": "string", "desc": "A domain name or IP address of the server to issue the request to" }, { "textRaw": "`port` {number} Port of remote server", "name": "port", "type": "number", "desc": "Port of remote server" }, { "textRaw": "`localAddress` {string} Local interface to bind for network connections when issuing the request", "name": "localAddress", "type": "string", "desc": "Local interface to bind for network connections when issuing the request" }, { "textRaw": "`family` {integer} Must be 4 or 6 if this doesn't equal `undefined`.", "name": "family", "type": "integer", "desc": "Must be 4 or 6 if this doesn't equal `undefined`." } ] } ] } ], "desc": "

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.

" } ], "properties": [ { "textRaw": "`freeSockets` {Object}", "type": "Object", "name": "freeSockets", "meta": { "added": [ "v0.11.4" ], "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 awaiting use by\nthe agent when keepAlive is enabled. Do not modify.

\n

Sockets in the freeSockets list will be automatically destroyed and\nremoved from the array on 'timeout'.

" }, { "textRaw": "`maxFreeSockets` {number}", "type": "number", "name": "maxFreeSockets", "meta": { "added": [ "v0.11.7" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`maxSockets` {number}", "type": "number", "name": "maxSockets", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "desc": "

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().

" }, { "textRaw": "`maxTotalSockets` {number}", "type": "number", "name": "maxTotalSockets", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "

By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open. Unlike maxSockets, this parameter applies across all origins.

" }, { "textRaw": "`requests` {Object}", "type": "Object", "name": "requests", "meta": { "added": [ "v0.5.9" ], "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 queues of requests that have not yet been assigned to\nsockets. Do not modify.

" }, { "textRaw": "`sockets` {Object}", "type": "Object", "name": "sockets", "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.

" } ], "signatures": [ { "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](net.md#net_socket_setkeepalive_enable_initialdelay) 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](net.md#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`." }, { "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 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 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." } ] } ], "desc": "

options in socket.connect() are also supported.

\n

The default http.globalAgent that is used by http.request() has all\nof these values set to their respective defaults.

\n

To configure any of them, a custom http.Agent instance must be created.

\n
const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
" } ] }, { "textRaw": "Class: `http.ClientRequest`", "type": "class", "name": "http.ClientRequest", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "\n

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().

\n

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.

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.

\n

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.

\n

For backward compatibility, res will only emit 'error' if there is an\n'error' listener registered.

\n

Node.js does not check whether Content-Length and the length of the\nbody which has been transmitted are equal or not.

", "events": [ { "textRaw": "Event: `'abort'`", "type": "event", "name": "abort", "meta": { "added": [ "v1.4.1" ], "changes": [] }, "params": [], "desc": "

Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().

" }, { "textRaw": "Event: `'connect'`", "type": "event", "name": "connect", "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.

\n

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>.

\n

A client and server pair demonstrating how to listen for the 'connect' event:

\n
const http = require('http');\nconst net = require('net');\nconst { URL } = require('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'`", "type": "event", "name": "continue", "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: `'information'`", "type": "event", "name": "information", "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.

\n
const http = require('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
\n

101 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.

" }, { "textRaw": "Event: `'response'`", "type": "event", "name": "response", "meta": { "added": [ "v0.1.0" ], "changes": [] }, "params": [ { "textRaw": "`response` {http.IncomingMessage}", "name": "response", "type": "http.IncomingMessage" } ], "desc": "

Emitted when a response is received to this request. This event is emitted only\nonce.

" }, { "textRaw": "Event: `'socket'`", "type": "event", "name": "socket", "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>.

" }, { "textRaw": "Event: `'timeout'`", "type": "event", "name": "timeout", "meta": { "added": [ "v0.7.8" ], "changes": [] }, "params": [], "desc": "

Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be aborted manually.

\n

See also: request.setTimeout().

" }, { "textRaw": "Event: `'upgrade'`", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ], "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 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.

\n

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>.

\n

A client server pair demonstrating how to listen for the 'upgrade' event.

\n
const http = require('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()`", "type": "method", "name": "abort", "meta": { "added": [ "v0.3.8" ], "deprecated": [ "v14.1.0", "v13.14.0" ], "changes": [] }, "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.end([data[, encoding]][, callback])`", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `ClientRequest`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`data` {string|Buffer}", "name": "data", "type": "string|Buffer" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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'.

\n

If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end(callback).

\n

If callback is specified, it will be called when the request stream\nis finished.

" }, { "textRaw": "`request.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": "v14.5.0", "pr-url": "https://github.com/nodejs/node/pull/32789", "description": "The function returns `this` for consistency with other Readable streams." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error} Optional, an error to emit with `'error'` event.", "name": "error", "type": "Error", "desc": "Optional, an error to emit with `'error'` event." } ] } ], "desc": "

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.

\n

See writable.destroy() for further details.

", "properties": [ { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v14.1.0", "v13.14.0" ], "changes": [] }, "desc": "

Is true after request.destroy() has been called.

\n

See writable.destroyed for further details.

" } ] }, { "textRaw": "`request.flushHeaders()`", "type": "method", "name": "flushHeaders", "meta": { "added": [ "v1.6.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Flushes the request headers.

\n

For 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.

\n

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.

" }, { "textRaw": "`request.getHeader(name)`", "type": "method", "name": "getHeader", "meta": { "added": [ "v1.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

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().

\n
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.getRawHeaderNames()`", "type": "method", "name": "getRawHeaderNames", "meta": { "added": [ "v15.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array containing the unique names of the current outgoing raw\nheaders. Header names are returned with their exact casing being set.

\n
request.setHeader('Foo', 'bar');\nrequest.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = request.getRawHeaderNames();\n// headerNames === ['Foo', 'Set-Cookie']\n
" }, { "textRaw": "`request.removeHeader(name)`", "type": "method", "name": "removeHeader", "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.

\n
request.removeHeader('Content-Type');\n
" }, { "textRaw": "`request.setHeader(name, value)`", "type": "method", "name": "setHeader", "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.

\n
request.setHeader('Content-Type', 'application/json');\n
\n

or

\n
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);\n
" }, { "textRaw": "`request.setNoDelay([noDelay])`", "type": "method", "name": "setNoDelay", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`noDelay` {boolean}", "name": "noDelay", "type": "boolean" } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.

" }, { "textRaw": "`request.setSocketKeepAlive([enable][, initialDelay])`", "type": "method", "name": "setSocketKeepAlive", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`enable` {boolean}", "name": "enable", "type": "boolean" }, { "textRaw": "`initialDelay` {number}", "name": "initialDelay", "type": "number" } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.

" }, { "textRaw": "`request.setTimeout(timeout[, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/8895", "description": "Consistently set socket timeout only when the socket connects." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "params": [ { "textRaw": "`timeout` {number} Milliseconds before a request times out.", "name": "timeout", "type": "number", "desc": "Milliseconds before a request times out." }, { "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." } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.

" }, { "textRaw": "`request.write(chunk[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`chunk` {string|Buffer}", "name": "chunk", "type": "string|Buffer" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.

\n

The callback argument is optional and will be called when this chunk of data\nis flushed, but only if the chunk is non-empty.

\n

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.

\n

When write function is called with empty string or buffer, it does\nnothing and waits for more input.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/20230", "description": "The `aborted` property is no longer a timestamp number." } ] }, "desc": "

The request.aborted property will be true if the request has\nbeen aborted.

" }, { "textRaw": "`connection` {stream.Duplex}", "type": "stream.Duplex", "name": "connection", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v13.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`request.socket`][].", "desc": "

See request.socket.

" }, { "textRaw": "`finished` {boolean}", "type": "boolean", "name": "finished", "meta": { "added": [ "v0.0.1" ], "deprecated": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`request.writableEnded`][].", "desc": "

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().

" }, { "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", "type": "number", "name": "maxHeadersCount", "default": "`2000`", "desc": "

Limits maximum response headers count. If set to 0, no limit will be applied.

" }, { "textRaw": "`path` {string} The request path.", "type": "string", "name": "path", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "The request path." }, { "textRaw": "`method` {string} The request method.", "type": "string", "name": "method", "meta": { "added": [ "v0.1.97" ], "changes": [] }, "desc": "The request method." }, { "textRaw": "`host` {string} The request host.", "type": "string", "name": "host", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request host." }, { "textRaw": "`protocol` {string} The request protocol.", "type": "string", "name": "protocol", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request protocol." }, { "textRaw": "`reusedSocket` {boolean} Whether the request is send through a reused socket.", "type": "boolean", "name": "reusedSocket", "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.

\n
const http = require('http');\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
\n

By marking a request whether it reused socket or not, we can do\nautomatic error retry base on it.

\n
const http = require('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": "`socket` {stream.Duplex}", "type": "stream.Duplex", "name": "socket", "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.

\n
const http = require('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
\n

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>.

" }, { "textRaw": "`writableEnded` {boolean}", "type": "boolean", "name": "writableEnded", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`writableFinished` {boolean}", "type": "boolean", "name": "writableFinished", "meta": { "added": [ "v12.7.0" ], "changes": [] }, "desc": "

Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

" } ] }, { "textRaw": "Class: `http.Server`", "type": "class", "name": "http.Server", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "", "events": [ { "textRaw": "Event: `'checkContinue'`", "type": "event", "name": "checkContinue", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" } ], "desc": "

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.

\n

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'checkExpectation'`", "type": "event", "name": "checkExpectation", "meta": { "added": [ "v5.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" } ], "desc": "

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'clientError'`", "type": "event", "name": "clientError", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/25605", "description": "The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs." }, { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/17672", "description": "The `rawPacket` is the current buffer that just parsed. Adding this buffer to the error object of `'clientError'` event is to make it possible that developers can log the broken packet." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4557", "description": "The default action of calling `.destroy()` on the `socket` will no longer take place if there are listeners attached for `'clientError'`." } ] }, "params": [ { "textRaw": "`exception` {Error}", "name": "exception", "type": "Error" }, { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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>.

\n

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 has already\nwritten data it is immediately destroyed.

\n

socket is the net.Socket object that the error originated from.

\n
const http = require('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
\n

When 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.

\n

err is an instance of Error with two extra columns:

\n
    \n
  • bytesParsed: the bytes count of request packet that Node.js may have parsed\ncorrectly;
  • \n
  • rawPacket: the raw packet of current request.
  • \n
\n

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.

\n
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'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.4" ], "changes": [] }, "params": [], "desc": "

Emitted when the server closes.

" }, { "textRaw": "Event: `'connect'`", "type": "event", "name": "connect", "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.

\n

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>.

\n

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.

" }, { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.0" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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.

\n

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).

\n

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>.

" }, { "textRaw": "Event: `'request'`", "type": "event", "name": "request", "meta": { "added": [ "v0.1.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http.IncomingMessage}", "name": "request", "type": "http.IncomingMessage" }, { "textRaw": "`response` {http.ServerResponse}", "name": "response", "type": "http.ServerResponse" } ], "desc": "

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'`", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ], "changes": [ { "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 requests an HTTP upgrade. Listening to this event\nis optional and clients cannot insist on a protocol change.

\n

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.

\n

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>.

" } ], "methods": [ { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Stops the server from accepting new connections. See net.Server.close().

" }, { "textRaw": "`server.listen()`", "type": "method", "name": "listen", "signatures": [ { "params": [] } ], "desc": "

Starts the HTTP server listening for connections.\nThis method is identical to server.listen() from net.Server.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ], "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)." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.Server}", "name": "return", "type": "http.Server" }, "params": [ { "textRaw": "`msecs` {number} **Default:** 0 (no timeout)", "name": "msecs", "type": "number", "default": "0 (no timeout)" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.

\n

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.

" } ], "properties": [ { "textRaw": "`headersTimeout` {number} **Default:** `60000`", "type": "number", "name": "headersTimeout", "meta": { "added": [ "v11.3.0", "v10.14.0" ], "changes": [] }, "default": "`60000`", "desc": "

Limit the amount of time the parser will wait to receive the complete HTTP\nheaders.

\n

In case of inactivity, the rules defined in server.timeout apply. However,\nthat inactivity based timeout would still allow the connection to be kept open\nif the headers are being sent very slowly (by default, up to a byte per 2\nminutes). In order to prevent this, whenever header data arrives an additional\ncheck is made that more than server.headersTimeout milliseconds has not\npassed since the connection was established. If the check fails, a 'timeout'\nevent is emitted on the server object, and (by default) the socket is destroyed.\nSee server.timeout for more information on how timeout behavior can be\ncustomized.

" }, { "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", "type": "boolean", "name": "listening", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Indicates whether or not the server is listening for connections." }, { "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", "type": "number", "name": "maxHeadersCount", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "default": "`2000`", "desc": "

Limits maximum incoming headers count. If set to 0, no limit will be applied.

" }, { "textRaw": "`requestTimeout` {number} **Default:** `0`", "type": "number", "name": "requestTimeout", "meta": { "added": [ "v14.11.0" ], "changes": [] }, "default": "`0`", "desc": "

Sets the timeout value in milliseconds for receiving the entire request from\nthe client.

\n

If the timeout expires, the server responds with status 408 without\nforwarding the request to the request listener and then closes the connection.

\n

It 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": "`timeout` {number} Timeout in milliseconds. **Default:** 0 (no timeout)", "type": "number", "name": "timeout", "meta": { "added": [ "v0.9.12" ], "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)." } ] }, "default": "0 (no timeout)", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

A value of 0 will disable the timeout behavior on incoming connections.

\n

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": "`keepAliveTimeout` {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).", "type": "number", "name": "keepAliveTimeout", "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. If the server receives new data before the keep-alive\ntimeout has fired, it will reset the regular inactivity timeout, i.e.,\nserver.timeout.

\n

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.

\n

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": "Class: `http.ServerResponse`", "type": "class", "name": "http.ServerResponse", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "\n

This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.6.7" ], "changes": [] }, "params": [], "desc": "

Indicates that the response is completed, or its underlying connection was\nterminated prematurely (before the response completion).

" }, { "textRaw": "Event: `'finish'`", "type": "event", "name": "finish", "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)`", "type": "method", "name": "addTrailers", "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.

\n

Trailers 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.

\n

HTTP requires the Trailer header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "`response.cork()`", "type": "method", "name": "cork", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

See writable.cork().

" }, { "textRaw": "`response.end([data[, encoding]][, callback])`", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `ServerResponse`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`data` {string|Buffer}", "name": "data", "type": "string|Buffer" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

If data is specified, it is similar in effect to calling\nresponse.write(data, encoding) followed by response.end(callback).

\n

If callback is specified, it will be called when the response stream\nis finished.

" }, { "textRaw": "`response.flushHeaders()`", "type": "method", "name": "flushHeaders", "meta": { "added": [ "v1.6.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Flushes the response headers. See also: request.flushHeaders().

" }, { "textRaw": "`response.getHeader(name)`", "type": "method", "name": "getHeader", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

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().

\n
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()`", "type": "method", "name": "getHeaderNames", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

\n
response.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()`", "type": "method", "name": "getHeaders", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "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.

\n

The 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.

\n
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)`", "type": "method", "name": "hasHeader", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

\n
const hasContentType = response.hasHeader('content-type');\n
" }, { "textRaw": "`response.removeHeader(name)`", "type": "method", "name": "removeHeader", "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.

\n
response.removeHeader('Content-Encoding');\n
" }, { "textRaw": "`response.setHeader(name, value)`", "type": "method", "name": "setHeader", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http.ServerResponse}", "name": "return", "type": "http.ServerResponse" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns the response object.

\n

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. 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.

\n
response.setHeader('Content-Type', 'text/html');\n
\n

or

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

\n

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.

\n
// 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
\n

If 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().

" }, { "textRaw": "`response.setTimeout(msecs[, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http.ServerResponse}", "name": "return", "type": "http.ServerResponse" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`response.uncork()`", "type": "method", "name": "uncork", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

See writable.uncork().

" }, { "textRaw": "`response.write(chunk[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`chunk` {string|Buffer}", "name": "chunk", "type": "string|Buffer" }, { "textRaw": "`encoding` {string} **Default:** `'utf8'`", "name": "encoding", "type": "string", "default": "`'utf8'`" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

\n

In the 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.

\n

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.

\n

This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

\n

The 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.

\n

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.

" }, { "textRaw": "`response.writeContinue()`", "type": "method", "name": "writeContinue", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue' event on\nServer.

" }, { "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", "type": "method", "name": "writeHead", "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": [ { "return": { "textRaw": "Returns: {http.ServerResponse}", "name": "return", "type": "http.ServerResponse" }, "params": [ { "textRaw": "`statusCode` {number}", "name": "statusCode", "type": "number" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string" }, { "textRaw": "`headers` {Object|Array}", "name": "headers", "type": "Object|Array" } ] } ], "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.

\n

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.

\n

Returns a reference to the ServerResponse, so that calls can be chained.

\n
const body = 'hello world';\nresponse\n  .writeHead(200, {\n    'Content-Length': Buffer.byteLength(body),\n    'Content-Type': 'text/plain'\n  })\n  .end(body);\n
\n

This method must only be called once on a message and it must\nbe called before response.end() is called.

\n

If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

\n

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.

\n

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.

\n
// 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
\n

Content-Length is given in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes. Node.js\ndoes not check whether Content-Length and the length of the body which has\nbeen transmitted are equal or not.

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "`response.writeProcessing()`", "type": "method", "name": "writeProcessing", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sends a HTTP/1.1 102 Processing message to the client, indicating that\nthe request body should be sent.

" } ], "properties": [ { "textRaw": "`connection` {stream.Duplex}", "type": "stream.Duplex", "name": "connection", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v13.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`response.socket`][].", "desc": "

See response.socket.

" }, { "textRaw": "`finished` {boolean}", "type": "boolean", "name": "finished", "meta": { "added": [ "v0.0.2" ], "deprecated": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`response.writableEnded`][].", "desc": "

The response.finished property will be true if response.end()\nhas been called.

" }, { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "desc": "

Boolean (read-only). True if headers were sent, false otherwise.

" }, { "textRaw": "`req` {http.IncomingMessage}", "type": "http.IncomingMessage", "name": "req", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "

A reference to the original HTTP request object.

" }, { "textRaw": "`sendDate` {boolean}", "type": "boolean", "name": "sendDate", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "desc": "

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.

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.

" }, { "textRaw": "`socket` {stream.Duplex}", "type": "stream.Duplex", "name": "socket", "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.

\n
const http = require('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
\n

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>.

" }, { "textRaw": "`statusCode` {number} **Default:** `200`", "type": "number", "name": "statusCode", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "default": "`200`", "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.

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

" }, { "textRaw": "`statusMessage` {string}", "type": "string", "name": "statusMessage", "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.

\n
response.statusMessage = 'Not found';\n
\n

After response header was sent to the client, this property indicates the\nstatus message which was sent out.

" }, { "textRaw": "`writableEnded` {boolean}", "type": "boolean", "name": "writableEnded", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`writableFinished` {boolean}", "type": "boolean", "name": "writableFinished", "meta": { "added": [ "v12.7.0" ], "changes": [] }, "desc": "

Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.

" } ] }, { "textRaw": "Class: `http.IncomingMessage`", "type": "class", "name": "http.IncomingMessage", "meta": { "added": [ "v0.1.17" ], "changes": [ { "version": "v15.5.0", "pr-url": "https://github.com/nodejs/node/pull/33035", "description": "The `destroyed` value returns `true` after the incoming data is consumed." }, { "version": [ "v13.1.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30135", "description": "The `readableHighWaterMark` value mirrors that of the socket." } ] }, "desc": "\n

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.

\n

Different from its socket value which is a subclass of <stream.Duplex>, the\nIncomingMessage 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.

", "events": [ { "textRaw": "Event: `'aborted'`", "type": "event", "name": "aborted", "meta": { "added": [ "v0.3.8" ], "changes": [] }, "params": [], "desc": "

Emitted when the request has been aborted.

" }, { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.4.2" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying connection was closed.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v10.1.0" ], "changes": [] }, "desc": "

The message.aborted property will be true if the request has\nbeen aborted.

" }, { "textRaw": "`complete` {boolean}", "type": "boolean", "name": "complete", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

The message.complete property will be true if a complete HTTP message has\nbeen received and successfully parsed.

\n

This property is particularly useful as a means of determining if a client or\nserver fully transmitted a message before a connection was terminated:

\n
const 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", "meta": { "added": [ "v0.1.90" ], "deprecated": [ "v16.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`message.socket`][].", "desc": "

Alias for message.socket.

" }, { "textRaw": "`headers` {Object}", "type": "Object", "name": "headers", "meta": { "added": [ "v0.1.5" ], "changes": [ { "version": "v15.1.0", "pr-url": "https://github.com/nodejs/node/pull/35281", "description": "`message.headers` is now lazily computed using an accessor property on the prototype." } ] }, "desc": "

The request/response headers object.

\n

Key-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

Duplicates in raw headers are handled in the following ways, depending on the\nheader name:

\n
    \n
  • Duplicates of age, 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.
  • \n
  • set-cookie is always an array. Duplicates are added to the array.
  • \n
  • For duplicate cookie headers, the values are joined together with '; '.
  • \n
  • For all other headers, the values are joined together with ', '.
  • \n
" }, { "textRaw": "`httpVersion` {string}", "type": "string", "name": "httpVersion", "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'.

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

" }, { "textRaw": "`method` {string}", "type": "string", "name": "method", "meta": { "added": [ "v0.1.1" ], "changes": [] }, "desc": "

Only valid for request obtained from http.Server.

\n

The request method as a string. Read only. Examples: 'GET', 'DELETE'.

" }, { "textRaw": "`rawHeaders` {string[]}", "type": "string[]", "name": "rawHeaders", "meta": { "added": [ "v0.11.6" ], "changes": [] }, "desc": "

The raw request/response headers list exactly as they were received.

\n

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.

\n

Header 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": "`rawTrailers` {string[]}", "type": "string[]", "name": "rawTrailers", "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.

" }, { "textRaw": "`socket` {stream.Duplex}", "type": "stream.Duplex", "name": "socket", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

The net.Socket object associated with the connection.

\n

With HTTPS support, use request.socket.getPeerCertificate() to obtain the\nclient's authentication details.

\n

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>.

" }, { "textRaw": "`statusCode` {number}", "type": "number", "name": "statusCode", "meta": { "added": [ "v0.1.1" ], "changes": [] }, "desc": "

Only valid for response obtained from http.ClientRequest.

\n

The 3-digit HTTP response status code. E.G. 404.

" }, { "textRaw": "`statusMessage` {string}", "type": "string", "name": "statusMessage", "meta": { "added": [ "v0.11.10" ], "changes": [] }, "desc": "

Only valid for response obtained from http.ClientRequest.

\n

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

" }, { "textRaw": "`trailers` {Object}", "type": "Object", "name": "trailers", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

" }, { "textRaw": "`url` {string}", "type": "string", "name": "url", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "

Only valid for request obtained from http.Server.

\n

Request URL string. This contains only the URL that is present in the actual\nHTTP request. Take the following request:

\n
GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
\n

To parse the URL into its parts:

\n
new URL(request.url, `http://${request.headers.host}`);\n
\n

When request.url is '/status?name=ryan' and\nrequest.headers.host is 'localhost:3000':

\n
$ node\n> new URL(request.url, `http://${request.headers.host}`)\nURL {\n  href: 'http://localhost:3000/status?name=ryan',\n  origin: 'http://localhost:3000',\n  protocol: 'http:',\n  username: '',\n  password: '',\n  host: 'localhost:3000',\n  hostname: 'localhost',\n  port: '3000',\n  pathname: '/status',\n  search: '?name=ryan',\n  searchParams: URLSearchParams { 'name' => 'ryan' },\n  hash: ''\n}\n
" } ], "methods": [ { "textRaw": "`message.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/32789", "description": "The function returns `this` for consistency with other Readable streams." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ] } ], "desc": "

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.

" }, { "textRaw": "`message.setTimeout(msecs[, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http.IncomingMessage}", "name": "return", "type": "http.IncomingMessage" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Calls message.socket.setTimeout(msecs, callback).

" } ] }, { "textRaw": "Class: `http.OutgoingMessage`", "type": "class", "name": "http.OutgoingMessage", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "\n

This class serves as the parent class of http.ClientRequest\nand http.ServerResponse. It is an abstract of outgoing message from\nthe perspective of the participants of HTTP transaction.

", "events": [ { "textRaw": "Event: `drain`", "type": "event", "name": "drain`", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "params": [], "desc": "

Emitted when the buffer of the message is free again.

" }, { "textRaw": "Event: `finish`", "type": "event", "name": "finish`", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "params": [], "desc": "

Emitted when the transmission is finished successfully.

" }, { "textRaw": "Event: `prefinish`", "type": "event", "name": "prefinish`", "meta": { "added": [ "v0.11.6" ], "changes": [] }, "params": [], "desc": "

Emitted when outgoingMessage.end was called.\nWhen the event is emitted, all data has been processed but not necessarily\ncompletely flushed.

" } ], "methods": [ { "textRaw": "`outgoingMessage.addTrailers(headers)`", "type": "method", "name": "addTrailers", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "

Adds HTTP trailers (headers but at the end of the message) to the message.

\n

Trailers are only be emitted if the message is chunked encoded. If not,\nthe trailer will be silently discarded.

\n

HTTP requires the Trailer header to be sent to emit trailers,\nwith a list of header fields in its value, e.g.

\n
message.writeHead(200, { 'Content-Type': 'text/plain',\n                         'Trailer': 'Content-MD5' });\nmessage.write(fileData);\nmessage.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nmessage.end();\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "`outgoingMessage.cork()`", "type": "method", "name": "cork", "meta": { "added": [ "v14.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

See writable.cork().

" }, { "textRaw": "`outgoingMessage.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error} Optional, an error to emit with `error` event", "name": "error", "type": "Error", "desc": "Optional, an error to emit with `error` event" } ] } ], "desc": "

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])`", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v0.11.6", "description": "add `callback` argument." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`chunk` {string | Buffer}", "name": "chunk", "type": "string | Buffer" }, { "textRaw": "`encoding` {string} Optional, **Default**: `utf8`", "name": "encoding", "type": "string", "desc": "Optional, **Default**: `utf8`" }, { "textRaw": "`callback` {Function} Optional", "name": "callback", "type": "Function", "desc": "Optional" } ] } ], "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 trailer (if any).

\n

If chunk is specified, it is equivalent to call\noutgoingMessage.write(chunk, encoding), followed by\noutgoingMessage.end(callback).

\n

If callback is provided, it will be called when the message is finished.\n(equivalent to the callback to event finish)

" }, { "textRaw": "`outgoingMessage.flushHeaders()`", "type": "method", "name": "flushHeaders", "meta": { "added": [ "v1.6.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Compulsorily flushes the message headers

\n

For 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.

\n

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 request.

" }, { "textRaw": "`outgoingMessage.getHeader(name)`", "type": "method", "name": "getHeader", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {string | undefined}", "name": "return", "type": "string | undefined" }, "params": [ { "textRaw": "`name` {string} Name of header", "name": "name", "type": "string", "desc": "Name of header" } ] } ], "desc": "

Gets the value of HTTP header with the given name. If such a name doesn't\nexist in message, it will be undefined.

" }, { "textRaw": "`outgoingMessage.getHeaderNames()`", "type": "method", "name": "getHeaderNames", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array of names of headers of the outgoing outgoingMessage. All\nnames are lowercase.

" }, { "textRaw": "`outgoingMessage.getHeaders()`", "type": "method", "name": "getHeaders", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "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.

\n

The 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.

\n
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)`", "type": "method", "name": "hasHeader", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns true if the header identified by name is currently set in the\noutgoing headers. The header name is case-insensitive.

\n
const hasContentType = outgoingMessage.hasHeader('content-type');\n
" }, { "textRaw": "`outgoingMessage.pipe()`", "type": "method", "name": "pipe", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Overrides the pipe method of legacy Stream which is the parent class of\nhttp.outgoingMessage.

\n

Since OutgoingMessage should be a write-only stream,\ncall this function will throw an Error. Thus, it disabled the pipe method\nit inherits from Stream.

\n

The User should not call this function directly.

" }, { "textRaw": "`outgoingMessage.removeHeader()`", "type": "method", "name": "removeHeader", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Removes a header that is queued for implicit sending.

\n
outgoingMessage.removeHeader('Content-Encoding');\n
" }, { "textRaw": "`outgoingMessage.setHeader(name, value)`", "type": "method", "name": "setHeader", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`name` {string} Header name", "name": "name", "type": "string", "desc": "Header name" }, { "textRaw": "`value` {string} Header value", "name": "value", "type": "string", "desc": "Header value" } ] } ], "desc": "

Sets a single header value for the header object.

" }, { "textRaw": "`outgoingMessage.setTimeout(msesc[, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msesc` {number}", "name": "msesc", "type": "number" }, { "textRaw": "`callback` {Function} Optional function to be called when a timeout", "name": "callback", "type": "Function", "desc": "Optional function to be called when a timeout" } ] } ], "desc": "

occurs, Same as binding to the timeout event.

\n\n

Once a socket is associated with the message and is connected,\nsocket.setTimeout() will be called with msecs as the first parameter.

" }, { "textRaw": "`outgoingMessage.uncork()`", "type": "method", "name": "uncork", "meta": { "added": [ "v14.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

See writable.uncork()

" }, { "textRaw": "`outgoingMessage.write(chunk[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ], "changes": [ { "version": "v0.11.6", "description": "add `callback` argument." } ] }, "signatures": [ { "return": { "textRaw": "Returns {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`chunk` {string | Buffer}", "name": "chunk", "type": "string | Buffer" }, { "textRaw": "`encoding` {string} **Default**: `utf8`", "name": "encoding", "type": "string", "desc": "**Default**: `utf8`" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

If this method is called and the header is not sent, it will call\nthis._implicitHeader to flush implicit header.\nIf the message should not have a body (indicated by this._hasBody),\nthe call is ignored and chunk will not be sent. It could be useful\nwhen handling a particular message which must not include a body.\ne.g. response to HEAD request, 204 and 304 response.

\n

chunk can be a string or a buffer. When chunk is a string, the\nencoding parameter specifies how to encode chunk into a byte stream.\ncallback will be called when the chunk is flushed.

\n

If the message is transferred in chucked encoding\n(indicated by this.chunkedEncoding), chunk will be flushed as\none chunk among a stream of chunks. Otherwise, it will be flushed as the\nbody of message.

\n

This method handles the raw body of the HTTP message and has nothing to do\nwith higher-level multi-part body encodings that may be used.

\n

If it is the first call to this method of a message, it will send the\nbuffered header first, then flush the chunk as described above.

\n

The second and successive calls to this method will assume the data\nwill be streamed and send the new data separately. It means that the response\nis buffered up to the first chunk of the body.

\n

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. Event drain will be emitted when the buffer is free again.

" } ], "properties": [ { "textRaw": "`outgoingMessage.connection`", "name": "connection", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v15.12.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`outgoingMessage.socket`][] instead.", "desc": "

Aliases of outgoingMessage.socket

" }, { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "desc": "

Read-only. true if the headers were sent, otherwise false.

" }, { "textRaw": "`socket` {stream.Duplex}", "type": "stream.Duplex", "name": "socket", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "

Reference to the underlying socket. Usually, users will not want to access\nthis property.

\n

After calling outgoingMessage.end(), this property will be nulled.

" }, { "textRaw": "`writableCorked` {number}", "type": "number", "name": "writableCorked", "meta": { "added": [ "v14.0.0" ], "changes": [] }, "desc": "

This outgoingMessage.writableCorked will return the time how many\noutgoingMessage.cork() have been called.

" }, { "textRaw": "`writableEnded` {boolean}", "type": "boolean", "name": "writableEnded", "meta": { "added": [ "v13.0.0" ], "changes": [] }, "desc": "

Readonly, true if outgoingMessage.end() has been called. Noted that\nthis property does not reflect whether the data has been flush. For that\npurpose, use message.writableFinished instead.

" }, { "textRaw": "`writableFinished` {boolean}", "type": "boolean", "name": "writableFinished", "meta": { "added": [ "v13.0.0" ], "changes": [] }, "desc": "

Readonly. true if all data has been flushed to the underlying system.

" }, { "textRaw": "`writableHighWaterMark` {number}", "type": "number", "name": "writableHighWaterMark", "meta": { "added": [ "v13.0.0" ], "changes": [] }, "desc": "

This outgoingMessage.writableHighWaterMark will be the highWaterMark of\nunderlying socket if socket exists. Else, it would be the default\nhighWaterMark.

\n

highWaterMark is the maximum amount of data that can be potentially\nbuffered by the socket.

" }, { "textRaw": "`writableLength` {number}", "type": "number", "name": "writableLength", "meta": { "added": [ "v13.0.0" ], "changes": [] }, "desc": "

Readonly, This outgoingMessage.writableLength contains the number of\nbytes (or objects) in the buffer ready to send.

" }, { "textRaw": "`writableObjectMode` {boolean}", "type": "boolean", "name": "writableObjectMode", "meta": { "added": [ "v13.0.0" ], "changes": [] }, "desc": "

Readonly, always returns false.

" } ] } ], "properties": [ { "textRaw": "`METHODS` {string[]}", "type": "string[]", "name": "METHODS", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "

A list of the HTTP methods that are supported by the parser.

" }, { "textRaw": "`STATUS_CODES` {Object}", "type": "Object", "name": "STATUS_CODES", "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'.

" }, { "textRaw": "`globalAgent` {http.Agent}", "type": "http.Agent", "name": "globalAgent", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "desc": "

Global instance of Agent which is used as the default for all HTTP client\nrequests.

" }, { "textRaw": "`maxHeaderSize` {number}", "type": "number", "name": "maxHeaderSize", "meta": { "added": [ "v11.6.0", "v10.15.0" ], "changes": [] }, "desc": "

Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 8 KB. Configurable using the --max-http-header-size CLI\noption.

\n

This can be overridden for servers and client requests by passing the\nmaxHeaderSize option.

" } ], "methods": [ { "textRaw": "`http.createServer([options][, requestListener])`", "type": "method", "name": "createServer", "meta": { "added": [ "v0.1.13" ], "changes": [ { "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": [ "v9.6.0", "v8.12.0" ], "pr-url": "https://github.com/nodejs/node/pull/15752", "description": "The `options` argument is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.Server}", "name": "return", "type": "http.Server" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. **Default:** `IncomingMessage`.", "name": "IncomingMessage", "type": "http.IncomingMessage", "default": "`IncomingMessage`", "desc": "Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`." }, { "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. **Default:** `ServerResponse`.", "name": "ServerResponse", "type": "http.ServerResponse", "default": "`ServerResponse`", "desc": "Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`." }, { "textRaw": "`insecureHTTPParser` {boolean} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", "name": "insecureHTTPParser", "type": "boolean", "default": "`false`", "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information." }, { "textRaw": "`maxHeaderSize` {number} Optionally overrides the value of [`--max-http-header-size`][] for requests received by this server, i.e. the maximum length of request headers in bytes. **Default:** 16384 (16 KB).", "name": "maxHeaderSize", "type": "number", "default": "16384 (16 KB)", "desc": "Optionally overrides the value of [`--max-http-header-size`][] for requests received by this server, i.e. the maximum length of request headers in bytes." } ] }, { "textRaw": "`requestListener` {Function}", "name": "requestListener", "type": "Function" } ] } ], "desc": "

Returns a new instance of http.Server.

\n

The requestListener is a function which is automatically\nadded to the 'request' event.

\n
const http = require('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
\n
const http = require('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])`", "type": "method", "name": "get", "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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "params": [ { "textRaw": "`url` {string | URL}", "name": "url", "type": "string | URL" }, { "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", "name": "options", "type": "Object", "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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 and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

\n

The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

\n

JSON fetching example:

\n
http.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.get(url[, options][, callback])`", "type": "method", "name": "get", "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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "params": [ { "textRaw": "`url` {string | URL}", "name": "url", "type": "string | URL" }, { "textRaw": "`options` {Object} Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored.", "name": "options", "type": "Object", "desc": "Accepts the same `options` as [`http.request()`][], with the `method` always set to `GET`. Properties that are inherited from the prototype are ignored." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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 and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.

\n

The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.

\n

JSON fetching example:

\n
http.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])`", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.7.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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "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 i.e. `'user:password'` to compute an Authorization header.", "name": "auth", "type": "string", "desc": "Basic authentication i.e. `'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} An object containing request headers.", "name": "headers", "type": "Object", "desc": "An object containing request headers." }, { "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} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", "name": "insecureHTTPParser", "type": "boolean", "default": "`false`", "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] 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`][] for requests received from the server, i.e. the maximum length of response headers in bytes. **Default:** 16384 (16 KB).", "name": "maxHeaderSize", "type": "number", "default": "16384 (16 KB)", "desc": "Optionally overrides the value of [`--max-http-header-size`][] for requests received from the server, i.e. the maximum length of response headers in bytes." }, { "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": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", "name": "setHost", "type": "boolean", "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." }, { "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", "name": "socketPath", "type": "string", "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, 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": "`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": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

\n

url 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.

\n

If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

\n

The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

\n

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.

\n
const http = require('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
\n

In 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.

\n

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.

\n

There are a few special headers that should be noted.

\n
    \n
  • \n

    Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

    \n
  • \n
  • \n

    Sending a 'Content-Length' header will disable the default chunked encoding.

    \n
  • \n
  • \n

    Sending 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.

    \n
  • \n
  • \n

    Sending an Authorization header will override using the auth option\nto compute basic authentication.

    \n
  • \n
\n

Example using a URL as options:

\n
const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
\n

In a successful request, the following events will be emitted in the following\norder:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \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)
    • \n
    • 'end' on the res object
    • \n
    \n
  • \n
  • 'close'
  • \n
\n

In the case of a connection error, the following events will be emitted:

\n
    \n
  • 'socket'
  • \n
  • 'error'
  • \n
  • 'close'
  • \n
\n

In the case of a premature connection close before the response is received,\nthe following events will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

In the case of a premature connection close after the response is received,\nthe following events will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (connection closed here)
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

If req.destroy() is called before a socket is assigned, the following\nevents will be emitted in the following order:

\n
    \n
  • (req.destroy() called here)
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.destroy() is called before the connection succeeds, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • (req.destroy() called here)
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.destroy() is called after the response is received, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (req.destroy() called here)
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

If req.abort() is called before a socket is assigned, the following\nevents will be emitted in the following order:

\n
    \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'close'
  • \n
\n

If req.abort() is called before the connection succeeds, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.abort() is called after the response is received, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

\n

Passing an AbortSignal and then calling abort on the corresponding\nAbortController will behave the same way as calling .destroy() on the\nrequest itself.

" }, { "textRaw": "`http.request(url[, options][, callback])`", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.7.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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "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 i.e. `'user:password'` to compute an Authorization header.", "name": "auth", "type": "string", "desc": "Basic authentication i.e. `'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} An object containing request headers.", "name": "headers", "type": "Object", "desc": "An object containing request headers." }, { "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} Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] for more information. **Default:** `false`", "name": "insecureHTTPParser", "type": "boolean", "default": "`false`", "desc": "Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. Using the insecure parser should be avoided. See [`--insecure-http-parser`][] 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`][] for requests received from the server, i.e. the maximum length of response headers in bytes. **Default:** 16384 (16 KB).", "name": "maxHeaderSize", "type": "number", "default": "16384 (16 KB)", "desc": "Optionally overrides the value of [`--max-http-header-size`][] for requests received from the server, i.e. the maximum length of response headers in bytes." }, { "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": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. Defaults to `true`.", "name": "setHost", "type": "boolean", "desc": ": Specifies whether or not to automatically add the `Host` header. Defaults to `true`." }, { "textRaw": "`socketPath` {string} Unix Domain Socket (cannot be used if one of `host` or `port` is specified, those specify a TCP Socket).", "name": "socketPath", "type": "string", "desc": "Unix Domain Socket (cannot be used if one of `host` or `port` is specified, 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": "`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": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

\n

url 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.

\n

If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.

\n

The optional callback parameter will be added as a one-time listener for\nthe 'response' event.

\n

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.

\n
const http = require('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
\n

In 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.

\n

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.

\n

There are a few special headers that should be noted.

\n
    \n
  • \n

    Sending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.

    \n
  • \n
  • \n

    Sending a 'Content-Length' header will disable the default chunked encoding.

    \n
  • \n
  • \n

    Sending 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.

    \n
  • \n
  • \n

    Sending an Authorization header will override using the auth option\nto compute basic authentication.

    \n
  • \n
\n

Example using a URL as options:

\n
const options = new URL('http://abc:xyz@example.com');\n\nconst req = http.request(options, (res) => {\n  // ...\n});\n
\n

In a successful request, the following events will be emitted in the following\norder:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \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)
    • \n
    • 'end' on the res object
    • \n
    \n
  • \n
  • 'close'
  • \n
\n

In the case of a connection error, the following events will be emitted:

\n
    \n
  • 'socket'
  • \n
  • 'error'
  • \n
  • 'close'
  • \n
\n

In the case of a premature connection close before the response is received,\nthe following events will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

In the case of a premature connection close after the response is received,\nthe following events will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (connection closed here)
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

If req.destroy() is called before a socket is assigned, the following\nevents will be emitted in the following order:

\n
    \n
  • (req.destroy() called here)
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.destroy() is called before the connection succeeds, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • (req.destroy() called here)
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.destroy() is called after the response is received, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (req.destroy() called here)
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

If req.abort() is called before a socket is assigned, the following\nevents will be emitted in the following order:

\n
    \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'close'
  • \n
\n

If req.abort() is called before the connection succeeds, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET'
  • \n
  • 'close'
  • \n
\n

If req.abort() is called after the response is received, the following\nevents will be emitted in the following order:

\n
    \n
  • 'socket'
  • \n
  • 'response'\n
      \n
    • 'data' any number of times, on the res object
    • \n
    \n
  • \n
  • (req.abort() called here)
  • \n
  • 'abort'
  • \n
  • 'aborted' on the res object
  • \n
  • 'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.
  • \n
  • 'close'
  • \n
  • 'close' on the res object
  • \n
\n

Setting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.

\n

Passing an AbortSignal and then calling abort on the corresponding\nAbortController will behave the same way as calling .destroy() on the\nrequest itself.

" }, { "textRaw": "`http.validateHeaderName(name)`", "type": "method", "name": "validateHeaderName", "meta": { "added": [ "v14.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Performs the low-level validations on the provided name that are done when\nres.setHeader(name, value) is called.

\n

Passing illegal value as name will result in a TypeError being thrown,\nidentified by code: 'ERR_INVALID_HTTP_TOKEN'.

\n

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:

\n

Example:

\n
const { validateHeaderName } = require('http');\n\ntry {\n  validateHeaderName('');\n} catch (err) {\n  err instanceof TypeError; // --> true\n  err.code; // --> 'ERR_INVALID_HTTP_TOKEN'\n  err.message; // --> 'Header name must be a valid HTTP token [\"\"]'\n}\n
" }, { "textRaw": "`http.validateHeaderValue(name, value)`", "type": "method", "name": "validateHeaderValue", "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.

\n

Passing illegal value as value will result in a TypeError being thrown.

\n
    \n
  • Undefined value error is identified by code: 'ERR_HTTP_INVALID_HEADER_VALUE'.
  • \n
  • Invalid value character error is identified by code: 'ERR_INVALID_CHAR'.
  • \n
\n

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.

\n

Examples:

\n
const { validateHeaderValue } = require('http');\n\ntry {\n  validateHeaderValue('x-my-header', undefined);\n} catch (err) {\n  err instanceof TypeError; // --> true\n  err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true\n  err.message; // --> 'Invalid value \"undefined\" for header \"x-my-header\"'\n}\n\ntry {\n  validateHeaderValue('x-my-header', 'oʊmɪɡə');\n} catch (err) {\n  err instanceof TypeError; // --> true\n  err.code === 'ERR_INVALID_CHAR'; // --> true\n  err.message; // --> 'Invalid character in header content [\"x-my-header\"]'\n}\n
" } ], "type": "module", "displayName": "HTTP", "source": "doc/api/http.md" }, { "textRaw": "HTTP/2", "name": "http/2", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v15.3.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." } ] }, "introduced_in": "v8.4.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/http2.js

\n

The http2 module provides an implementation of the HTTP/2 protocol. It\ncan be accessed using:

\n
const http2 = require('http2');\n
", "modules": [ { "textRaw": "Core API", "name": "core_api", "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.

\n

The 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.

", "modules": [ { "textRaw": "Server-side example", "name": "server-side_example", "desc": "

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.

\n
const http2 = require('http2');\nconst fs = require('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
\n

To generate the certificate and key for this example, run:

\n
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n  -keyout localhost-privkey.pem -out localhost-cert.pem\n
", "type": "module", "displayName": "Server-side example" }, { "textRaw": "Client-side example", "name": "client-side_example", "desc": "

The following illustrates an HTTP/2 client:

\n
const http2 = require('http2');\nconst fs = require('fs');\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
", "type": "module", "displayName": "Client-side example" }, { "textRaw": "Headers object", "name": "headers_object", "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).

\n
const headers = {\n  ':status': '200',\n  'content-type': 'text-plain',\n  'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
\n

Header 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.

\n

For incoming headers:

\n
    \n
  • The :status header is converted to number.
  • \n
  • Duplicates of :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.
  • \n
  • set-cookie is always an array. Duplicates are added to the array.
  • \n
  • For duplicate cookie headers, the values are joined together with '; '.
  • \n
  • For all other headers, the values are joined together with ', '.
  • \n
\n
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n  console.log(headers[':path']);\n  console.log(headers.ABC);\n});\n
", "modules": [ { "textRaw": "Sensitive headers", "name": "sensitive_headers", "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:

\n
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
\n

For some headers, such as Authorization and short Cookie headers,\nthis flag is set automatically.

\n

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.

", "type": "module", "displayName": "Sensitive headers" } ], "type": "module", "displayName": "Headers object" }, { "textRaw": "Settings object", "name": "settings_object", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/29833", "description": "The `maxConcurrentStreams` setting is stricter." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "The `maxHeaderListSize` setting is now strictly enforced." } ] }, "desc": "

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.

\n
    \n
  • 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.
  • \n
  • enablePush <boolean> Specifies true if HTTP/2 Push Streams are to be\npermitted on the Http2Session instances. Default: true.
  • \n
  • 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.
  • \n
  • 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.
  • \n
  • 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.
  • \n
  • 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.
  • \n
  • maxHeaderSize <number> Alias for maxHeaderListSize.
  • \n
  • 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.
  • \n
\n

All additional properties on the settings object are ignored.

", "type": "module", "displayName": "Settings object" }, { "textRaw": "Error handling", "name": "error_handling", "desc": "

There are several types of error conditions that may arise when using the\nhttp2 module:

\n

Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.

\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "Error handling" }, { "textRaw": "Invalid character handling in header names and values", "name": "invalid_character_handling_in_header_names_and_values", "desc": "

The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.

\n

Header 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.

\n

Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.

\n

Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.

\n

Header 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.

", "type": "module", "displayName": "Invalid character handling in header names and values" }, { "textRaw": "Push streams on the client", "name": "push_streams_on_the_client", "desc": "

To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:

\n
const http2 = require('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
", "type": "module", "displayName": "Push streams on the client" }, { "textRaw": "Supporting the `CONNECT` method", "name": "supporting_the_`connect`_method", "desc": "

The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.

\n

A simple TCP Server:

\n
const net = require('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
\n

An HTTP/2 CONNECT proxy:

\n
const http2 = require('http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('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
\n

An HTTP/2 CONNECT client:

\n
const http2 = require('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:${port}`\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
", "type": "module", "displayName": "Supporting the `CONNECT` method" }, { "textRaw": "The extended `CONNECT` protocol", "name": "the_extended_`connect`_protocol", "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).

\n

The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:

\n
const http2 = require('http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
\n

Once 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:

\n
const http2 = require('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
", "type": "module", "displayName": "The extended `CONNECT` protocol" } ], "classes": [ { "textRaw": "Class: `Http2Session`", "type": "class", "name": "Http2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

", "modules": [ { "textRaw": "`Http2Session` and sockets", "name": "`http2session`_and_sockets", "desc": "

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.

\n

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.

\n

Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.

", "type": "module", "displayName": "`Http2Session` and sockets" } ], "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.

" }, { "textRaw": "Event: `'connect'`", "type": "event", "name": "connect", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {Http2Session}", "name": "session", "type": "Http2Session" }, { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" } ], "desc": "

The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.

\n

User code will typically not listen for this event directly.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "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.

" }, { "textRaw": "Event: `'frameError'`", "type": "event", "name": "frameError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {integer} The frame type.", "name": "type", "type": "integer", "desc": "The frame type." }, { "textRaw": "`code` {integer} The error code.", "name": "code", "type": "integer", "desc": "The error code." }, { "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", "name": "id", "type": "integer", "desc": "The stream id (or `0` if the frame isn't associated with a stream)." } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'goaway'`", "type": "event", "name": "goaway", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.", "name": "errorCode", "type": "number", "desc": "The HTTP/2 error code specified in the `GOAWAY` frame." }, { "textRaw": "`lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified).", "name": "lastStreamID", "type": "number", "desc": "The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified)." }, { "textRaw": "`opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data.", "name": "opaqueData", "type": "Buffer", "desc": "If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data." } ], "desc": "

The 'goaway' event is emitted when a GOAWAY frame is received.

\n

The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.

" }, { "textRaw": "Event: `'localSettings'`", "type": "event", "name": "localSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.

\n

When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.

\n
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: `'ping'`", "type": "event", "name": "ping", "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.

" }, { "textRaw": "Event: `'remoteSettings'`", "type": "event", "name": "remoteSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.

\n
session.on('remoteSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: `'stream'`", "type": "event", "name": "stream", "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` {Array} An array containing the raw header names followed by their respective values.", "name": "rawHeaders", "type": "Array", "desc": "An array containing the raw header names followed by their respective values." } ], "desc": "

The 'stream' event is emitted when a new Http2Stream is created.

\n
const http2 = require('http2');\nsession.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
\n

On 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:

\n
const http2 = require('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(80);\n
\n

Even 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'`", "type": "event", "name": "timeout", "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.

\n
session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
" } ], "properties": [ { "textRaw": "`alpnProtocol` {string|undefined}", "type": "string|undefined", "name": "alpnProtocol", "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.

" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been closed, otherwise\nfalse.

" }, { "textRaw": "`connecting` {boolean}", "type": "boolean", "name": "connecting", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.

" }, { "textRaw": "`encrypted` {boolean|undefined}", "type": "boolean|undefined", "name": "encrypted", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`localSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "localSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.

" }, { "textRaw": "`originSet` {string[]|undefined}", "type": "string[]|undefined", "name": "originSet", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

\n

The originSet property is only available when using a secure TLS connection.

" }, { "textRaw": "`pendingSettingsAck` {boolean}", "type": "boolean", "name": "pendingSettingsAck", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`remoteSettings` {HTTP/2 Settings Object}", "type": "HTTP/2 Settings Object", "name": "remoteSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.

" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

\n

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.

\n

setTimeout method will be called on this Http2Session.

\n

All other interactions will be routed directly to the socket.

" }, { "textRaw": "`http2session.state`", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Session.

\n
    \n
  • <Object>\n
      \n
    • effectiveLocalWindowSize <number> The current local (receive)\nflow control window size for the Http2Session.
    • \n
    • effectiveRecvDataLength <number> The current number of bytes\nthat have been received since the last flow control WINDOW_UPDATE.
    • \n
    • nextStreamID <number> The numeric identifier to be used the\nnext time a new Http2Stream is created by this Http2Session.
    • \n
    • localWindowSize <number> The number of bytes that the remote peer can\nsend without receiving a WINDOW_UPDATE.
    • \n
    • lastProcStreamID <number> The numeric id of the Http2Stream\nfor which a HEADERS or DATA frame was most recently received.
    • \n
    • remoteWindowSize <number> The number of bytes that this Http2Session\nmay send without receiving a WINDOW_UPDATE.
    • \n
    • outboundQueueSize <number> The number of frames currently within the\noutbound queue for this Http2Session.
    • \n
    • deflateDynamicTableSize <number> The current size in bytes of the\noutbound header compression state table.
    • \n
    • inflateDynamicTableSize <number> The current size in bytes of the\ninbound header compression state table.
    • \n
    \n
  • \n
\n

An object describing the current status of this Http2Session.

" }, { "textRaw": "`type` {number}", "type": "number", "name": "type", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" } ], "methods": [ { "textRaw": "`http2session.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

If specified, the callback function is registered as a handler for the\n'close' event.

" }, { "textRaw": "`http2session.destroy([error][, code])`", "type": "method", "name": "destroy", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error} An `Error` object if the `Http2Session` is being destroyed due to an error.", "name": "error", "type": "Error", "desc": "An `Error` object if the `Http2Session` is being destroyed due to an error." }, { "textRaw": "`code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.", "name": "code", "type": "number", "desc": "The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`." } ] } ], "desc": "

Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.

\n

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.

\n

If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.

" }, { "textRaw": "`http2session.goaway([code[, lastStreamID[, opaqueData]]])`", "type": "method", "name": "goaway", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} An HTTP/2 error code", "name": "code", "type": "number", "desc": "An HTTP/2 error code" }, { "textRaw": "`lastStreamID` {number} The numeric ID of the last processed `Http2Stream`", "name": "lastStreamID", "type": "number", "desc": "The numeric ID of the last processed `Http2Stream`" }, { "textRaw": "`opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", "name": "opaqueData", "type": "Buffer|TypedArray|DataView", "desc": "A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame." } ] } ], "desc": "

Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.

" }, { "textRaw": "`http2session.ping([payload, ]callback)`", "type": "method", "name": "ping", "meta": { "added": [ "v8.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`payload` {Buffer|TypedArray|DataView} Optional ping payload.", "name": "payload", "type": "Buffer|TypedArray|DataView", "desc": "Optional ping payload." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.

\n

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.

\n

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.

\n
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
\n

If the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.

" }, { "textRaw": "`http2session.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls ref() on this Http2Session\ninstance's underlying net.Socket.

" }, { "textRaw": "`http2session.setLocalWindowSize(windowSize)`", "type": "method", "name": "setLocalWindowSize", "meta": { "added": [ "v15.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`windowSize` {number}", "name": "windowSize", "type": "number" } ] } ], "desc": "

Sets the local endpoint's window size.\nThe windowSize is the total window size to set, not\nthe delta.

\n
const http2 = require('http2');\n\nconst server = http2.createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('connect', (session) => {\n\n  // Set local window size to be 2 ** 20\n  session.setLocalWindowSize(expectedWindowSize);\n});\n
" }, { "textRaw": "`http2session.setTimeout(msecs, callback)`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

" }, { "textRaw": "`http2session.settings([settings][, callback])`", "type": "method", "name": "settings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" }, { "textRaw": "`callback` {Function} Callback that is called once the session is connected or right away if the session is already connected.", "name": "callback", "type": "Function", "desc": "Callback that is called once the session is connected or right away if the session is already connected.", "options": [ { "textRaw": "`err` {Error|null}", "name": "err", "type": "Error|null" }, { "textRaw": "`settings` {HTTP/2 Settings Object} The updated `settings` object.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The updated `settings` object." }, { "textRaw": "`duration` {integer}", "name": "duration", "type": "integer" } ] } ] } ], "desc": "

Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.

\n

Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.

\n

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.

" }, { "textRaw": "`http2session.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls unref() on this Http2Session\ninstance's underlying net.Socket.

" } ] }, { "textRaw": "Class: `ServerHttp2Session`", "type": "class", "name": "ServerHttp2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "", "methods": [ { "textRaw": "`serverhttp2session.altsvc(alt, originOrStream)`", "type": "method", "name": "altsvc", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`alt` {string} A description of the alternative service configuration as defined by [RFC 7838][].", "name": "alt", "type": "string", "desc": "A description of the alternative service configuration as defined by [RFC 7838][]." }, { "textRaw": "`originOrStream` {number|string|URL|Object} Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property.", "name": "originOrStream", "type": "number|string|URL|Object", "desc": "Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the `http2stream.id` property." } ] } ], "desc": "

Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

\n
const http2 = require('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
\n

Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.

\n

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.

\n

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.

\n

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.

" }, { "textRaw": "`serverhttp2session.origin(...origins)`", "type": "method", "name": "origin", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`origins` { string | URL | Object } One or more URL Strings passed as separate arguments.", "name": "origins", "type": " string | URL | Object ", "desc": "One or more URL Strings passed as separate arguments." } ] } ], "desc": "

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.

\n
const http2 = require('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
\n

When 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.

\n

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.

\n

Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:

\n
const http2 = require('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", "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.

\n

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.

\n

Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.

\n

The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.

\n

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.

", "type": "module", "displayName": "Specifying alternative services" } ] }, { "textRaw": "Class: `ClientHttp2Session`", "type": "class", "name": "ClientHttp2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "", "events": [ { "textRaw": "Event: `'altsvc'`", "type": "event", "name": "altsvc", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "params": [ { "textRaw": "`alt` {string}", "name": "alt", "type": "string" }, { "textRaw": "`origin` {string}", "name": "origin", "type": "string" }, { "textRaw": "`streamId` {number}", "name": "streamId", "type": "number" } ], "desc": "

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.

\n
const http2 = require('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'`", "type": "event", "name": "origin", "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.

\n
const http2 = require('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
\n

The 'origin' event is only emitted when using a secure TLS connection.

" } ], "methods": [ { "textRaw": "`clienthttp2session.request(headers[, options])`", "type": "method", "name": "request", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ClientHttp2Stream}", "name": "return", "type": "ClientHttp2Stream" }, "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`endStream` {boolean} `true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body.", "name": "endStream", "type": "boolean", "desc": "`true` if the `Http2Stream` *writable* side should be closed initially, such as when sending a `GET` request that should not expect a payload body." }, { "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." }, { "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", "name": "weight", "type": "number", "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." }, { "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": "`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." } ] } ] } ], "desc": "

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.

\n

This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.

\n
const http2 = require('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
\n

When 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.

\n

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.

\n

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.

\n

The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:

\n
    \n
  • :method = 'GET'
  • \n
  • :path = /
  • \n
" } ] }, { "textRaw": "Class: `Http2Stream`", "type": "class", "name": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

\n

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.

\n

The default text character encoding for all Http2Streams is UTF-8. As a best\npractice, it is recommended that when using an Http2Stream to send text,\nthe 'content-type' header should be set and should identify the character\nencoding used.

\n
stream.respond({\n  'content-type': 'text/html; charset=utf-8',\n  ':status': 200\n});\n
", "modules": [ { "textRaw": "`Http2Stream` Lifecycle", "name": "`http2stream`_lifecycle", "modules": [ { "textRaw": "Creation", "name": "creation", "desc": "

On the server side, instances of ServerHttp2Stream are created either\nwhen:

\n
    \n
  • A new HTTP/2 HEADERS frame with a previously unused stream ID is received;
  • \n
  • The http2stream.pushStream() method is called.
  • \n
\n

On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.

\n

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.

", "type": "module", "displayName": "Creation" }, { "textRaw": "Destruction", "name": "destruction", "desc": "

All Http2Stream instances are destroyed either when:

\n
    \n
  • An RST_STREAM frame for the stream is received by the connected peer,\nand (for client streams only) pending data has been read.
  • \n
  • The http2stream.close() method is called, and (for client streams only)\npending data has been read.
  • \n
  • The http2stream.destroy() or http2session.destroy() methods are called.
  • \n
\n

When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.

\n

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.

\n

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.

", "type": "module", "displayName": "Destruction" } ], "type": "module", "displayName": "`Http2Stream` Lifecycle" } ], "events": [ { "textRaw": "Event: `'aborted'`", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.

\n

The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.

" }, { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.

\n

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.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "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 Http2Stream.

" }, { "textRaw": "Event: `'frameError'`", "type": "event", "name": "frameError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {integer} The frame type.", "name": "type", "type": "integer", "desc": "The frame type." }, { "textRaw": "`code` {integer} The error code.", "name": "code", "type": "integer", "desc": "The error code." }, { "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", "name": "id", "type": "integer", "desc": "The stream id (or `0` if the frame isn't associated with a stream)." } ], "desc": "

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.

" }, { "textRaw": "Event: `'ready'`", "type": "event", "name": "ready", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'timeout'`", "type": "event", "name": "timeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'trailers'`", "type": "event", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "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": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" } ], "desc": "

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.

\n

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.

\n
stream.on('trailers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'wantTrailers'`", "type": "event", "name": "wantTrailers", "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.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.

" }, { "textRaw": "`bufferSize` {number}", "type": "number", "name": "bufferSize", "meta": { "added": [ "v11.2.0", "v10.16.0" ], "changes": [] }, "desc": "

This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.

" }, { "textRaw": "`closed` {boolean}", "type": "boolean", "name": "closed", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been closed.

" }, { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.

" }, { "textRaw": "`endAfterHeaders` {boolean}", "type": "boolean", "name": "endAfterHeaders", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "desc": "

Set the 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.

" }, { "textRaw": "`id` {number|undefined}", "type": "number|undefined", "name": "id", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.

" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.

" }, { "textRaw": "`rstCode` {number}", "type": "number", "name": "rstCode", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`sentHeaders` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound headers sent for this Http2Stream.

" }, { "textRaw": "`sentInfoHeaders` {HTTP/2 Headers Object[]}", "type": "HTTP/2 Headers Object[]", "name": "sentInfoHeaders", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.

" }, { "textRaw": "`sentTrailers` {HTTP/2 Headers Object}", "type": "HTTP/2 Headers Object", "name": "sentTrailers", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound trailers sent for this HttpStream.

" }, { "textRaw": "`session` {Http2Session}", "type": "Http2Session", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.

" }, { "textRaw": "`http2stream.state`", "name": "state", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Stream.

\n
    \n
  • <Object>\n
      \n
    • localWindowSize <number> The number of bytes the connected peer may send\nfor this Http2Stream without receiving a WINDOW_UPDATE.
    • \n
    • state <number> A flag indicating the low-level current state of the\nHttp2Stream as determined by nghttp2.
    • \n
    • localClose <number> 1 if this Http2Stream has been closed locally.
    • \n
    • remoteClose <number> 1 if this Http2Stream has been closed\nremotely.
    • \n
    • sumDependencyWeight <number> The sum weight of all Http2Stream\ninstances that depend on this Http2Stream as specified using\nPRIORITY frames.
    • \n
    • weight <number> The priority weight of this Http2Stream.
    • \n
    \n
  • \n
\n

A current state of this Http2Stream.

" } ], "methods": [ { "textRaw": "`http2stream.close(code[, callback])`", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).", "name": "code", "type": "number", "default": "`http2.constants.NGHTTP2_NO_ERROR` (`0x00`)", "desc": "Unsigned 32-bit integer identifying the error code." }, { "textRaw": "`callback` {Function} An optional function registered to listen for the `'close'` event.", "name": "callback", "type": "Function", "desc": "An optional function registered to listen for the `'close'` event." } ] } ], "desc": "

Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.

" }, { "textRaw": "`http2stream.priority(options)`", "type": "method", "name": "priority", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. **Default:** `false`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "When `true` and `parent` identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream this stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream this stream is dependent on." }, { "textRaw": "`weight` {number} Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive).", "name": "weight", "type": "number", "desc": "Specifies the relative dependency of a stream in relation to other streams with the same `parent`. The value is a number between `1` and `256` (inclusive)." }, { "textRaw": "`silent` {boolean} When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer.", "name": "silent", "type": "boolean", "desc": "When `true`, changes the priority locally without sending a `PRIORITY` frame to the connected peer." } ] } ] } ], "desc": "

Updates the priority for this Http2Stream instance.

" }, { "textRaw": "`http2stream.setTimeout(msecs, callback)`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "
const http2 = require('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)`", "type": "method", "name": "sendTrailers", "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.

\n
const http2 = require('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
\n

The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).

" } ] }, { "textRaw": "Class: `ClientHttp2Stream`", "type": "class", "name": "ClientHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'continue'`", "type": "event", "name": "continue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'headers'`", "type": "event", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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 and flags\nassociated with the headers.

\n
stream.on('headers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'push'`", "type": "event", "name": "push", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "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.

\n
stream.on('push', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'response'`", "type": "event", "name": "response", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "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 two arguments: an Object containing the received\nHTTP/2 Headers Object, and flags associated with the headers.

\n
const http2 = require('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`", "type": "class", "name": "ServerHttp2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "methods": [ { "textRaw": "`http2stream.additionalHeaders(headers)`", "type": "method", "name": "additionalHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ] } ], "desc": "

Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

" }, { "textRaw": "`http2stream.pushStream(headers[, options], callback)`", "type": "method", "name": "pushStream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`exclusive` {boolean} When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. **Default:** `false`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "When `true` and `parent` identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." } ] }, { "textRaw": "`callback` {Function} Callback that is called once the push stream has been initiated.", "name": "callback", "type": "Function", "desc": "Callback that is called once the push stream has been initiated.", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`pushStream` {ServerHttp2Stream} The returned `pushStream` object.", "name": "pushStream", "type": "ServerHttp2Stream", "desc": "The returned `pushStream` object." }, { "textRaw": "`headers` {HTTP/2 Headers Object} Headers object the `pushStream` was initiated with.", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "Headers object the `pushStream` was initiated with." } ] } ] } ], "desc": "

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.

\n
const http2 = require('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
\n

Setting 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.

\n

Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.

" }, { "textRaw": "`http2stream.respond([headers[, options]])`", "type": "method", "name": "respond", "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." } ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`endStream` {boolean} Set to `true` to indicate that the response will not include payload data.", "name": "endStream", "type": "boolean", "desc": "Set to `true` to indicate that the response will not include payload data." }, { "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." } ] } ] } ], "desc": "
const http2 = require('http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.end('some data');\n});\n
\n

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.

\n

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.

\n
const http2 = require('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]])`", "type": "method", "name": "respondWithFD", "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" }, { "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." } ] } ] } ], "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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\n
const http2 = require('http2');\nconst fs = require('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
\n

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 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.

\n

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.

\n

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.

\n

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.

\n

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.

\n
const http2 = require('http2');\nconst fs = require('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]])`", "type": "method", "name": "respondWithFile", "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" }, { "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." } ] } ] } ], "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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\n

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:

\n

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.

\n

Example using a file path:

\n
const http2 = require('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.log(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
\n

The 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:

\n
const http2 = require('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
\n

The content-length header field will be automatically set.

\n

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.

\n

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.

\n

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.

\n

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.

\n
const http2 = require('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": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" }, { "textRaw": "`pushAllowed` {boolean}", "type": "boolean", "name": "pushAllowed", "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.

" } ] }, { "textRaw": "Class: `Http2Server`", "type": "class", "name": "Http2Server", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the http2\nmodule.

", "events": [ { "textRaw": "Event: `'checkContinue'`", "type": "event", "name": "checkContinue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'request'`", "type": "event", "name": "request", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: `'session'`", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.

" }, { "textRaw": "Event: `'sessionError'`", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.

" }, { "textRaw": "Event: `'stream'`", "type": "event", "name": "stream", "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` {Array} An array containing the raw header names followed by their respective values.", "name": "rawHeaders", "type": "Array", "desc": "An array containing the raw header names followed by their respective values." } ], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n

See also Http2Session's 'stream' event.

\n
const http2 = require('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'`", "type": "event", "name": "timeout", "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)

" } ], "methods": [ { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

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.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "type": "method", "name": "setTimeout", "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)." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" }, "params": [ { "textRaw": "`msecs` {number} **Default:** 0 (no timeout)", "name": "msecs", "type": "number", "default": "0 (no timeout)" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case if callback is not a function, a new ERR_INVALID_CALLBACK\nerror will be thrown.

" }, { "textRaw": "`server.updateSettings([settings])`", "type": "method", "name": "updateSettings", "meta": { "added": [ "v15.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" } ] } ], "desc": "

Used to update the server with the provided settings.

\n

Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.

\n

Throws ERR_INVALID_ARG_TYPE for invalid settings argument.

" } ], "properties": [ { "textRaw": "`timeout` {number} Timeout in milliseconds. **Default:** 0 (no timeout)", "type": "number", "name": "timeout", "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)." } ] }, "default": "0 (no timeout)", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

A value of 0 will disable the timeout behavior on incoming connections.

\n

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`", "type": "class", "name": "Http2SecureServer", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the http2 module.

", "events": [ { "textRaw": "Event: `'checkContinue'`", "type": "event", "name": "checkContinue", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'request'`", "type": "event", "name": "request", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: `'session'`", "type": "event", "name": "session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.

" }, { "textRaw": "Event: `'sessionError'`", "type": "event", "name": "sessionError", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.

" }, { "textRaw": "Event: `'stream'`", "type": "event", "name": "stream", "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` {Array} An array containing the raw header names followed by their respective values.", "name": "rawHeaders", "type": "Array", "desc": "An array containing the raw header names followed by their respective values." } ], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n

See also Http2Session's 'stream' event.

\n
const http2 = require('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'`", "type": "event", "name": "timeout", "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.

" }, { "textRaw": "Event: `'unknownProtocol'`", "type": "event", "name": "unknownProtocol", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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().\nSee the Compatibility API.

" } ], "methods": [ { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

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.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Http2SecureServer}", "name": "return", "type": "Http2SecureServer" }, "params": [ { "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", "name": "msecs", "type": "number", "default": "`120000` (2 minutes)" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case if callback is not a function, a new ERR_INVALID_CALLBACK\nerror will be thrown.

" }, { "textRaw": "`server.updateSettings([settings])`", "type": "method", "name": "updateSettings", "meta": { "added": [ "v15.1.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" } ] } ], "desc": "

Used to update the server with the provided settings.

\n

Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.

\n

Throws ERR_INVALID_ARG_TYPE for invalid settings argument.

" } ], "properties": [ { "textRaw": "`timeout` {number} Timeout in milliseconds. **Default:** 0 (no timeout)", "type": "number", "name": "timeout", "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)." } ] }, "default": "0 (no timeout)", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

A value of 0 will disable the timeout behavior on incoming connections.

\n

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])`", "type": "method", "name": "createServer", "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.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": [ { "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" }, "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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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} 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": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.", "name": "Http1IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`", "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`.", "name": "Http1ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`", "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." }, { "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": "...: Any [`net.createServer()`][] option can be provided.", "name": "...", "desc": "Any [`net.createServer()`][] option can be provided." } ] }, { "textRaw": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]" } ] } ], "desc": "

Returns a net.Server instance that creates and manages Http2Session\ninstances.

\n

Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

\n
const http2 = require('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(80);\n
" }, { "textRaw": "`http2.createSecureServer(options[, onRequestHandler])`", "type": "method", "name": "createSecureServer", "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.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": [ { "return": { "textRaw": "Returns: {Http2SecureServer}", "name": "return", "type": "Http2SecureServer" }, "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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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": "...: Any [`tls.createServer()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required.", "name": "...", "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": "`onRequestHandler` {Function} See [Compatibility API][]", "name": "onRequestHandler", "type": "Function", "desc": "See [Compatibility API][]" } ] } ], "desc": "

Returns a tls.Server instance that creates and manages Http2Session\ninstances.

\n
const http2 = require('http2');\nconst fs = require('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(80);\n
" }, { "textRaw": "`http2.connect(authority[, options][, listener])`", "type": "method", "name": "connect", "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": [ { "return": { "textRaw": "Returns: {ClientHttp2Session}", "name": "return", "type": "ClientHttp2Session" }, "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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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 [`http.Server#maxHeadersCount`][] or [`http.ClientRequest#maxHeadersCount`][]. 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": "`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": "...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided.", "name": "...", "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": "`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." } ] } ], "desc": "

Returns a ClientHttp2Session instance.

\n
const http2 = require('http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
" }, { "textRaw": "`http2.getDefaultSettings()`", "type": "method", "name": "getDefaultSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {HTTP/2 Settings Object}", "name": "return", "type": "HTTP/2 Settings Object" }, "params": [] } ], "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.

" }, { "textRaw": "`http2.getPackedSettings([settings])`", "type": "method", "name": "getPackedSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object" } ] } ], "desc": "

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.

\n
const http2 = require('http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
" }, { "textRaw": "`http2.getUnpackedSettings(buf)`", "type": "method", "name": "getUnpackedSettings", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {HTTP/2 Settings Object}", "name": "return", "type": "HTTP/2 Settings Object" }, "params": [ { "textRaw": "`buf` {Buffer|TypedArray} The packed settings.", "name": "buf", "type": "Buffer|TypedArray", "desc": "The packed settings." } ] } ], "desc": "

Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().

" } ], "properties": [ { "textRaw": "`http2.constants`", "name": "constants", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "modules": [ { "textRaw": "Error codes for `RST_STREAM` and `GOAWAY`", "name": "error_codes_for_`rst_stream`_and_`goaway`", "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
ValueNameConstant
0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
0x08Cancelhttp2.constants.NGHTTP2_CANCEL
0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
\n

The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().

", "type": "module", "displayName": "Error codes for `RST_STREAM` and `GOAWAY`" } ] }, { "textRaw": "`sensitiveHeaders` {symbol}", "type": "symbol", "name": "sensitiveHeaders", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

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.

" } ], "type": "module", "displayName": "Core API" }, { "textRaw": "Compatibility API", "name": "compatibility_api", "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.

\n

The following example creates an HTTP/2 server using the compatibility\nAPI:

\n
const http2 = require('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
\n

In 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.

\n

The 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.

", "modules": [ { "textRaw": "ALPN negotiation", "name": "alpn_negotiation", "desc": "

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.

\n

The following example creates a server that supports both protocols:

\n
const { createSecureServer } = require('http2');\nconst { readFileSync } = require('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
\n

The 'request' event works identically on both HTTPS and\nHTTP/2.

", "type": "module", "displayName": "ALPN negotiation" } ], "classes": [ { "textRaw": "Class: `http2.Http2ServerRequest`", "type": "class", "name": "http2.Http2ServerRequest", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'aborted'`", "type": "event", "name": "aborted", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.

\n

The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.

" }, { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.

" } ], "properties": [ { "textRaw": "`aborted` {boolean}", "type": "boolean", "name": "aborted", "meta": { "added": [ "v10.1.0" ], "changes": [] }, "desc": "

The request.aborted property will be true if the request has\nbeen aborted.

" }, { "textRaw": "`authority` {string}", "type": "string", "name": "authority", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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'].

" }, { "textRaw": "`complete` {boolean}", "type": "boolean", "name": "complete", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "

The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.

" }, { "textRaw": "`connection` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "connection", "meta": { "added": [ "v8.4.0" ], "deprecated": [ "v13.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`request.socket`][].", "desc": "

See request.socket.

" }, { "textRaw": "`headers` {Object}", "type": "Object", "name": "headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response headers object.

\n

Key-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

See HTTP/2 Headers Object.

\n

In 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:

\n
removeAllHeaders(request.headers);\nassert(request.url);   // Fails because the :path header has been removed\n
" }, { "textRaw": "`httpVersion` {string}", "type": "string", "name": "httpVersion", "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'.

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

" }, { "textRaw": "`method` {string}", "type": "string", "name": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

" }, { "textRaw": "`rawHeaders` {string[]}", "type": "string[]", "name": "rawHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The raw request/response headers list exactly as they were received.

\n

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.

\n

Header 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": "`rawTrailers` {string[]}", "type": "string[]", "name": "rawTrailers", "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.

" }, { "textRaw": "`scheme` {string}", "type": "string", "name": "scheme", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request scheme pseudo header field indicating the scheme\nportion of the target URL.

" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "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.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.

\n

destroy, emit, end, on and once methods will be called on\nrequest.stream.

\n

setTimeout method will be called on request.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.

" }, { "textRaw": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the request.

" }, { "textRaw": "`trailers` {Object}", "type": "Object", "name": "trailers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

" }, { "textRaw": "`url` {string}", "type": "string", "name": "url", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:

\n
GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
\n

Then request.url will be:

\n\n
'/status?name=ryan'\n
\n

To parse the url into its parts, new URL() can be used:

\n
$ 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])`", "type": "method", "name": "destroy", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ] } ], "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.

\n

It does nothing if the stream was already destroyed.

" }, { "textRaw": "`request.setTimeout(msecs, callback)`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http2.Http2ServerRequest}", "name": "return", "type": "http2.Http2ServerRequest" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

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.

" } ] }, { "textRaw": "Class: `http2.Http2ServerResponse`", "type": "class", "name": "http2.Http2ServerResponse", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.

" }, { "textRaw": "Event: `'finish'`", "type": "event", "name": "finish", "meta": { "added": [ "v8.4.0" ], "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 HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.

\n

After this event, no more events will be emitted on the response object.

" } ], "methods": [ { "textRaw": "`response.addTrailers(headers)`", "type": "method", "name": "addTrailers", "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.

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "`response.createPushResponse(headers, callback)`", "type": "method", "name": "createPushResponse", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "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.

" }, { "textRaw": "`response.end([data[, encoding]][, callback])`", "type": "method", "name": "end", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `ServerResponse`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`data` {string|Buffer|Uint8Array}", "name": "data", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n

If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).

\n

If callback is specified, it will be called when the response stream\nis finished.

" }, { "textRaw": "`response.getHeader(name)`", "type": "method", "name": "getHeader", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.

\n
const contentType = response.getHeader('content-type');\n
" }, { "textRaw": "`response.getHeaderNames()`", "type": "method", "name": "getHeaderNames", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

\n
response.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()`", "type": "method", "name": "getHeaders", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "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.

\n

The 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.

\n
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)`", "type": "method", "name": "hasHeader", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

\n
const hasContentType = response.hasHeader('content-type');\n
" }, { "textRaw": "`response.removeHeader(name)`", "type": "method", "name": "removeHeader", "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.

\n
response.removeHeader('Content-Encoding');\n
" } ], "properties": [ { "textRaw": "`connection` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "connection", "meta": { "added": [ "v8.4.0" ], "deprecated": [ "v13.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`response.socket`][].", "desc": "

See response.socket.

" }, { "textRaw": "`finished` {boolean}", "type": "boolean", "name": "finished", "meta": { "added": [ "v8.4.0" ], "deprecated": [ "v13.4.0", "v12.16.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated. Use [`response.writableEnded`][].", "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

" }, { "textRaw": "`headersSent` {boolean}", "type": "boolean", "name": "headersSent", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" } ] } ], "properties": [ { "textRaw": "`req` {http2.Http2ServerRequest}", "type": "http2.Http2ServerRequest", "name": "req", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "

A reference to the original HTTP2 request object.

", "properties": [ { "textRaw": "`sendDate` {boolean}", "type": "boolean", "name": "sendDate", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.

" }, { "textRaw": "`socket` {net.Socket|tls.TLSSocket}", "type": "net.Socket|tls.TLSSocket", "name": "socket", "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.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.

\n

destroy, emit, end, on and once methods will be called on\nresponse.stream.

\n

setTimeout method will be called on response.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket.

\n
const http2 = require('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": "`statusCode` {number}", "type": "number", "name": "statusCode", "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.

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

" }, { "textRaw": "`statusMessage` {string}", "type": "string", "name": "statusMessage", "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": "`stream` {Http2Stream}", "type": "Http2Stream", "name": "stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the response.

" }, { "textRaw": "`writableEnded` {boolean}", "type": "boolean", "name": "writableEnded", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

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.

" } ], "methods": [ { "textRaw": "`response.setHeader(name, value)`", "type": "method", "name": "setHeader", "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.

\n
response.setHeader('Content-Type', 'text/html; charset=utf-8');\n
\n

or

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

\n

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.

\n
// 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])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" }, "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

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.

" }, { "textRaw": "`response.write(chunk[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array}", "name": "chunk", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

\n

In the 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.

\n

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.

\n

This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

\n

The 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.

\n

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.

" }, { "textRaw": "`response.writeContinue()`", "type": "method", "name": "writeContinue", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.

" }, { "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", "type": "method", "name": "writeHead", "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": [ { "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" }, "params": [ { "textRaw": "`statusCode` {number}", "name": "statusCode", "type": "number" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string" }, { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "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.

\n

Returns a reference to the Http2ServerResponse, so that calls can be chained.

\n

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.

\n
const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain; charset=utf-8',\n});\n
\n

Content-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.

\n

This method may be called at most one time on a message before\nresponse.end() is called.

\n

If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

\n

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.

\n
// 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
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" } ] } ], "type": "module", "displayName": "Compatibility API" }, { "textRaw": "Collecting HTTP/2 performance metrics", "name": "collecting_http/2_performance_metrics", "desc": "

The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.

\n
const { PerformanceObserver } = require('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
\n

The entryType property of the PerformanceEntry will be equal to 'http2'.

\n

The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.

\n

If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:

\n
    \n
  • bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.
  • \n
  • bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.
  • \n
  • id <number> The identifier of the associated Http2Stream
  • \n
  • timeToFirstByte <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first DATA frame.
  • \n
  • timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.
  • \n
  • timeToFirstHeader <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first header.
  • \n
\n

If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:

\n
    \n
  • bytesRead <number> The number of bytes received for this Http2Session.
  • \n
  • bytesWritten <number> The number of bytes sent for this Http2Session.
  • \n
  • framesReceived <number> The number of HTTP/2 frames received by the\nHttp2Session.
  • \n
  • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
  • \n
  • maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.
  • \n
  • 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.
  • \n
  • streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.
  • \n
  • streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.
  • \n
  • type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.
  • \n
", "type": "module", "displayName": "Collecting HTTP/2 performance metrics" }, { "textRaw": "Note on `:authority` and `host`", "name": "note_on_`:authority`_and_`host`", "desc": "

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).

\n

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.

", "type": "module", "displayName": "Note on `:authority` and `host`" } ], "type": "module", "displayName": "HTTP/2", "source": "doc/api/http2.md" }, { "textRaw": "HTTPS", "name": "https", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/https.js

\n

HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.

", "classes": [ { "textRaw": "Class: `https.Agent`", "type": "class", "name": "https.Agent", "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.

", "signatures": [ { "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][sni wiki] 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][sni wiki] to be sent to the server. Use empty string `''` to disable sending the extension." } ] } ] } ] }, { "textRaw": "Class: `https.Server`", "type": "class", "name": "https.Server", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "desc": "\n

See http.Server for more information.

", "methods": [ { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {https.Server}", "name": "return", "type": "https.Server" }, "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

See server.close() from the HTTP module for details.

" }, { "textRaw": "`server.listen()`", "type": "method", "name": "listen", "signatures": [ { "params": [] } ], "desc": "

Starts the HTTPS server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {https.Server}", "name": "return", "type": "https.Server" }, "params": [ { "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", "name": "msecs", "type": "number", "default": "`120000` (2 minutes)" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

See http.Server#setTimeout().

" } ], "properties": [ { "textRaw": "`headersTimeout` {number} **Default:** `60000`", "type": "number", "name": "headersTimeout", "meta": { "added": [ "v11.3.0" ], "changes": [] }, "default": "`60000`", "desc": "

See http.Server#headersTimeout.

" }, { "textRaw": "`maxHeadersCount` {number} **Default:** `2000`", "type": "number", "name": "maxHeadersCount", "default": "`2000`", "desc": "

See http.Server#maxHeadersCount.

" }, { "textRaw": "`requestTimeout` {number} **Default:** `0`", "type": "number", "name": "requestTimeout", "meta": { "added": [ "v14.11.0" ], "changes": [] }, "default": "`0`", "desc": "

See http.Server#requestTimeout.

" }, { "textRaw": "`timeout` {number} **Default:** 0 (no timeout)", "type": "number", "name": "timeout", "meta": { "added": [ "v0.11.2" ], "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)." } ] }, "default": "0 (no timeout)", "desc": "

See http.Server#timeout.

" }, { "textRaw": "`keepAliveTimeout` {number} **Default:** `5000` (5 seconds)", "type": "number", "name": "keepAliveTimeout", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "default": "`5000` (5 seconds)", "desc": "

See http.Server#keepAliveTimeout.

" } ] } ], "methods": [ { "textRaw": "`https.createServer([options][, requestListener])`", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {https.Server}", "name": "return", "type": "https.Server" }, "params": [ { "textRaw": "`options` {Object} Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][].", "name": "options", "type": "Object", "desc": "Accepts `options` from [`tls.createServer()`][], [`tls.createSecureContext()`][] and [`http.createServer()`][]." }, { "textRaw": "`requestListener` {Function} A listener to be added to the `'request'` event.", "name": "requestListener", "type": "Function", "desc": "A listener to be added to the `'request'` event." } ] } ], "desc": "
// curl -k https://localhost:8000/\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);\n
\n

Or

\n
const https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('test/fixtures/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
" }, { "textRaw": "`https.get(options[, callback])`", "type": "method", "name": "get", "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` always set to `GET`.", "name": "options", "type": "Object | string | URL", "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Like http.get() but for HTTPS.

\n

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.

\n
const https = require('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.get(url[, options][, callback])`", "type": "method", "name": "get", "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` always set to `GET`.", "name": "options", "type": "Object | string | URL", "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Like http.get() but for HTTPS.

\n

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.

\n
const https = require('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])`", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.7.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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "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`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Makes a request to a secure web server.

\n

The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext,\nhighWaterMark.

\n

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.

\n

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.

\n
const https = require('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
\n

Example using options from tls.connect():

\n
const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Alternatively, opt out of connection pooling by not using an Agent.

\n
const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Example using a URL as options:

\n
const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

\n
const tls = require('tls');\nconst https = require('https');\nconst crypto = require('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-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\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 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\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  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
\n

Outputs for example:

\n
Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
" }, { "textRaw": "`https.request(url[, options][, callback])`", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.7.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": [ { "return": { "textRaw": "Returns: {http.ClientRequest}", "name": "return", "type": "http.ClientRequest" }, "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`" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Makes a request to a secure web server.

\n

The following additional options from tls.connect() are also accepted:\nca, cert, ciphers, clientCertEngine, crl, dhparam, ecdhCurve,\nhonorCipherOrder, key, passphrase, pfx, rejectUnauthorized,\nsecureOptions, secureProtocol, servername, sessionIdContext,\nhighWaterMark.

\n

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.

\n

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.

\n
const https = require('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
\n

Example using options from tls.connect():

\n
const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Alternatively, opt out of connection pooling by not using an Agent.

\n
const options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Example using a URL as options:

\n
const options = new URL('https://abc:xyz@example.com');\n\nconst req = https.request(options, (res) => {\n  // ...\n});\n
\n

Example pinning on certificate fingerprint, or the public key (similar to\npin-sha256):

\n
const tls = require('tls');\nconst https = require('https');\nconst crypto = require('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-sha25 pinning\n    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';\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 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +\n      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';\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  // Print the HPKP values\n  console.log('headers:', res.headers['public-key-pins']);\n\n  res.on('data', (d) => {});\n});\n\nreq.on('error', (e) => {\n  console.error(e.message);\n});\nreq.end();\n
\n

Outputs for example:

\n
Subject Common Name: github.com\n  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16\n  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=\nSubject Common Name: DigiCert SHA2 Extended Validation Server CA\n  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A\n  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\nSubject Common Name: DigiCert High Assurance EV Root CA\n  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF\n  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\nAll OK. Server matched our pinned cert or public key\nstatusCode: 200\nheaders: max-age=0; pin-sha256=\"WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=\"; pin-sha256=\"RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=\"; pin-sha256=\"k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws=\"; pin-sha256=\"K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=\"; pin-sha256=\"IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=\"; pin-sha256=\"iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0=\"; pin-sha256=\"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=\"; includeSubDomains\n
" } ], "properties": [ { "textRaw": "`https.globalAgent`", "name": "globalAgent", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "desc": "

Global instance of https.Agent for all HTTPS client requests.

" } ], "type": "module", "displayName": "HTTPS", "source": "doc/api/https.md" }, { "textRaw": "Inspector", "name": "inspector", "introduced_in": "v8.0.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/inspector.js

\n

The inspector module provides an API for interacting with the V8 inspector.

\n

It can be accessed using:

\n
const inspector = require('inspector');\n
", "methods": [ { "textRaw": "`inspector.close()`", "type": "method", "name": "close", "signatures": [ { "params": [] } ], "desc": "

Deactivate the inspector. Blocks until there are no active connections.

" }, { "textRaw": "`inspector.open([port[, host[, wait]]])`", "type": "method", "name": "open", "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." }, { "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." }, { "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." } ] } ], "desc": "

Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programmatically after node has\nstarted.

\n

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.

\n

See the security warning regarding the host\nparameter usage.

" }, { "textRaw": "`inspector.url()`", "type": "method", "name": "url", "signatures": [ { "return": { "textRaw": "Returns: {string|undefined}", "name": "return", "type": "string|undefined" }, "params": [] } ], "desc": "

Return the URL of the active inspector, or undefined if there is none.

\n
$ 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()`", "type": "method", "name": "waitForDebugger", "meta": { "added": [ "v12.7.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Blocks until a client (existing or connected later) has sent\nRuntime.runIfWaitingForDebugger command.

\n

An exception will be thrown if there is no active inspector.

" } ], "properties": [ { "textRaw": "`console` {Object} An object to send messages to the remote inspector console.", "type": "Object", "name": "console", "desc": "
require('inspector').console.log('a message');\n
\n

The inspector console does not have API parity with Node.js\nconsole.

", "shortDesc": "An object to send messages to the remote inspector console." } ], "classes": [ { "textRaw": "Class: `inspector.Session`", "type": "class", "name": "inspector.Session", "desc": "\n

The inspector.Session is used for dispatching messages to the V8 inspector\nback-end and receiving message responses and notifications.

", "events": [ { "textRaw": "Event: `'inspectorNotification'`", "type": "event", "name": "inspectorNotification", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "params": [ { "textRaw": "{Object} The notification message object", "type": "Object", "desc": "The notification message object" } ], "desc": "

Emitted when any notification from the V8 Inspector is received.

\n
session.on('inspectorNotification', (message) => console.log(message.method));\n// Debugger.paused\n// Debugger.resumed\n
\n

It is also possible to subscribe only to notifications with specific method:

" }, { "textRaw": "Event: ``;", "type": "event", "name": "`;", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "params": [ { "textRaw": "{Object} The notification message object", "type": "Object", "desc": "The notification message object" } ], "desc": "

Emitted when an inspector notification is received that has its method field set\nto the <inspector-protocol-method> value.

\n

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):

\n
session.on('Debugger.paused', ({ params }) => {\n  console.log(params.hitBreakpoints);\n});\n// [ '/the/file/that/has/the/breakpoint.js:11:0' ]\n
" } ], "methods": [ { "textRaw": "`session.connect()`", "type": "method", "name": "connect", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Connects a session to the inspector back-end.

" }, { "textRaw": "`session.connectToMainThread()`", "type": "method", "name": "connectToMainThread", "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()`", "type": "method", "name": "disconnect", "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.

" }, { "textRaw": "`session.post(method[, params][, callback])`", "type": "method", "name": "post", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`method` {string}", "name": "method", "type": "string" }, { "textRaw": "`params` {Object}", "name": "params", "type": "Object" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

\n
session.post('Runtime.evaluate', { expression: '2 + 2' },\n             (error, { result }) => console.log(result));\n// Output: { type: 'number', value: 4, description: '4' }\n
\n

The latest version of the V8 inspector protocol is published on the\nChrome DevTools Protocol Viewer.

\n

Node.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.

\n

Example usage

\n

Apart from the debugger, various V8 Profilers are available through the DevTools\nprotocol.

" } ], "modules": [ { "textRaw": "CPU profiler", "name": "cpu_profiler", "desc": "

Here's an example showing how to use the CPU Profiler:

\n
const inspector = require('inspector');\nconst fs = require('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
", "type": "module", "displayName": "CPU profiler" }, { "textRaw": "Heap profiler", "name": "heap_profiler", "desc": "

Here's an example showing how to use the Heap Profiler:

\n
const inspector = require('inspector');\nconst fs = require('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
", "type": "module", "displayName": "Heap profiler" } ], "signatures": [ { "params": [], "desc": "

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.

" } ] } ], "type": "module", "displayName": "Inspector", "source": "doc/api/inspector.md" }, { "textRaw": "Modules: CommonJS modules", "name": "module", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

In the Node.js module system, each file is treated as a separate module. For\nexample, consider a file named foo.js:

\n
const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n
\n

On the first line, foo.js loads the module circle.js that is in the same\ndirectory as foo.js.

\n

Here are the contents of circle.js:

\n
const { PI } = Math;\n\nexports.area = (r) => PI * r ** 2;\n\nexports.circumference = (r) => 2 * PI * r;\n
\n

The 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.

\n

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.

\n

The module.exports property can be assigned a new value (such as a function\nor object).

\n

Below, bar.js makes use of the square module, which exports a Square class:

\n
const Square = require('./square.js');\nconst mySquare = new Square(2);\nconsole.log(`The area of mySquare is ${mySquare.area()}`);\n
\n

The square module is defined in square.js:

\n
// 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
\n

The module system is implemented in the require('module') module.

", "miscs": [ { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

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.

\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.

" }, { "textRaw": "Package manager tips", "name": "Package manager tips", "type": "misc", "desc": "

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.

\n

Below we give a suggested directory structure that could work:

\n

Let'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.

\n

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.

\n

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:

\n
    \n
  • /usr/lib/node/foo/1.2.3/: Contents of the foo package, version 1.2.3.
  • \n
  • /usr/lib/node/bar/4.3.2/: Contents of the bar package that foo depends\non.
  • \n
  • /usr/lib/node/foo/1.2.3/node_modules/bar: Symbolic link to\n/usr/lib/node/bar/4.3.2/.
  • \n
  • /usr/lib/node/bar/4.3.2/node_modules/*: Symbolic links to the packages that\nbar depends on.
  • \n
\n

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.

\n

When 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.

\n

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.

\n

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.

" }, { "textRaw": "All together...", "name": "All together...", "type": "misc", "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require() does:

\n
\nrequire(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 be the filesystem root\n3. If X begins with './' or '/' 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\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, load X.js as JavaScript text. STOP\n3. If X.json is a file, parse 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, load X/index.js as JavaScript text. 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 = [GLOBAL_FOLDERS]\n4. while I >= 0,\n   a. if PARTS[I] = \"node_modules\" CONTINUE\n   b. DIR = path join(PARTS[0 .. I] + \"node_modules\")\n   c. DIRS = DIRS + DIR\n   d. let I = I - 1\n5. return DIRS\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. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),\n  [\"node\", \"require\"]) defined in the ESM resolver.\n5. 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. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), \".\" + SUBPATH,\n   `package.json` \"exports\", [\"node\", \"require\"]) defined in the ESM resolver.\n6. 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   defined in the ESM resolver.\n6. RESOLVE_ESM_MATCH(MATCH)\n\nRESOLVE_ESM_MATCH(MATCH)\n1. let { RESOLVED, EXACT } = MATCH\n2. let RESOLVED_PATH = fileURLToPath(RESOLVED)\n3. If EXACT is true,\n   a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension\n      format. STOP\n4. Otherwise, if EXACT is false,\n   a. LOAD_AS_FILE(RESOLVED_PATH)\n   b. LOAD_AS_DIRECTORY(RESOLVED_PATH)\n5. 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.

\n

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.

\n

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.

\n

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.

" } ] }, { "textRaw": "Core modules", "name": "Core modules", "type": "misc", "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37246", "description": "Added `node:` import support to `require(...)`." } ] }, "desc": "

Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.

\n

The core modules are defined within the Node.js source and are located in the\nlib/ folder.

\n

Core 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.

\n

Core modules can also 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.

" }, { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

When there are circular require() calls, a module might not have finished\nexecuting when it is returned.

\n

Consider this situation:

\n

a.js:

\n
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
\n

b.js:

\n
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
\n

main.js:

\n
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
\n

When 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.

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:

\n
$ 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
\n

Careful 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.

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with process.dlopen().

\n

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.

\n

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.

\n

Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules folder.

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.

" }, { "textRaw": "Folders as modules", "name": "Folders as modules", "type": "misc", "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to those directories.\nThere are three ways in which a folder may be passed to require() as\nan argument.

\n

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:

\n
{ \"name\" : \"some-library\",\n  \"main\" : \"./lib/some-library.js\" }\n
\n

If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.

\n

This is the extent of the awareness of package.json files within Node.js.

\n

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:

\n
    \n
  • ./some-library/index.js
  • \n
  • ./some-library/index.node
  • \n
\n

If these attempts fail, then Node.js will report the entire module as missing\nwith the default error:

\n
Error: Cannot find module 'some-library'\n
" }, { "textRaw": "Loading from `node_modules` folders", "name": "Loading from `node_modules` folders", "type": "misc", "desc": "

If the module identifier passed to require() is not a\ncore module, and does not begin with '/', '../', or\n'./', then Node.js starts at the parent 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.

\n

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.

\n

For 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:

\n
    \n
  • /home/ry/projects/node_modules/bar.js
  • \n
  • /home/ry/node_modules/bar.js
  • \n
  • /home/node_modules/bar.js
  • \n
  • /node_modules/bar.js
  • \n
\n

This allows programs to localize their dependencies, so that they do not\nclash.

\n

It 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.

" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

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.

\n

On Windows, NODE_PATH is delimited by semicolons (;) instead of colons.

\n

NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was defined.

\n

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.

\n

Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:

\n
    \n
  • 1: $HOME/.node_modules
  • \n
  • 2: $HOME/.node_libraries
  • \n
  • 3: $PREFIX/lib/node
  • \n
\n

Where $HOME is the user's home directory, and $PREFIX is the Node.js\nconfigured node_prefix.

\n

These are mostly for historic reasons.

\n

It is strongly encouraged to place dependencies in the local node_modules\nfolder. These will be loaded faster, and more reliably.

" }, { "textRaw": "The module wrapper", "name": "The module wrapper", "type": "misc", "desc": "

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
\n

By doing this, Node.js achieves a few things:

\n
    \n
  • It keeps top-level variables (defined with var, const or let) scoped to\nthe module rather than the global object.
  • \n
  • It helps to provide some global-looking variables that are actually specific\nto the module, such as:\n
      \n
    • The module and exports objects that the implementor can use to export\nvalues from the module.
    • \n
    • The convenience variables __filename and __dirname, containing the\nmodule's absolute filename and directory path.
    • \n
    \n
  • \n
" } ], "modules": [ { "textRaw": "The `.mjs` extension", "name": "the_`.mjs`_extension", "desc": "

It is not possible to require() files that have the .mjs extension.\nAttempting to do so will throw an error. The .mjs extension is\nreserved for ECMAScript Modules which cannot be loaded via require().\nSee ECMAScript Modules for more details.

", "type": "module", "displayName": "The `.mjs` extension" }, { "textRaw": "The module scope", "name": "the_module_scope", "vars": [ { "textRaw": "`__dirname`", "name": "`__dirname`", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "type": "var", "desc": "\n

The directory name of the current module. This is the same as the\npath.dirname() of the __filename.

\n

Example: running node example.js from /Users/mjr

\n
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
" }, { "textRaw": "`__filename`", "name": "`__filename`", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "type": "var", "desc": "\n

The file name of the current module. This is the current module file's absolute\npath with symlinks resolved.

\n

For a main program this is not necessarily the same as the file name used in the\ncommand line.

\n

See __dirname for the directory name of the current module.

\n

Examples:

\n

Running node example.js from /Users/mjr

\n
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
\n

Given two modules: a and b, where b is a dependency of\na and there is a directory structure of:

\n
    \n
  • /Users/mjr/app/a.js
  • \n
  • /Users/mjr/app/node_modules/b/b.js
  • \n
\n

References 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.

" }, { "textRaw": "`exports`", "name": "`exports`", "meta": { "added": [ "v0.1.12" ], "changes": [] }, "type": "var", "desc": "\n

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.

" }, { "textRaw": "`module`", "name": "`module`", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "type": "var", "desc": "\n

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().

" }, { "textRaw": "`require(id)`", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ], "changes": [] }, "desc": "
    \n
  • id <string> module name or path
  • \n
  • Returns: <any> exported module content
  • \n
\n

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.

\n
// 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('crypto');\n
", "properties": [ { "textRaw": "`cache` {Object}", "type": "Object", "name": "cache", "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.

\n

Adding or replacing entries is also possible. This cache is checked before\nnative modules and if a name matching a native module is added to the cache,\nonly node:-prefixed require calls are going to receive the native module.\nUse with care!

\n\n
const assert = require('assert');\nconst realFs = require('fs');\n\nconst fakeFs = {};\nrequire.cache.fs = { exports: fakeFs };\n\nassert.strictEqual(require('fs'), fakeFs);\nassert.strictEqual(require('node:fs'), realFs);\n
" }, { "textRaw": "`extensions` {Object}", "type": "Object", "name": "extensions", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.10.6" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

Instruct require on how to handle certain file extensions.

\n

Process files with the extension .sjs as .js:

\n
require.extensions['.sjs'] = require.extensions['.js'];\n
\n

Deprecated. 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.

\n

Avoid using require.extensions. Use could cause subtle bugs and resolving the\nextensions gets slower with each registered extension.

" }, { "textRaw": "`main` {module}", "type": "module", "name": "main", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "

The Module object representing the entry script loaded when the Node.js\nprocess launched.\nSee \"Accessing the main module\".

\n

In entry.js script:

\n
console.log(require.main);\n
\n
node entry.js\n
\n\n
Module {\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])`", "type": "method", "name": "resolve", "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": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "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." } ] } ] } ], "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.

\n

If the module can not be found, a MODULE_NOT_FOUND error is thrown.

", "methods": [ { "textRaw": "`require.resolve.paths(request)`", "type": "method", "name": "paths", "meta": { "added": [ "v8.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]|null}", "name": "return", "type": "string[]|null" }, "params": [ { "textRaw": "`request` {string} The module path whose lookup paths are being retrieved.", "name": "request", "type": "string", "desc": "The module path whose lookup paths are being retrieved." } ] } ], "desc": "

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.

" } ] } ] } ], "type": "module", "displayName": "The module scope" }, { "textRaw": "The `Module` object", "name": "the_`module`_object", "desc": "

This section was moved to\nModules: module core module.

\n\n", "type": "module", "displayName": "The `Module` object" }, { "textRaw": "Source map v3 support", "name": "source_map_v3_support", "desc": "

This section was moved to\nModules: module core module.

\n\n", "type": "module", "displayName": "Source map v3 support" } ], "meta": { "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37246", "description": "Added `node:` import support to `require(...)`." } ] }, "vars": [ { "textRaw": "The `module` object", "name": "module", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "type": "var", "desc": "\n

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.

", "properties": [ { "textRaw": "`children` {module[]}", "type": "module[]", "name": "children", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The module objects required for the first time by this one.

" }, { "textRaw": "`exports` {Object}", "type": "Object", "name": "exports", "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.

\n

For example, suppose we were making a module called a.js:

\n
const EventEmitter = require('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
\n

Then in another file we could do:

\n
const a = require('./a');\na.on('ready', () => {\n  console.log('module \"a\" is ready');\n});\n
\n

Assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:

\n

x.js:

\n
setTimeout(() => {\n  module.exports = { a: 'hello' };\n}, 0);\n
\n

y.js:

\n
const x = require('./x');\nconsole.log(x.a);\n
", "modules": [ { "textRaw": "`exports` shortcut", "name": "`exports`_shortcut", "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.

\n

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:

\n
module.exports.hello = true; // Exported from require of module\nexports = { hello: false };  // Not exported, only available in the module\n
\n

When the module.exports property is being completely replaced by a new\nobject, it is common to also reassign exports:

\n\n
module.exports = exports = function Constructor() {\n  // ... etc.\n};\n
\n

To illustrate the behavior, imagine this hypothetical implementation of\nrequire(), which is quite similar to what is actually done by require():

\n
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
", "type": "module", "displayName": "`exports` shortcut" } ] }, { "textRaw": "`filename` {string}", "type": "string", "name": "filename", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The fully resolved filename of the module.

" }, { "textRaw": "`id` {string}", "type": "string", "name": "id", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.

" }, { "textRaw": "`isPreloading` Type: {boolean} `true` if the module is running during the Node.js preload phase.", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "desc": "`true` if the module is running during the Node.js preload phase." }, { "textRaw": "`loaded` {boolean}", "type": "boolean", "name": "loaded", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

Whether or not the module is done loading, or is in the process of\nloading.

" }, { "textRaw": "`parent` {module | null | undefined}", "type": "module | null | undefined", "name": "parent", "meta": { "added": [ "v0.1.16" ], "deprecated": [ "v14.6.0", "v12.19.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Please use [`require.main`][] and\n[`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).

" }, { "textRaw": "`path` {string}", "type": "string", "name": "path", "meta": { "added": [ "v11.14.0" ], "changes": [] }, "desc": "

The directory name of the module. This is usually the same as the\npath.dirname() of the module.id.

" }, { "textRaw": "`paths` {string[]}", "type": "string[]", "name": "paths", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "

The search paths for the module.

" } ], "methods": [ { "textRaw": "`module.require(id)`", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {any} exported module content", "name": "return", "type": "any", "desc": "exported module content" }, "params": [ { "textRaw": "`id` {string}", "name": "id", "type": "string" } ] } ], "desc": "

The module.require() method provides a way to load a module as if\nrequire() was called from the original module.

\n

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.

" } ] } ], "type": "module", "displayName": "module", "source": "doc/api/modules.md" }, { "textRaw": "Modules: `module` API", "name": "modules:_`module`_api", "introduced_in": "v12.20.0", "meta": { "added": [ "v0.3.7" ], "changes": [] }, "modules": [ { "textRaw": "The `Module` object", "name": "the_`module`_object", "desc": "\n

Provides general utility methods when interacting with instances of\nModule, the module variable often seen in CommonJS modules. Accessed\nvia import 'module' or require('module').

", "properties": [ { "textRaw": "`builtinModules` {string[]}", "type": "string[]", "name": "builtinModules", "meta": { "added": [ "v9.3.0", "v8.10.0", "v6.13.0" ], "changes": [] }, "desc": "

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.

\n

module in this context isn't the same object that's provided\nby the module wrapper. To access it, require the Module module:

\n
// module.mjs\n// In an ECMAScript module\nimport { builtinModules as builtin } from 'module';\n
\n
// module.cjs\n// In a CommonJS module\nconst builtin = require('module').builtinModules;\n
" } ], "methods": [ { "textRaw": "`module.createRequire(filename)`", "type": "method", "name": "createRequire", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {require} Require function", "name": "return", "type": "require", "desc": "Require function" }, "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." } ] } ], "desc": "
import { createRequire } from 'module';\nconst require = createRequire(import.meta.url);\n\n// sibling-module.js is a CommonJS module.\nconst siblingModule = require('./sibling-module');\n
" }, { "textRaw": "`module.syncBuiltinESMExports()`", "type": "method", "name": "syncBuiltinESMExports", "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.

\n
const fs = require('fs');\nconst assert = require('assert');\nconst { syncBuiltinESMExports } = require('module');\n\nfs.readFile = newAPI;\n\ndelete fs.readFileSync;\n\nfunction newAPI() {\n  // ...\n}\n\nfs.newAPI = newAPI;\n\nsyncBuiltinESMExports();\n\nimport('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
" } ], "type": "module", "displayName": "The `Module` object" }, { "textRaw": "Source map v3 support", "name": "source_map_v3_support", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Helpers for interacting with the source map cache. This cache is\npopulated when source map parsing is enabled and\nsource map include directives are found in a modules' footer.

\n

To 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.

\n
// module.mjs\n// In an ECMAScript module\nimport { findSourceMap, SourceMap } from 'module';\n
\n
// module.cjs\n// In a CommonJS module\nconst { findSourceMap, SourceMap } = require('module');\n
\n\n

", "methods": [ { "textRaw": "`module.findSourceMap(path)`", "type": "method", "name": "findSourceMap", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {module.SourceMap}", "name": "return", "type": "module.SourceMap" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

path is the resolved path for the file for which a corresponding source map\nshould be fetched.

" } ], "classes": [ { "textRaw": "Class: `module.SourceMap`", "type": "class", "name": "module.SourceMap", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "properties": [ { "textRaw": "`payload` Returns: {Object}", "type": "Object", "name": "return", "desc": "

Getter for the payload used to construct the SourceMap instance.

" } ], "methods": [ { "textRaw": "`sourceMap.findEntry(lineNumber, columnNumber)`", "type": "method", "name": "findEntry", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`lineNumber` {number}", "name": "lineNumber", "type": "number" }, { "textRaw": "`columnNumber` {number}", "name": "columnNumber", "type": "number" } ] } ], "desc": "

Given a line number and column number in the generated source file, returns\nan object representing the position in the original file. The object returned\nconsists of the following keys:

\n" } ], "signatures": [ { "params": [ { "textRaw": "`payload` {Object}", "name": "payload", "type": "Object" } ], "desc": "

Creates a new sourceMap instance.

\n

payload is an object with keys matching the Source map v3 format:

\n" } ] } ], "type": "module", "displayName": "Source map v3 support" } ], "type": "module", "displayName": "Modules: `module` API", "source": "doc/api/module.md" }, { "textRaw": "Net", "name": "net", "introduced_in": "v0.10.0", "desc": "\n
\n

Stability: 2 - Stable

\n
\n

Source Code: lib/net.js

\n

The net module provides an asynchronous network API for creating stream-based\nTCP or IPC servers (net.createServer()) and clients\n(net.createConnection()).

\n

It can be accessed using:

\n
const net = require('net');\n
", "modules": [ { "textRaw": "IPC support", "name": "ipc_support", "desc": "

The net module supports IPC with named pipes on Windows, and Unix domain\nsockets on other operating systems.

", "modules": [ { "textRaw": "Identifying paths for IPC connections", "name": "identifying_paths_for_ipc_connections", "desc": "

net.connect(), net.createConnection(), server.listen() and\nsocket.connect() take a path parameter to identify IPC endpoints.

\n

On Unix, the local domain is also known as the Unix domain. The path is a\nfilesystem pathname. It gets truncated to an OS-dependent length of\nsizeof(sockaddr_un.sun_path) - 1. Typical values are 107 bytes on Linux and\n103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,\nit will unlink the Unix domain socket as well. For example,\nnet.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 filesystem and\nwill persist until unlinked.

\n

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.

\n

JavaScript string escaping requires paths to be specified with extra backslash\nescaping such as:

\n
net.createServer().listen(\n  path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n
", "type": "module", "displayName": "Identifying paths for IPC connections" } ], "type": "module", "displayName": "IPC support" } ], "classes": [ { "textRaw": "Class: `net.BlockList`", "type": "class", "name": "net.BlockList", "meta": { "added": [ "v15.0.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.

", "methods": [ { "textRaw": "`blockList.addAddress(address[, type])`", "type": "method", "name": "addAddress", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`address` {string|net.SocketAddress} An IPv4 or IPv6 address.", "name": "address", "type": "string|net.SocketAddress", "desc": "An IPv4 or IPv6 address." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`." } ] } ], "desc": "

Adds a rule to block the given IP address.

" }, { "textRaw": "`blockList.addRange(start, end[, type])`", "type": "method", "name": "addRange", "meta": { "added": [ "v15.0.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'`." } ] } ], "desc": "

Adds a rule to block a range of IP addresses from start (inclusive) to\nend (inclusive).

" }, { "textRaw": "`blockList.addSubnet(net, prefix[, type])`", "type": "method", "name": "addSubnet", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`net` {string|net.SocketAddress} The network IPv4 or IPv6 address.", "name": "net", "type": "string|net.SocketAddress", "desc": "The network IPv4 or IPv6 address." }, { "textRaw": "`prefix` {number} The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`.", "name": "prefix", "type": "number", "desc": "The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`." }, { "textRaw": "`type` {string} Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.", "name": "type", "type": "string", "default": "`'ipv4'`", "desc": "Either `'ipv4'` or `'ipv6'`." } ] } ], "desc": "

Adds a rule to block a range of IP addresses specified as a subnet mask.

" }, { "textRaw": "`blockList.check(address[, type])`", "type": "method", "name": "check", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "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'`." } ] } ], "desc": "

Returns true if the given IP address matches any of the rules added to the\nBlockList.

\n
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
" } ], "properties": [ { "textRaw": "`rules` Type: {string[]}", "type": "string[]", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The list of rules added to the blocklist.

" } ] }, { "textRaw": "Class: `net.SocketAddress`", "type": "class", "name": "net.SocketAddress", "meta": { "added": [ "v15.14.0" ], "changes": [] }, "properties": [ { "textRaw": "`address` Type {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.14.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "`family` Type {string} Either `'ipv4'` or `'ipv6'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.14.0" ], "changes": [] }, "desc": "Either `'ipv4'` or `'ipv6'`." }, { "textRaw": "`flowlabel` Type {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.14.0" ], "changes": [] } }, { "textRaw": "`port` Type {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.14.0" ], "changes": [] } } ], "signatures": [ { "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." } ] } ] } ] }, { "textRaw": "Class: `net.Server`", "type": "class", "name": "net.Server", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "desc": "\n

This class is used to create a TCP or IPC server.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "params": [], "desc": "

Emitted when the server closes. If connections exist, this\nevent is not emitted until all connections are ended.

" }, { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "{net.Socket} The connection object", "type": "net.Socket", "desc": "The connection object" } ], "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "type": "Error" } ], "desc": "

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().

" }, { "textRaw": "Event: `'listening'`", "type": "event", "name": "listening", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the server has been bound after calling server.listen().

" } ], "methods": [ { "textRaw": "`server.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object|string|null}", "name": "return", "type": "Object|string|null" }, "params": [] } ], "desc": "

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' }.

\n

For a server listening on a pipe or Unix domain socket, the name is returned\nas a string.

\n
const 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
\n

server.address() returns null before the 'listening' event has been\nemitted or after calling server.close().

" }, { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`callback` {Function} Called when the server is closed.", "name": "callback", "type": "Function", "desc": "Called when the server is closed." } ] } ], "desc": "

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.

" }, { "textRaw": "`server.getConnections(callback)`", "type": "method", "name": "getConnections", "meta": { "added": [ "v0.9.7" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.

\n

Callback should take two arguments err and count.

" }, { "textRaw": "`server.listen()`", "type": "method", "name": "listen", "signatures": [ { "params": [] } ], "desc": "

Start a server listening for connections. A net.Server can be a TCP or\nan IPC server depending on what it listens to.

\n

Possible signatures:

\n\n\n\n

This 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.

\n

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).

\n

All net.Socket are set to SO_REUSEADDR (see socket(7) for\ndetails).

\n

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.

\n

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:

\n
server.on('error', (e) => {\n  if (e.code === 'EADDRINUSE') {\n    console.log('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])`", "type": "method", "name": "listen", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "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" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "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.

\n

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.

\n

Listening on a file descriptor is not supported on Windows.

" }, { "textRaw": "`server.listen(options[, callback])`", "type": "method", "name": "listen", "meta": { "added": [ "v0.11.14" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`options` {Object} Required. Supports the following properties:", "name": "options", "type": "Object", "desc": "Required. Supports the following properties:", "options": [ { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "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": "`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": "`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": "`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": "`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": "`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": "`callback` {Function} functions.", "name": "callback", "type": "Function", "desc": "functions." } ] } ], "desc": "\n

If port is specified, it behaves the same as\n\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.

\n\n

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.

\n
server.listen({\n  host: 'localhost',\n  port: 80,\n  exclusive: true\n});\n
\n

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.

\n

If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the server:

\n
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])`", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "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." }, { "textRaw": "`callback` {Function}.", "name": "callback", "type": "Function", "desc": "." } ] } ], "desc": "

Start an IPC server listening for connections on the given path.

" }, { "textRaw": "`server.listen([port[, host[, backlog]]][, callback])`", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "textRaw": "`backlog` {number} Common parameter of [`server.listen()`][] functions.", "name": "backlog", "type": "number", "desc": "Common parameter of [`server.listen()`][] functions." }, { "textRaw": "`callback` {Function}.", "name": "callback", "type": "Function", "desc": "." } ] } ], "desc": "

Start a TCP server listening for connections on the given port and host.

\n

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.

\n

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.

\n

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).

" } ] }, { "textRaw": "`server.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [] } ], "desc": "

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.

" }, { "textRaw": "`server.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [] } ], "desc": "

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.

" } ], "properties": [ { "textRaw": "`listening` {boolean} Indicates whether or not the server is listening for connections.", "type": "boolean", "name": "listening", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Indicates whether or not the server is listening for connections." }, { "textRaw": "`maxConnections` {integer}", "type": "integer", "name": "maxConnections", "meta": { "added": [ "v0.2.0" ], "changes": [] }, "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.

\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().

" } ], "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`options` {Object} See [`net.createServer([options][, connectionListener])`][`net.createServer()`].", "name": "options", "type": "Object", "desc": "See [`net.createServer([options][, connectionListener])`][`net.createServer()`]." }, { "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." } ], "desc": "

net.Server is an EventEmitter with the following events:

" } ] }, { "textRaw": "Class: `net.Socket`", "type": "class", "name": "net.Socket", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "`hadError` {boolean} `true` if the socket had a transmission error.", "name": "hadError", "type": "boolean", "desc": "`true` if the socket had a transmission error." } ], "desc": "

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.

" }, { "textRaw": "Event: `'connect'`", "type": "event", "name": "connect", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when a socket connection is successfully established.\nSee net.createConnection().

" }, { "textRaw": "Event: `'data'`", "type": "event", "name": "data", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "{Buffer|string}", "type": "Buffer|string" } ], "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().

\n

The data will be lost if there is no listener when a Socket\nemits a 'data' event.

" }, { "textRaw": "Event: `'drain'`", "type": "event", "name": "drain", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

\n

See also: the return values of socket.write().

" }, { "textRaw": "Event: `'end'`", "type": "event", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

Emitted when the other end of the socket signals the end of transmission, thus\nending the readable side of the socket.

\n

By 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).

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "type": "Error" } ], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.

" }, { "textRaw": "Event: `'lookup'`", "type": "event", "name": "lookup", "meta": { "added": [ "v0.11.3" ], "changes": [ { "version": "v5.10.0", "pr-url": "https://github.com/nodejs/node/pull/5598", "description": "The `host` parameter is supported now." } ] }, "params": [], "desc": "

Emitted after resolving the host name but before connecting.\nNot applicable to Unix sockets.

\n" }, { "textRaw": "Event: `'ready'`", "type": "event", "name": "ready", "meta": { "added": [ "v9.11.0" ], "changes": [] }, "params": [], "desc": "

Emitted when a socket is ready to be used.

\n

Triggered immediately after 'connect'.

" }, { "textRaw": "Event: `'timeout'`", "type": "event", "name": "timeout", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "params": [], "desc": "

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.

\n

See also: socket.setTimeout().

" } ], "methods": [ { "textRaw": "`socket.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

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' }

" }, { "textRaw": "`socket.connect()`", "type": "method", "name": "connect", "signatures": [ { "params": [] } ], "desc": "

Initiate a connection on a given socket.

\n

Possible signatures:

\n\n

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.

\n

This function should only be used for reconnecting a socket after\n'close' has been emitted or otherwise it may lead to undefined\nbehavior.

", "methods": [ { "textRaw": "`socket.connect(options[, connectListener])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v12.10.0", "pr-url": "https://github.com/nodejs/node/pull/25436", "description": "Added `onread` option." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6021", "description": "The `hints` option defaults to `0` in all cases now. Previously, in the absence of the `family` option it would default to `dns.ADDRCONFIG | dns.V4MAPPED`." }, { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/6000", "description": "The `hints` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object" }, { "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", "name": "connectListener", "type": "Function", "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." } ] } ], "desc": "

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.

\n

For TCP connections, available options are:

\n
    \n
  • port <number> Required. Port the socket should connect to.
  • \n
  • host <string> Host the socket should connect to. Default: 'localhost'.
  • \n
  • localAddress <string> Local address the socket should connect from.
  • \n
  • localPort <number> Local port the socket should connect from.
  • \n
  • 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.
  • \n
  • hints <number> Optional dns.lookup() hints.
  • \n
  • lookup <Function> Custom lookup function. Default: dns.lookup().
  • \n
\n

For IPC connections, available options are:

\n\n

For both types, available options include:

\n
    \n
  • onread <Object> If specified, incoming data is stored in a single buffer\nand passed to the supplied callback when data arrives on the socket.\nThis will cause the streaming functionality to not provide any data.\nThe socket will emit events like 'error', 'end', and 'close'\nas usual. Methods like pause() and resume() will also behave as\nexpected.\n
      \n
    • buffer <Buffer> | <Uint8Array> | <Function> Either a reusable chunk of memory to\nuse for storing incoming data or a function that returns such.
    • \n
    • callback <Function> This function is called for every chunk of incoming\ndata. Two arguments are passed to it: the number of bytes written to\nbuffer and a reference to buffer. Return false from this function to\nimplicitly pause() the socket. This function will be executed in the\nglobal context.
    • \n
    \n
  • \n
\n

Following is an example of a client using the onread option:

\n
const net = require('net');\nnet.connect({\n  port: 80,\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": "`socket.connect(path[, connectListener])`", "type": "method", "name": "connect", "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`path` {string} Path the client should connect to. See [Identifying paths for IPC connections][].", "name": "path", "type": "string", "desc": "Path the client should connect to. See [Identifying paths for IPC connections][]." }, { "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", "name": "connectListener", "type": "Function", "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." } ] } ], "desc": "

Initiate an IPC connection on the given socket.

\n

Alias to\nsocket.connect(options[, connectListener])\ncalled with { path: path } as options.

" }, { "textRaw": "`socket.connect(port[, host][, connectListener])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`port` {number} Port the client should connect to.", "name": "port", "type": "number", "desc": "Port the client should connect to." }, { "textRaw": "`host` {string} Host the client should connect to.", "name": "host", "type": "string", "desc": "Host the client should connect to." }, { "textRaw": "`connectListener` {Function} Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once.", "name": "connectListener", "type": "Function", "desc": "Common parameter of [`socket.connect()`][] methods. Will be added as a listener for the [`'connect'`][] event once." } ] } ], "desc": "

Initiate a TCP connection on the given socket.

\n

Alias to\nsocket.connect(options[, connectListener])\ncalled with {port: port, host: host} as options.

" } ] }, { "textRaw": "`socket.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "params": [ { "textRaw": "`error` {Object}", "name": "error", "type": "Object" } ] } ], "desc": "

Ensures that no more I/O activity happens on this socket.\nDestroys the stream and closes the connection.

\n

See writable.destroy() for further details.

" }, { "textRaw": "`socket.end([data[, encoding]][, callback])`", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`data` {string|Buffer|Uint8Array}", "name": "data", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `'utf8'`.", "name": "encoding", "type": "string", "default": "`'utf8'`", "desc": "Only used when data is `string`." }, { "textRaw": "`callback` {Function} Optional callback for when the socket is finished.", "name": "callback", "type": "Function", "desc": "Optional callback for when the socket is finished." } ] } ], "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.

\n

See writable.end() for further details.

" }, { "textRaw": "`socket.pause()`", "type": "method", "name": "pause", "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] } ], "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.

" }, { "textRaw": "`socket.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] } ], "desc": "

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.

" }, { "textRaw": "`socket.resume()`", "type": "method", "name": "resume", "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] } ], "desc": "

Resumes reading after a call to socket.pause().

" }, { "textRaw": "`socket.setEncoding([encoding])`", "type": "method", "name": "setEncoding", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string" } ] } ], "desc": "

Set the encoding for the socket as a Readable Stream. See\nreadable.setEncoding() for more information.

" }, { "textRaw": "`socket.setKeepAlive([enable][, initialDelay])`", "type": "method", "name": "setKeepAlive", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32204", "description": "New defaults for `TCP_KEEPCNT` and `TCP_KEEPINTVL` socket options were added." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`enable` {boolean} **Default:** `false`", "name": "enable", "type": "boolean", "default": "`false`" }, { "textRaw": "`initialDelay` {number} **Default:** `0`", "name": "initialDelay", "type": "number", "default": "`0`" } ] } ], "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.

\n

Set 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.

\n

Enabling the keep-alive functionality will set the following socket options:

\n
    \n
  • SO_KEEPALIVE=1
  • \n
  • TCP_KEEPIDLE=initialDelay
  • \n
  • TCP_KEEPCNT=10
  • \n
  • TCP_KEEPINTVL=1
  • \n
" }, { "textRaw": "`socket.setNoDelay([noDelay])`", "type": "method", "name": "setNoDelay", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`noDelay` {boolean} **Default:** `true`", "name": "noDelay", "type": "boolean", "default": "`true`" } ] } ], "desc": "

Enable/disable the use of Nagle's algorithm.

\n

When a TCP connection is created, it will have Nagle's algorithm enabled.

\n

Nagle's algorithm delays data before it is sent via the network. It attempts\nto optimize throughput at the expense of latency.

\n

Passing 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.

" }, { "textRaw": "`socket.setTimeout(timeout[, callback])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "textRaw": "`timeout` {number}", "name": "timeout", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.

\n

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.

\n
socket.setTimeout(3000);\nsocket.on('timeout', () => {\n  console.log('socket timeout');\n  socket.end();\n});\n
\n

If timeout is 0, then the existing idle timeout is disabled.

\n

The optional callback parameter will be added as a one-time listener for the\n'timeout' event.

" }, { "textRaw": "`socket.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself.", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] } ], "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.

" }, { "textRaw": "`socket.write(data[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`data` {string|Buffer|Uint8Array}", "name": "data", "type": "string|Buffer|Uint8Array" }, { "textRaw": "`encoding` {string} Only used when data is `string`. **Default:** `utf8`.", "name": "encoding", "type": "string", "default": "`utf8`", "desc": "Only used when data is `string`." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string. It defaults to UTF8 encoding.

\n

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 again free.

\n

The optional callback parameter will be executed when the data is finally\nwritten out, which may not be immediately.

\n

See Writable stream write() method for more\ninformation.

" } ], "properties": [ { "textRaw": "`bufferSize` {integer}", "type": "integer", "name": "bufferSize", "meta": { "added": [ "v0.3.8" ], "deprecated": [ "v14.6.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`writable.writableLength`][] instead.", "desc": "

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.

\n

net.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.

\n

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().

" }, { "textRaw": "`bytesRead` {integer}", "type": "integer", "name": "bytesRead", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "

The amount of received bytes.

" }, { "textRaw": "`bytesWritten` {integer}", "type": "integer", "name": "bytesWritten", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "desc": "

The amount of bytes sent.

" }, { "textRaw": "`connecting` {boolean}", "type": "boolean", "name": "connecting", "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.

" }, { "textRaw": "`destroyed` {boolean} Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.", "type": "boolean", "name": "destroyed", "desc": "

See writable.destroyed for further details.

", "shortDesc": "Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it." }, { "textRaw": "`localAddress` {string}", "type": "string", "name": "localAddress", "meta": { "added": [ "v0.9.6" ], "changes": [] }, "desc": "

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'.

" }, { "textRaw": "`localPort` {integer}", "type": "integer", "name": "localPort", "meta": { "added": [ "v0.9.6" ], "changes": [] }, "desc": "

The numeric representation of the local port. For example, 80 or 21.

" }, { "textRaw": "`pending` {boolean}", "type": "boolean", "name": "pending", "meta": { "added": [ "v11.2.0", "v10.16.0" ], "changes": [] }, "desc": "

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).

" }, { "textRaw": "`remoteAddress` {string}", "type": "string", "name": "remoteAddress", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "desc": "

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).

" }, { "textRaw": "`remoteFamily` {string}", "type": "string", "name": "remoteFamily", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "

The string representation of the remote IP family. 'IPv4' or 'IPv6'.

" }, { "textRaw": "`remotePort` {integer}", "type": "integer", "name": "remotePort", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "desc": "

The numeric representation of the remote port. For example, 80 or 21.

" }, { "textRaw": "`timeout` {number|undefined}", "type": "number|undefined", "name": "timeout", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "desc": "

The socket timeout in milliseconds as set by socket.setTimeout().\nIt is undefined if a timeout has not been set.

" }, { "textRaw": "`readyState` {string}", "type": "string", "name": "readyState", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

This property represents the state of the connection as a string.

\n
    \n
  • If the stream is connecting socket.readyState is opening.
  • \n
  • If the stream is readable and writable, it is open.
  • \n
  • If the stream is readable and not writable, it is readOnly.
  • \n
  • If the stream is not readable and writable, it is writeOnly.
  • \n
" } ], "signatures": [ { "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "params": [ { "textRaw": "`options` {Object} Available options are:", "name": "options", "type": "Object", "desc": "Available options are:", "options": [ { "textRaw": "`fd` {number} If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.", "name": "fd", "type": "number", "desc": "If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created." }, { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the socket will automatically end the writable side when the readable side ends. See [`net.createServer()`][] and the [`'end'`][] event for details. **Default:** `false`.", "name": "allowHalfOpen", "type": "boolean", "default": "`false`", "desc": "If set to `false`, then the socket will automatically end the writable side when the readable side ends. See [`net.createServer()`][] and the [`'end'`][] event for details." }, { "textRaw": "`readable` {boolean} Allow reads on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", "name": "readable", "type": "boolean", "default": "`false`", "desc": "Allow reads on the socket when an `fd` is passed, otherwise ignored." }, { "textRaw": "`writable` {boolean} Allow writes on the socket when an `fd` is passed, otherwise ignored. **Default:** `false`.", "name": "writable", "type": "boolean", "default": "`false`", "desc": "Allow writes on the socket when an `fd` is passed, otherwise ignored." }, { "textRaw": "`signal` {AbortSignal} An Abort signal that may be used to destroy the socket.", "name": "signal", "type": "AbortSignal", "desc": "An Abort signal that may be used to destroy the socket." } ] } ], "desc": "

Creates a new socket object.

\n

The newly created socket can be either a TCP socket or a streaming IPC\nendpoint, depending on what it connect() to.

" } ] } ], "methods": [ { "textRaw": "`net.connect()`", "type": "method", "name": "connect", "signatures": [ { "params": [] } ], "desc": "

Aliases to\nnet.createConnection().

\n

Possible signatures:

\n", "methods": [ { "textRaw": "`net.connect(options[, connectListener])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object" }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function" } ] } ], "desc": "

Alias to\nnet.createConnection(options[, connectListener]).

" }, { "textRaw": "`net.connect(path[, connectListener])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function" } ] } ], "desc": "

Alias to\nnet.createConnection(path[, connectListener]).

" }, { "textRaw": "`net.connect(port[, host][, connectListener])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket}", "name": "return", "type": "net.Socket" }, "params": [ { "textRaw": "`port` {number}", "name": "port", "type": "number" }, { "textRaw": "`host` {string}", "name": "host", "type": "string" }, { "textRaw": "`connectListener` {Function}", "name": "connectListener", "type": "Function" } ] } ], "desc": "

Alias to\nnet.createConnection(port[, host][, connectListener]).

" } ] }, { "textRaw": "`net.createConnection()`", "type": "method", "name": "createConnection", "signatures": [ { "params": [] } ], "desc": "

A factory function, which creates a new net.Socket,\nimmediately initiates connection with socket.connect(),\nthen returns the net.Socket that starts the connection.

\n

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.

\n

Possible signatures:

\n\n

The net.connect() function is an alias to this function.

", "methods": [ { "textRaw": "`net.createConnection(options[, connectListener])`", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`options` {Object} Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method.", "name": "options", "type": "Object", "desc": "Required. Will be passed to both the [`new net.Socket([options])`][`new net.Socket(options)`] call and the [`socket.connect(options[, connectListener])`][`socket.connect(options)`] method." }, { "textRaw": "`connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once.", "name": "connectListener", "type": "Function", "desc": "Common parameter of the [`net.createConnection()`][] functions. If supplied, will be added as a listener for the [`'connect'`][] event on the returned socket once." } ] } ], "desc": "

For available options, see\nnew net.Socket([options])\nand socket.connect(options[, connectListener]).

\n

Additional options:

\n\n

Following is an example of a client of the echo server described\nin the net.createServer() section:

\n
const net = require('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
\n

To connect on the socket /tmp/echo.sock:

\n
const client = net.createConnection({ path: '/tmp/echo.sock' });\n
" }, { "textRaw": "`net.createConnection(path[, connectListener])`", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`path` {string} Path the socket should connect to. Will be passed to [`socket.connect(path[, connectListener])`][`socket.connect(path)`]. 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])`][`socket.connect(path)`]. 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])`][`socket.connect(path)`].", "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])`][`socket.connect(path)`]." } ] } ], "desc": "

Initiates an IPC connection.

\n

This 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.

" }, { "textRaw": "`net.createConnection(port[, host][, connectListener])`", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ], "changes": [] }, "signatures": [ { "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." }, "params": [ { "textRaw": "`port` {number} Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].", "name": "port", "type": "number", "desc": "Port the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." }, { "textRaw": "`host` {string} Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. **Default:** `'localhost'`.", "name": "host", "type": "string", "default": "`'localhost'`", "desc": "Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]." }, { "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(port[, host][, connectListener])`][`socket.connect(port)`].", "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(port[, host][, connectListener])`][`socket.connect(port)`]." } ] } ], "desc": "

Initiates a TCP connection.

\n

This 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.

" } ] }, { "textRaw": "`net.createServer([options][, connectionListener])`", "type": "method", "name": "createServer", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server}", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the socket will automatically end the writable side when the readable side ends. **Default:** `false`.", "name": "allowHalfOpen", "type": "boolean", "default": "`false`", "desc": "If set to `false`, then the socket will automatically end the writable side when the readable side ends." }, { "textRaw": "`pauseOnConnect` {boolean} Indicates whether the socket should be paused on incoming connections. **Default:** `false`.", "name": "pauseOnConnect", "type": "boolean", "default": "`false`", "desc": "Indicates whether the socket should be paused on incoming connections." } ] }, { "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." } ] } ], "desc": "

Creates a new TCP or IPC server.

\n

If 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.

\n

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().

\n

The server can be a TCP server or an IPC server, depending on what it\nlisten() to.

\n

Here is an example of an TCP echo server which listens for connections\non port 8124:

\n
const net = require('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
\n

Test this by using telnet:

\n
$ telnet localhost 8124\n
\n

To listen on the socket /tmp/echo.sock:

\n
server.listen('/tmp/echo.sock', () => {\n  console.log('server bound');\n});\n
\n

Use nc to connect to a Unix domain socket server:

\n
$ nc -U /tmp/echo.sock\n
" }, { "textRaw": "`net.isIP(input)`", "type": "method", "name": "isIP", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [ { "textRaw": "`input` {string}", "name": "input", "type": "string" } ] } ], "desc": "

Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6\naddresses.

" }, { "textRaw": "`net.isIPv4(input)`", "type": "method", "name": "isIPv4", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`input` {string}", "name": "input", "type": "string" } ] } ], "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.

" }, { "textRaw": "`net.isIPv6(input)`", "type": "method", "name": "isIPv6", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`input` {string}", "name": "input", "type": "string" } ] } ], "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.

" } ], "type": "module", "displayName": "Net", "source": "doc/api/net.md" }, { "textRaw": "OS", "name": "os", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/os.js

\n

The os module provides operating system-related utility methods and\nproperties. It can be accessed using:

\n
const os = require('os');\n
", "properties": [ { "textRaw": "`EOL` {string}", "type": "string", "name": "EOL", "meta": { "added": [ "v0.7.8" ], "changes": [] }, "desc": "

The operating system-specific end-of-line marker.

\n
    \n
  • \\n on POSIX
  • \n
  • \\r\\n on Windows
  • \n
" }, { "textRaw": "`constants` {Object}", "type": "Object", "name": "constants", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "

Contains commonly used operating system-specific constants for error codes,\nprocess signals, and so on. The specific constants defined are described in\nOS constants.

" }, { "textRaw": "`devNull` {string}", "type": "string", "name": "devNull", "meta": { "added": [ "v16.3.0" ], "changes": [] }, "desc": "

The platform-specific file path of the null device.

\n
    \n
  • \\\\.\\nul on Windows
  • \n
  • /dev/null on POSIX
  • \n
" } ], "methods": [ { "textRaw": "`os.arch()`", "type": "method", "name": "arch", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the operating system CPU architecture for which the Node.js binary was\ncompiled. Possible values are 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n

The return value is equivalent to process.arch.

" }, { "textRaw": "`os.cpus()`", "type": "method", "name": "cpus", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object[]}", "name": "return", "type": "Object[]" }, "params": [] } ], "desc": "

Returns an array of objects containing information about each logical CPU core.

\n

The properties included on each object include:

\n
    \n
  • model <string>
  • \n
  • speed <number> (in MHz)
  • \n
  • times <Object>\n
      \n
    • user <number> The number of milliseconds the CPU has spent in user mode.
    • \n
    • nice <number> The number of milliseconds the CPU has spent in nice mode.
    • \n
    • sys <number> The number of milliseconds the CPU has spent in sys mode.
    • \n
    • idle <number> The number of milliseconds the CPU has spent in idle mode.
    • \n
    • irq <number> The number of milliseconds the CPU has spent in irq mode.
    • \n
    \n
  • \n
\n\n
[\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
\n

nice values are POSIX-only. On Windows, the nice values of all processors\nare always 0.

" }, { "textRaw": "`os.endianness()`", "type": "method", "name": "endianness", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns a string identifying the endianness of the CPU for which the Node.js\nbinary was compiled.

\n

Possible values are 'BE' for big endian and 'LE' for little endian.

" }, { "textRaw": "`os.freemem()`", "type": "method", "name": "freemem", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns the amount of free system memory in bytes as an integer.

" }, { "textRaw": "`os.getPriority([pid])`", "type": "method", "name": "getPriority", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "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." } ] } ], "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.

" }, { "textRaw": "`os.homedir()`", "type": "method", "name": "homedir", "meta": { "added": [ "v2.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the string path of the current user's home directory.

\n

On POSIX, it uses the $HOME environment variable if defined. Otherwise it\nuses the effective UID to look up the user's home directory.

\n

On Windows, it uses the USERPROFILE environment variable if defined.\nOtherwise it uses the path to the profile directory of the current user.

" }, { "textRaw": "`os.hostname()`", "type": "method", "name": "hostname", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the host name of the operating system as a string.

" }, { "textRaw": "`os.loadavg()`", "type": "method", "name": "loadavg", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number[]}", "name": "return", "type": "number[]" }, "params": [] } ], "desc": "

Returns an array containing the 1, 5, and 15 minute load averages.

\n

The load average is a measure of system activity calculated by the operating\nsystem and expressed as a fractional number.

\n

The load average is a Unix-specific concept. On Windows, the return value is\nalways [0, 0, 0].

" }, { "textRaw": "`os.networkInterfaces()`", "type": "method", "name": "networkInterfaces", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object containing network interfaces that have been assigned a\nnetwork address.

\n

Each key on the returned object identifies a network interface. The associated\nvalue is an array of objects that each describe an assigned network address.

\n

The properties available on the assigned network address object include:

\n
    \n
  • address <string> The assigned IPv4 or IPv6 address
  • \n
  • netmask <string> The IPv4 or IPv6 network mask
  • \n
  • family <string> Either IPv4 or IPv6
  • \n
  • mac <string> The MAC address of the network interface
  • \n
  • internal <boolean> true if the network interface is a loopback or\nsimilar interface that is not remotely accessible; otherwise false
  • \n
  • scopeid <number> The numeric IPv6 scope ID (only specified when family\nis IPv6)
  • \n
  • 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
\n\n
{\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()`", "type": "method", "name": "platform", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns a string identifying the operating system platform. The value is set\nat compile time. Possible values are 'aix', 'darwin', 'freebsd',\n'linux', 'openbsd', 'sunos', and 'win32'.

\n

The return value is equivalent to process.platform.

\n

The value 'android' may also be returned if Node.js is built on the Android\noperating system. Android support is experimental.

" }, { "textRaw": "`os.release()`", "type": "method", "name": "release", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the operating system as a string.

\n

On 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.

" }, { "textRaw": "`os.setPriority([pid, ]priority)`", "type": "method", "name": "setPriority", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`pid` {integer} The process ID to set scheduling priority for. **Default:** `0`.", "name": "pid", "type": "integer", "default": "`0`", "desc": "The process ID to set scheduling priority for." }, { "textRaw": "`priority` {integer} The scheduling priority to assign to the process.", "name": "priority", "type": "integer", "desc": "The scheduling priority to assign to the process." } ] } ], "desc": "

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.

\n

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.

\n

On Windows, setting priority to PRIORITY_HIGHEST requires elevated user\nprivileges. Otherwise the set priority will be silently reduced to\nPRIORITY_HIGH.

" }, { "textRaw": "`os.tmpdir()`", "type": "method", "name": "tmpdir", "meta": { "added": [ "v0.9.9" ], "changes": [ { "version": "v2.0.0", "pr-url": "https://github.com/nodejs/node/pull/747", "description": "This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the operating system's default directory for temporary files as a\nstring.

" }, { "textRaw": "`os.totalmem()`", "type": "method", "name": "totalmem", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns the total amount of system memory in bytes as an integer.

" }, { "textRaw": "`os.type()`", "type": "method", "name": "type", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "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.

\n

See https://en.wikipedia.org/wiki/Uname#Examples for additional information\nabout the output of running uname(3) on various operating systems.

" }, { "textRaw": "`os.uptime()`", "type": "method", "name": "uptime", "meta": { "added": [ "v0.3.3" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/20129", "description": "The result of this function no longer contains a fraction component on Windows." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns the system uptime in number of seconds.

" }, { "textRaw": "`os.userInfo([options])`", "type": "method", "name": "userInfo", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "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." } ] } ] } ], "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.

\n

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.

\n

Throws a SystemError if a user has no username or homedir.

" }, { "textRaw": "`os.version()`", "type": "method", "name": "version", "meta": { "added": [ "v13.11.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns a string identifying the kernel version.

\n

On 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.

" } ], "modules": [ { "textRaw": "OS constants", "name": "os_constants", "desc": "

The following constants are exported by os.constants.

\n

Not all constants will be available on every operating system.

", "modules": [ { "textRaw": "Signal constants", "name": "signal_constants", "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.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
SIGHUPSent to indicate when a controlling terminal is closed or a parent\n process exits.
SIGINTSent to indicate when a user wishes to interrupt a process\n (Ctrl+C).
SIGQUITSent to indicate when a user wishes to terminate a process and perform a\n core dump.
SIGILLSent to a process to notify that it has attempted to perform an illegal,\n malformed, unknown, or privileged instruction.
SIGTRAPSent to a process when an exception has occurred.
SIGABRTSent to a process to request that it abort.
SIGIOTSynonym for SIGABRT
SIGBUSSent to a process to notify that it has caused a bus error.
SIGFPESent to a process to notify that it has performed an illegal arithmetic\n operation.
SIGKILLSent to a process to terminate it immediately.
SIGUSR1 SIGUSR2Sent to a process to identify user-defined conditions.
SIGSEGVSent to a process to notify of a segmentation fault.
SIGPIPESent to a process when it has attempted to write to a disconnected\n pipe.
SIGALRMSent to a process when a system timer elapses.
SIGTERMSent to a process to request termination.
SIGCHLDSent to a process when a child process terminates.
SIGSTKFLTSent to a process to indicate a stack fault on a coprocessor.
SIGCONTSent to instruct the operating system to continue a paused process.
SIGSTOPSent to instruct the operating system to halt a process.
SIGTSTPSent to a process to request it to stop.
SIGBREAKSent to indicate when a user wishes to interrupt a process.
SIGTTINSent to a process when it reads from the TTY while in the\n background.
SIGTTOUSent to a process when it writes to the TTY while in the\n background.
SIGURGSent to a process when a socket has urgent data to read.
SIGXCPUSent to a process when it has exceeded its limit on CPU usage.
SIGXFSZSent to a process when it grows a file larger than the maximum\n allowed.
SIGVTALRMSent to a process when a virtual timer has elapsed.
SIGPROFSent to a process when a system timer has elapsed.
SIGWINCHSent to a process when the controlling terminal has changed its\n size.
SIGIOSent to a process when I/O is available.
SIGPOLLSynonym for SIGIO
SIGLOSTSent to a process when a file lock has been lost.
SIGPWRSent to a process to notify of a power failure.
SIGINFOSynonym for SIGPWR
SIGSYSSent to a process to notify of a bad argument.
SIGUNUSEDSynonym for SIGSYS
", "type": "module", "displayName": "Signal constants" }, { "textRaw": "Error constants", "name": "error_constants", "desc": "

The following error constants are exported by os.constants.errno.

", "modules": [ { "textRaw": "POSIX error constants", "name": "posix_error_constants", "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 \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
E2BIGIndicates that the list of arguments is longer than expected.
EACCESIndicates that the operation did not have sufficient permissions.
EADDRINUSEIndicates that the network address is already in use.
EADDRNOTAVAILIndicates that the network address is currently unavailable for\n use.
EAFNOSUPPORTIndicates that the network address family is not supported.
EAGAINIndicates that there is no data available and to try the\n operation again later.
EALREADYIndicates that the socket already has a pending connection in\n progress.
EBADFIndicates that a file descriptor is not valid.
EBADMSGIndicates an invalid data message.
EBUSYIndicates that a device or resource is busy.
ECANCELEDIndicates that an operation was canceled.
ECHILDIndicates that there are no child processes.
ECONNABORTEDIndicates that the network connection has been aborted.
ECONNREFUSEDIndicates that the network connection has been refused.
ECONNRESETIndicates that the network connection has been reset.
EDEADLKIndicates that a resource deadlock has been avoided.
EDESTADDRREQIndicates that a destination address is required.
EDOMIndicates that an argument is out of the domain of the function.
EDQUOTIndicates that the disk quota has been exceeded.
EEXISTIndicates that the file already exists.
EFAULTIndicates an invalid pointer address.
EFBIGIndicates that the file is too large.
EHOSTUNREACHIndicates that the host is unreachable.
EIDRMIndicates that the identifier has been removed.
EILSEQIndicates an illegal byte sequence.
EINPROGRESSIndicates that an operation is already in progress.
EINTRIndicates that a function call was interrupted.
EINVALIndicates that an invalid argument was provided.
EIOIndicates an otherwise unspecified I/O error.
EISCONNIndicates that the socket is connected.
EISDIRIndicates that the path is a directory.
ELOOPIndicates too many levels of symbolic links in a path.
EMFILEIndicates that there are too many open files.
EMLINKIndicates that there are too many hard links to a file.
EMSGSIZEIndicates that the provided message is too long.
EMULTIHOPIndicates that a multihop was attempted.
ENAMETOOLONGIndicates that the filename is too long.
ENETDOWNIndicates that the network is down.
ENETRESETIndicates that the connection has been aborted by the network.
ENETUNREACHIndicates that the network is unreachable.
ENFILEIndicates too many open files in the system.
ENOBUFSIndicates that no buffer space is available.
ENODATAIndicates that no message is available on the stream head read\n queue.
ENODEVIndicates that there is no such device.
ENOENTIndicates that there is no such file or directory.
ENOEXECIndicates an exec format error.
ENOLCKIndicates that there are no locks available.
ENOLINKIndications that a link has been severed.
ENOMEMIndicates that there is not enough space.
ENOMSGIndicates that there is no message of the desired type.
ENOPROTOOPTIndicates that a given protocol is not available.
ENOSPCIndicates that there is no space available on the device.
ENOSRIndicates that there are no stream resources available.
ENOSTRIndicates that a given resource is not a stream.
ENOSYSIndicates that a function has not been implemented.
ENOTCONNIndicates that the socket is not connected.
ENOTDIRIndicates that the path is not a directory.
ENOTEMPTYIndicates that the directory is not empty.
ENOTSOCKIndicates that the given item is not a socket.
ENOTSUPIndicates that a given operation is not supported.
ENOTTYIndicates an inappropriate I/O control operation.
ENXIOIndicates no such device or address.
EOPNOTSUPPIndicates 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.)
EOVERFLOWIndicates that a value is too large to be stored in a given data\n type.
EPERMIndicates that the operation is not permitted.
EPIPEIndicates a broken pipe.
EPROTOIndicates a protocol error.
EPROTONOSUPPORTIndicates that a protocol is not supported.
EPROTOTYPEIndicates the wrong type of protocol for a socket.
ERANGEIndicates that the results are too large.
EROFSIndicates that the file system is read only.
ESPIPEIndicates an invalid seek operation.
ESRCHIndicates that there is no such process.
ESTALEIndicates that the file handle is stale.
ETIMEIndicates an expired timer.
ETIMEDOUTIndicates that the connection timed out.
ETXTBSYIndicates that a text file is busy.
EWOULDBLOCKIndicates that the operation would block.
EXDEVIndicates an improper link.\n
", "type": "module", "displayName": "POSIX error constants" }, { "textRaw": "Windows-specific error constants", "name": "windows-specific_error_constants", "desc": "

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
ConstantDescription
WSAEINTRIndicates an interrupted function call.
WSAEBADFIndicates an invalid file handle.
WSAEACCESIndicates insufficient permissions to complete the operation.
WSAEFAULTIndicates an invalid pointer address.
WSAEINVALIndicates that an invalid argument was passed.
WSAEMFILEIndicates that there are too many open files.
WSAEWOULDBLOCKIndicates that a resource is temporarily unavailable.
WSAEINPROGRESSIndicates that an operation is currently in progress.
WSAEALREADYIndicates that an operation is already in progress.
WSAENOTSOCKIndicates that the resource is not a socket.
WSAEDESTADDRREQIndicates that a destination address is required.
WSAEMSGSIZEIndicates that the message size is too long.
WSAEPROTOTYPEIndicates the wrong protocol type for the socket.
WSAENOPROTOOPTIndicates a bad protocol option.
WSAEPROTONOSUPPORTIndicates that the protocol is not supported.
WSAESOCKTNOSUPPORTIndicates that the socket type is not supported.
WSAEOPNOTSUPPIndicates that the operation is not supported.
WSAEPFNOSUPPORTIndicates that the protocol family is not supported.
WSAEAFNOSUPPORTIndicates that the address family is not supported.
WSAEADDRINUSEIndicates that the network address is already in use.
WSAEADDRNOTAVAILIndicates that the network address is not available.
WSAENETDOWNIndicates that the network is down.
WSAENETUNREACHIndicates that the network is unreachable.
WSAENETRESETIndicates that the network connection has been reset.
WSAECONNABORTEDIndicates that the connection has been aborted.
WSAECONNRESETIndicates that the connection has been reset by the peer.
WSAENOBUFSIndicates that there is no buffer space available.
WSAEISCONNIndicates that the socket is already connected.
WSAENOTCONNIndicates that the socket is not connected.
WSAESHUTDOWNIndicates that data cannot be sent after the socket has been\n shutdown.
WSAETOOMANYREFSIndicates that there are too many references.
WSAETIMEDOUTIndicates that the connection has timed out.
WSAECONNREFUSEDIndicates that the connection has been refused.
WSAELOOPIndicates that a name cannot be translated.
WSAENAMETOOLONGIndicates that a name was too long.
WSAEHOSTDOWNIndicates that a network host is down.
WSAEHOSTUNREACHIndicates that there is no route to a network host.
WSAENOTEMPTYIndicates that the directory is not empty.
WSAEPROCLIMIndicates that there are too many processes.
WSAEUSERSIndicates that the user quota has been exceeded.
WSAEDQUOTIndicates that the disk quota has been exceeded.
WSAESTALEIndicates a stale file handle reference.
WSAEREMOTEIndicates that the item is remote.
WSASYSNOTREADYIndicates that the network subsystem is not ready.
WSAVERNOTSUPPORTEDIndicates that the winsock.dll version is out of\n range.
WSANOTINITIALISEDIndicates that successful WSAStartup has not yet been performed.
WSAEDISCONIndicates that a graceful shutdown is in progress.
WSAENOMOREIndicates that there are no more results.
WSAECANCELLEDIndicates that an operation has been canceled.
WSAEINVALIDPROCTABLEIndicates that the procedure call table is invalid.
WSAEINVALIDPROVIDERIndicates an invalid service provider.
WSAEPROVIDERFAILEDINITIndicates that the service provider failed to initialized.
WSASYSCALLFAILUREIndicates a system call failure.
WSASERVICE_NOT_FOUNDIndicates that a service was not found.
WSATYPE_NOT_FOUNDIndicates that a class type was not found.
WSA_E_NO_MOREIndicates that there are no more results.
WSA_E_CANCELLEDIndicates that the call was canceled.
WSAEREFUSEDIndicates that a database query was refused.
", "type": "module", "displayName": "Windows-specific error constants" } ], "type": "module", "displayName": "Error constants" }, { "textRaw": "dlopen constants", "name": "dlopen_constants", "desc": "

If available on the operating system, the following constants\nare exported in os.constants.dlopen. See dlopen(3) for detailed\ninformation.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
RTLD_LAZYPerform lazy binding. Node.js sets this flag by default.
RTLD_NOWResolve all undefined symbols in the library before dlopen(3)\n returns.
RTLD_GLOBALSymbols defined by the library will be made available for symbol\n resolution of subsequently loaded libraries.
RTLD_LOCALThe converse of RTLD_GLOBAL. This is the default behavior\n if neither flag is specified.
RTLD_DEEPBINDMake a self-contained library use its own symbols in preference to\n symbols from previously loaded libraries.
", "type": "module", "displayName": "dlopen constants" }, { "textRaw": "Priority constants", "name": "priority_constants", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "desc": "

The following process scheduling constants are exported by\nos.constants.priority.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
PRIORITY_LOWThe 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_NORMALThe 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_NORMALThe 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_NORMALThe 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_HIGHThe 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_HIGHESTThe highest process scheduling priority. This corresponds to\n REALTIME_PRIORITY_CLASS on Windows, and a nice value of\n -20 on all other platforms.
", "type": "module", "displayName": "Priority constants" }, { "textRaw": "libuv constants", "name": "libuv_constants", "desc": "\n \n \n \n \n \n \n \n \n
ConstantDescription
UV_UDP_REUSEADDR
", "type": "module", "displayName": "libuv constants" } ], "type": "module", "displayName": "OS constants" } ], "type": "module", "displayName": "OS", "source": "doc/api/os.md" }, { "textRaw": "Path", "name": "path", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/path.js

\n

The path module provides utilities for working with file and directory paths.\nIt can be accessed using:

\n
const path = require('path');\n
", "modules": [ { "textRaw": "Windows vs. POSIX", "name": "windows_vs._posix", "desc": "

The default operation of the path module varies based on the operating system\non which a Node.js application is running. Specifically, when running on a\nWindows operating system, the path module will assume that Windows-style\npaths are being used.

\n

So using path.basename() might yield different results on POSIX and Windows:

\n

On POSIX:

\n
path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'C:\\\\temp\\\\myfile.html'\n
\n

On Windows:

\n
path.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
\n

To achieve consistent results when working with Windows file paths on any\noperating system, use path.win32:

\n

On POSIX and Windows:

\n
path.win32.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
\n

To achieve consistent results when working with POSIX file paths on any\noperating system, use path.posix:

\n

On POSIX and Windows:

\n
path.posix.basename('/tmp/myfile.html');\n// Returns: 'myfile.html'\n
\n

On 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.

", "type": "module", "displayName": "Windows vs. POSIX" } ], "methods": [ { "textRaw": "`path.basename(path[, ext])`", "type": "method", "name": "basename", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5348", "description": "Passing a non-string as the `path` argument will throw now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" }, { "textRaw": "`ext` {string} An optional file extension", "name": "ext", "type": "string", "desc": "An optional file extension" } ] } ], "desc": "

The path.basename() method returns the last portion of a path, similar to\nthe Unix basename command. Trailing directory separators are ignored, see\npath.sep.

\n
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
\n

Although 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:

\n
path.win32.basename('C:\\\\foo.html', '.html');\n// Returns: 'foo'\n\npath.win32.basename('C:\\\\foo.HTML', '.html');\n// Returns: 'foo.HTML'\n
\n

A TypeError is thrown if path is not a string or if ext is given\nand is not a string.

" }, { "textRaw": "`path.dirname(path)`", "type": "method", "name": "dirname", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5348", "description": "Passing a non-string as the `path` argument will throw now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

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.

\n
path.dirname('/foo/bar/baz/asdf/quux');\n// Returns: '/foo/bar/baz/asdf'\n
\n

A TypeError is thrown if path is not a string.

" }, { "textRaw": "`path.extname(path)`", "type": "method", "name": "extname", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5348", "description": "Passing a non-string as the `path` argument will throw now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

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.

\n
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
\n

A TypeError is thrown if path is not a string.

" }, { "textRaw": "`path.format(pathObject)`", "type": "method", "name": "format", "meta": { "added": [ "v0.11.15" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`pathObject` {Object} Any JavaScript object having the following properties:", "name": "pathObject", "type": "Object", "desc": "Any JavaScript object having the following properties:", "options": [ { "textRaw": "`dir` {string}", "name": "dir", "type": "string" }, { "textRaw": "`root` {string}", "name": "root", "type": "string" }, { "textRaw": "`base` {string}", "name": "base", "type": "string" }, { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`ext` {string}", "name": "ext", "type": "string" } ] } ] } ], "desc": "

The path.format() method returns a path string from an object. This is the\nopposite of path.parse().

\n

When providing properties to the pathObject remember that there are\ncombinations where one property has priority over another:

\n
    \n
  • pathObject.root is ignored if pathObject.dir is provided
  • \n
  • pathObject.ext and pathObject.name are ignored if pathObject.base exists
  • \n
\n

For 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

On Windows:

\n
path.format({\n  dir: 'C:\\\\path\\\\dir',\n  base: 'file.txt'\n});\n// Returns: 'C:\\\\path\\\\dir\\\\file.txt'\n
" }, { "textRaw": "`path.isAbsolute(path)`", "type": "method", "name": "isAbsolute", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

The path.isAbsolute() method determines if path is an absolute path.

\n

If the given path is a zero-length string, false will be returned.

\n

For example, on POSIX:

\n
path.isAbsolute('/foo/bar'); // true\npath.isAbsolute('/baz/..');  // true\npath.isAbsolute('qux/');     // false\npath.isAbsolute('.');        // false\n
\n

On Windows:

\n
path.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
\n

A TypeError is thrown if path is not a string.

" }, { "textRaw": "`path.join([...paths])`", "type": "method", "name": "join", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`...paths` {string} A sequence of path segments", "name": "...paths", "type": "string", "desc": "A sequence of path segments" } ] } ], "desc": "

The path.join() method joins all given path segments together using the\nplatform-specific separator as a delimiter, then normalizes the resulting path.

\n

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.

\n
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
\n

A TypeError is thrown if any of the path segments is not a string.

" }, { "textRaw": "`path.normalize(path)`", "type": "method", "name": "normalize", "meta": { "added": [ "v0.1.23" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

The path.normalize() method normalizes the given path, resolving '..' and\n'.' segments.

\n

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.

\n

If the path is a zero-length string, '.' is returned, representing the\ncurrent working directory.

\n

For example, on POSIX:

\n
path.normalize('/foo/bar//baz/asdf/quux/..');\n// Returns: '/foo/bar/baz/asdf'\n
\n

On Windows:

\n
path.normalize('C:\\\\temp\\\\\\\\foo\\\\bar\\\\..\\\\');\n// Returns: 'C:\\\\temp\\\\foo\\\\'\n
\n

Since Windows recognizes multiple path separators, both separators will be\nreplaced by instances of the Windows preferred separator (\\):

\n
path.win32.normalize('C:////temp\\\\\\\\/\\\\/\\\\/foo/bar');\n// Returns: 'C:\\\\temp\\\\foo\\\\bar'\n
\n

A TypeError is thrown if path is not a string.

" }, { "textRaw": "`path.parse(path)`", "type": "method", "name": "parse", "meta": { "added": [ "v0.11.15" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

The path.parse() method returns an object whose properties represent\nsignificant elements of the path. Trailing directory separators are ignored,\nsee path.sep.

\n

The returned object will have the following properties:

\n\n

For example, on POSIX:

\n
path.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
\n

On Windows:

\n
path.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
\n

A TypeError is thrown if path is not a string.

" }, { "textRaw": "`path.relative(from, to)`", "type": "method", "name": "relative", "meta": { "added": [ "v0.5.0" ], "changes": [ { "version": "v6.8.0", "pr-url": "https://github.com/nodejs/node/pull/8523", "description": "On Windows, the leading slashes for UNC paths are now included in the return value." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`from` {string}", "name": "from", "type": "string" }, { "textRaw": "`to` {string}", "name": "to", "type": "string" } ] } ], "desc": "

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.

\n

If a zero-length string is passed as from or to, the current working\ndirectory will be used instead of the zero-length strings.

\n

For example, on POSIX:

\n
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');\n// Returns: '../../impl/bbb'\n
\n

On Windows:

\n
path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb');\n// Returns: '..\\\\..\\\\impl\\\\bbb'\n
\n

A TypeError is thrown if either from or to is not a string.

" }, { "textRaw": "`path.resolve([...paths])`", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`...paths` {string} A sequence of paths or path segments", "name": "...paths", "type": "string", "desc": "A sequence of paths or path segments" } ] } ], "desc": "

The path.resolve() method resolves a sequence of paths or path segments into\nan absolute path.

\n

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.

\n

If, after processing all given path segments, an absolute path has not yet\nbeen generated, the current working directory is used.

\n

The resulting path is normalized and trailing slashes are removed unless the\npath is resolved to the root directory.

\n

Zero-length path segments are ignored.

\n

If no path segments are passed, path.resolve() will return the absolute path\nof the current working directory.

\n
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
\n

A TypeError is thrown if any of the arguments is not a string.

" }, { "textRaw": "`path.toNamespacedPath(path)`", "type": "method", "name": "toNamespacedPath", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string}", "name": "path", "type": "string" } ] } ], "desc": "

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.

\n

This method is meaningful only on Windows systems. On POSIX systems, the\nmethod is non-operational and always returns path without modifications.

" } ], "properties": [ { "textRaw": "`delimiter` {string}", "type": "string", "name": "delimiter", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "desc": "

Provides the platform-specific path delimiter:

\n
    \n
  • ; for Windows
  • \n
  • : for POSIX
  • \n
\n

For example, on POSIX:

\n
console.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
\n

On Windows:

\n
console.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": "`posix` {Object}", "type": "Object", "name": "posix", "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.

\n

The API is accessible via require('path').posix or require('path/posix').

" }, { "textRaw": "`sep` {string}", "type": "string", "name": "sep", "meta": { "added": [ "v0.7.9" ], "changes": [] }, "desc": "

Provides the platform-specific path segment separator:

\n
    \n
  • \\ on Windows
  • \n
  • / on POSIX
  • \n
\n

For example, on POSIX:

\n
'foo/bar/baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
\n

On Windows:

\n
'foo\\\\bar\\\\baz'.split(path.sep);\n// Returns: ['foo', 'bar', 'baz']\n
\n

On Windows, both the forward slash (/) and backward slash (\\) are accepted\nas path segment separators; however, the path methods only add backward\nslashes (\\).

" }, { "textRaw": "`win32` {Object}", "type": "Object", "name": "win32", "meta": { "added": [ "v0.11.15" ], "changes": [ { "version": "v15.3.0", "pr-url": "https://github.com/nodejs/node/pull/34962", "description": "Exposed as `require('path/win32')`." } ] }, "desc": "

The path.win32 property provides access to Windows-specific implementations\nof the path methods.

\n

The API is accessible via require('path').win32 or require('path/win32').

" } ], "type": "module", "displayName": "Path", "source": "doc/api/path.md" }, { "textRaw": "Performance measurement APIs", "name": "performance_measurement_apis", "introduced_in": "v8.5.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/perf_hooks.js

\n

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.

\n

Node.js supports the following Web Performance APIs:

\n\n
const { PerformanceObserver, performance } = require('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
", "properties": [ { "textRaw": "`perf_hooks.performance`", "name": "performance", "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.

", "methods": [ { "textRaw": "`performance.clearMarks([name])`", "type": "method", "name": "clearMarks", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

If name is not provided, removes all PerformanceMark objects from the\nPerformance Timeline. If name is provided, removes only the named mark.

" }, { "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", "type": "method", "name": "eventLoopUtilization", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`idle` {number}", "name": "idle", "type": "number" }, { "textRaw": "`active` {number}", "name": "active", "type": "number" }, { "textRaw": "`utilization` {number}", "name": "utilization", "type": "number" } ] }, "params": [ { "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", "name": "utilization1", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()`." }, { "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", "name": "utilization2", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." } ] } ], "desc": "

The eventLoopUtilization() method 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).

\n

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.

\n

Both utilization1 and utilization2 are optional parameters.

\n

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()).

\n

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.

\n

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.

\n
'use strict';\nconst { eventLoopUtilization } = require('perf_hooks').performance;\nconst { spawnSync } = require('child_process');\n\nsetImmediate(() => {\n  const elu = eventLoopUtilization();\n  spawnSync('sleep', ['5']);\n  console.log(eventLoopUtilization(elu).utilization);\n});\n
\n

Although 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.

\n

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.

" }, { "textRaw": "`performance.mark([name[, options]])`", "type": "method", "name": "mark", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Updated to conform to the User Timing Level 3 specification." } ] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`detail` {any} Additional optional detail to include with the mark.", "name": "detail", "type": "any", "desc": "Additional optional detail to include with the mark." }, { "textRaw": "`startTime` {number} An optional timestamp to be used as the mark time. **Defaults**: `performance.now()`.", "name": "startTime", "type": "number", "desc": "An optional timestamp to be used as the mark time. **Defaults**: `performance.now()`." } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`performance.measure(name[, startMarkOrOptions[, endMark]])`", "type": "method", "name": "measure", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Updated to conform to the User Timing Level 3 specification." }, { "version": [ "v13.13.0", "v12.16.3" ], "pr-url": "https://github.com/nodejs/node/pull/32651", "description": "Make `startMark` and `endMark` parameters optional." } ] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`startMarkOrOptions` {string|Object} Optional.", "name": "startMarkOrOptions", "type": "string|Object", "desc": "Optional.", "options": [ { "textRaw": "`detail` {any} Additional optional detail to include with the measure.", "name": "detail", "type": "any", "desc": "Additional optional detail to include with the measure." }, { "textRaw": "`duration` {number} Duration between start and end times.", "name": "duration", "type": "number", "desc": "Duration between start and end times." }, { "textRaw": "`end` {number|string} Timestamp to be used as the end time, or a string identifying a previously recorded mark.", "name": "end", "type": "number|string", "desc": "Timestamp to be used as the end time, or a string identifying a previously recorded mark." }, { "textRaw": "`start` {number|string} Timestamp to be used as the start time, or a string identifying a previously recorded mark.", "name": "start", "type": "number|string", "desc": "Timestamp to be used as the start time, or a string identifying a previously recorded mark." } ] }, { "textRaw": "`endMark` {string} Optional. Must be omitted if `startMarkOrOptions` is an {Object}.", "name": "endMark", "type": "string", "desc": "Optional. Must be omitted if `startMarkOrOptions` is an {Object}." } ] } ], "desc": "

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.

\n

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.

\n

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.

" }, { "textRaw": "`performance.now()`", "type": "method", "name": "now", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [] } ], "desc": "

Returns the current high resolution millisecond timestamp, where 0 represents\nthe start of the current node process.

" }, { "textRaw": "`performance.timerify(fn[, options])`", "type": "method", "name": "timerify", "meta": { "added": [ "v8.5.0" ], "changes": [ { "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." } ] } ] } ], "desc": "

This property is an extension by Node.js. It is not available in Web browsers.

\n

Wraps 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.

\n
const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nfunction someFunction() {\n  console.log('hello world');\n}\n\nconst wrapped = performance.timerify(someFunction);\n\nconst obs = new PerformanceObserver((list) => {\n  console.log(list.getEntries()[0].duration);\n  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'] });\n\n// A performance timeline entry will be created\nwrapped();\n
\n

If 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.

" }, { "textRaw": "`performance.toJSON()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v16.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

An object which is JSON representation of the performance object. It\nis similar to window.performance.toJSON in browsers.

" } ], "properties": [ { "textRaw": "`nodeTiming` {PerformanceNodeTiming}", "type": "PerformanceNodeTiming", "name": "nodeTiming", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

This property is an extension by Node.js. It is not available in Web browsers.

\n

An instance of the PerformanceNodeTiming class that provides performance\nmetrics for specific Node.js operational milestones.

" }, { "textRaw": "`timeOrigin` {number}", "type": "number", "name": "timeOrigin", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The timeOrigin specifies the high resolution millisecond timestamp at\nwhich the current node process began, measured in Unix time.

" } ] } ], "classes": [ { "textRaw": "Class: `PerformanceEntry`", "type": "class", "name": "PerformanceEntry", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "properties": [ { "textRaw": "`details` {any}", "type": "any", "name": "details", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "desc": "

Additional detail specific to the entryType.

" }, { "textRaw": "`duration` {number}", "type": "number", "name": "duration", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The total number of milliseconds elapsed for this entry. This value will not\nbe meaningful for all Performance Entry types.

" }, { "textRaw": "`entryType` {string}", "type": "string", "name": "entryType", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The type of the performance entry. It may be one of:

\n
    \n
  • 'node' (Node.js only)
  • \n
  • 'mark' (available on the Web)
  • \n
  • 'measure' (available on the Web)
  • \n
  • 'gc' (Node.js only)
  • \n
  • 'function' (Node.js only)
  • \n
  • 'http2' (Node.js only)
  • \n
  • 'http' (Node.js only)
  • \n
" }, { "textRaw": "`flags` {number}", "type": "number", "name": "flags", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Runtime deprecated. Now moved to the detail property when entryType is 'gc'." } ] }, "desc": "

This property is an extension by Node.js. It is not available in Web browsers.

\n

When performanceEntry.entryType is equal to 'gc', the performance.flags\nproperty contains additional information about garbage collection operation.\nThe value may be one of:

\n
    \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
  • \n
" }, { "textRaw": "`name` {string}", "type": "string", "name": "name", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The name of the performance entry.

" }, { "textRaw": "`kind` {number}", "type": "number", "name": "kind", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Runtime deprecated. Now moved to the detail property when entryType is 'gc'." } ] }, "desc": "

This property is an extension by Node.js. It is not available in Web browsers.

\n

When 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:

\n
    \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
  • \n
  • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
  • \n
" }, { "textRaw": "`startTime` {number}", "type": "number", "name": "startTime", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The high resolution millisecond timestamp marking the starting time of the\nPerformance Entry.

" } ], "modules": [ { "textRaw": "Garbage Collection ('gc') Details", "name": "garbage_collection_('gc')_details", "desc": "

When performanceEntry.type is equal to 'gc', the performanceEntry.details\nproperty will be an <Object> with two properties:

\n
    \n
  • kind <number> One of:\n
      \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB
    • \n
    \n
  • \n
  • flags <number> One of:\n
      \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY
    • \n
    • perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE
    • \n
    \n
  • \n
", "type": "module", "displayName": "Garbage Collection ('gc') Details" }, { "textRaw": "HTTP/2 ('http2') Details", "name": "http/2_('http2')_details", "desc": "

When performanceEntry.type is equal to 'http2', the\nperformanceEntry.details property will be an <Object> containing\nadditional performance information.

\n

If performanceEntry.name is equal to Http2Stream, the details\nwill contain the following properties:

\n
    \n
  • bytesRead <number> The number of DATA frame bytes received for this\nHttp2Stream.
  • \n
  • bytesWritten <number> The number of DATA frame bytes sent for this\nHttp2Stream.
  • \n
  • id <number> The identifier of the associated Http2Stream
  • \n
  • timeToFirstByte <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first DATA frame.
  • \n
  • timeToFirstByteSent <number> The number of milliseconds elapsed between\nthe PerformanceEntry startTime and sending of the first DATA frame.
  • \n
  • timeToFirstHeader <number> The number of milliseconds elapsed between the\nPerformanceEntry startTime and the reception of the first header.
  • \n
\n

If performanceEntry.name is equal to Http2Session, the details will\ncontain the following properties:

\n
    \n
  • bytesRead <number> The number of bytes received for this Http2Session.
  • \n
  • bytesWritten <number> The number of bytes sent for this Http2Session.
  • \n
  • framesReceived <number> The number of HTTP/2 frames received by the\nHttp2Session.
  • \n
  • framesSent <number> The number of HTTP/2 frames sent by the Http2Session.
  • \n
  • maxConcurrentStreams <number> The maximum number of streams concurrently\nopen during the lifetime of the Http2Session.
  • \n
  • 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.
  • \n
  • streamAverageDuration <number> The average duration (in milliseconds) for\nall Http2Stream instances.
  • \n
  • streamCount <number> The number of Http2Stream instances processed by\nthe Http2Session.
  • \n
  • type <string> Either 'server' or 'client' to identify the type of\nHttp2Session.
  • \n
", "type": "module", "displayName": "HTTP/2 ('http2') Details" }, { "textRaw": "Timerify ('function') Details", "name": "timerify_('function')_details", "desc": "

When performanceEntry.type is equal to 'function', the\nperformanceEntry.details property will be an <Array> listing\nthe input arguments to the timed function.

", "type": "module", "displayName": "Timerify ('function') Details" } ] }, { "textRaw": "Class: `PerformanceNodeTiming`", "type": "class", "name": "PerformanceNodeTiming", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "\n

This property is an extension by Node.js. It is not available in Web browsers.

\n

Provides timing details for Node.js itself. The constructor of this class\nis not exposed to users.

", "properties": [ { "textRaw": "`bootstrapComplete` {number}", "type": "number", "name": "bootstrapComplete", "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": "`environment` {number}", "type": "number", "name": "environment", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The high resolution millisecond timestamp at which the Node.js environment was\ninitialized.

" }, { "textRaw": "`idleTime` {number}", "type": "number", "name": "idleTime", "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.

" }, { "textRaw": "`loopExit` {number}", "type": "number", "name": "loopExit", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`loopStart` {number}", "type": "number", "name": "loopStart", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

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": "`nodeStart` {number}", "type": "number", "name": "nodeStart", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The high resolution millisecond timestamp at which the Node.js process was\ninitialized.

" }, { "textRaw": "`v8Start` {number}", "type": "number", "name": "v8Start", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "desc": "

The high resolution millisecond timestamp at which the V8 platform was\ninitialized.

" } ] }, { "textRaw": "Class: `perf_hooks.PerformanceObserver`", "type": "class", "name": "perf_hooks.PerformanceObserver", "methods": [ { "textRaw": "`performanceObserver.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Disconnects the PerformanceObserver instance from all notifications.

" }, { "textRaw": "`performanceObserver.observe(options)`", "type": "method", "name": "observe", "meta": { "added": [ "v8.5.0" ], "changes": [ { "version": "v16.7.0", "pr-url": "https://github.com/nodejs/node/pull/39297", "description": "Updated to conform to Performance Timeline Level 2. The buffered option has been added back." }, { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/37136", "description": "Updated to conform to User Timing Level 3. The buffered option has been removed." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`type` {string} A single {PerformanceEntry} type. Must not be given if `entryTypes` is already specified.", "name": "type", "type": "string", "desc": "A single {PerformanceEntry} type. Must not be given if `entryTypes` is already specified." }, { "textRaw": "`entryTypes` {string[]} An array of strings identifying the types of {PerformanceEntry} instances the observer is interested in. If not provided an error will be thrown.", "name": "entryTypes", "type": "string[]", "desc": "An array of strings identifying the types of {PerformanceEntry} instances the observer is interested in. If not provided an error will be thrown." }, { "textRaw": "`buffered` {boolean} If true, the observer callback is called with a list global `PerformanceEntry` buffered entries. If false, only `PerformanceEntry`s created after the time point are sent to the observer callback. **Default:** `false`.", "name": "buffered", "type": "boolean", "default": "`false`", "desc": "If true, the observer callback is called with a list global `PerformanceEntry` buffered entries. If false, only `PerformanceEntry`s created after the time point are sent to the observer callback." } ] } ] } ], "desc": "

Subscribes the <PerformanceObserver> instance to notifications of new\n<PerformanceEntry> instances identified either by options.entryTypes\nor options.type:

\n
const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  // Called three times synchronously. `list` contains one item.\n});\nobs.observe({ type: 'mark' });\n\nfor (let n = 0; n < 3; n++)\n  performance.mark(`test${n}`);\n
" } ], "signatures": [ { "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.

\n
const {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\n\nconst obs = new PerformanceObserver((list, observer) => {\n  console.log(list.getEntries());\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark'], buffered: true });\n\nperformance.mark('test');\n
\n

Because 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.

\n

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.

" } ] }, { "textRaw": "Class: `PerformanceObserverEntryList`", "type": "class", "name": "PerformanceObserverEntryList", "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.

", "methods": [ { "textRaw": "`performanceObserverEntryList.getEntries()`", "type": "method", "name": "getEntries", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {PerformanceEntry[]}", "name": "return", "type": "PerformanceEntry[]" }, "params": [] } ], "desc": "

Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime.

\n
const {\n  performance,\n  PerformanceObserver\n} = require('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   *   },\n   *   PerformanceEntry {\n   *     name: 'meow',\n   *     entryType: 'mark',\n   *     startTime: 81.860064,\n   *     duration: 0\n   *   }\n   * ]\n   */\n  observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n
" }, { "textRaw": "`performanceObserverEntryList.getEntriesByName(name[, type])`", "type": "method", "name": "getEntriesByName", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {PerformanceEntry[]}", "name": "return", "type": "PerformanceEntry[]" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "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.

\n
const {\n  performance,\n  PerformanceObserver\n} = require('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   *   }\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   *   }\n   * ]\n   */\n  console.log(perfObserverList.getEntriesByName('test', 'measure')); // []\n  observer.disconnect();\n});\nobs.observe({ entryTypes: ['mark', 'measure'] });\n\nperformance.mark('test');\nperformance.mark('meow');\n
" }, { "textRaw": "`performanceObserverEntryList.getEntriesByType(type)`", "type": "method", "name": "getEntriesByType", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {PerformanceEntry[]}", "name": "return", "type": "PerformanceEntry[]" }, "params": [ { "textRaw": "`type` {string}", "name": "type", "type": "string" } ] } ], "desc": "

Returns a list of PerformanceEntry objects in chronological order\nwith respect to performanceEntry.startTime whose performanceEntry.entryType\nis equal to type.

\n
const {\n  performance,\n  PerformanceObserver\n} = require('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   *   },\n   *   PerformanceEntry {\n   *     name: 'meow',\n   *     entryType: 'mark',\n   *     startTime: 56.350146,\n   *     duration: 0\n   *   }\n   * ]\n   */\n  observer.disconnect();\n});\nobs.observe({ type: 'mark' });\n\nperformance.mark('test');\nperformance.mark('meow');\n
" } ] }, { "textRaw": "Class: `Histogram`", "type": "class", "name": "Histogram", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "properties": [ { "textRaw": "`exceeds` {number}", "type": "number", "name": "exceeds", "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": "`max` {number}", "type": "number", "name": "max", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "

The maximum recorded event loop delay.

" }, { "textRaw": "`mean` {number}", "type": "number", "name": "mean", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "

The mean of the recorded event loop delays.

" }, { "textRaw": "`min` {number}", "type": "number", "name": "min", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "

The minimum recorded event loop delay.

" }, { "textRaw": "`percentiles` {Map}", "type": "Map", "name": "percentiles", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "

Returns a Map object detailing the accumulated percentile distribution.

" }, { "textRaw": "`stddev` {number}", "type": "number", "name": "stddev", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "desc": "

The standard deviation of the recorded event loop delays.

" } ], "methods": [ { "textRaw": "`histogram.percentile(percentile)`", "type": "method", "name": "percentile", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "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]." } ] } ], "desc": "

Returns the value at the given percentile.

" }, { "textRaw": "`histogram.reset()`", "type": "method", "name": "reset", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Resets the collected histogram data.

" } ] }, { "textRaw": "Class: `IntervalHistogram extends Histogram`", "type": "class", "name": "IntervalHistogram", "desc": "

A Histogram that is periodically updated on a given interval.

", "methods": [ { "textRaw": "`histogram.disable()`", "type": "method", "name": "disable", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Disables the update interval timer. Returns true if the timer was\nstopped, false if it was already stopped.

" }, { "textRaw": "`histogram.enable()`", "type": "method", "name": "enable", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Enables the update interval timer. Returns true if the timer was\nstarted, false if it was already started.

" } ], "modules": [ { "textRaw": "Cloning an `IntervalHistogram`", "name": "cloning_an_`intervalhistogram`", "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.

", "type": "module", "displayName": "Cloning an `IntervalHistogram`" } ] }, { "textRaw": "Class: `RecordableHistogram extends Histogram`", "type": "class", "name": "RecordableHistogram", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "methods": [ { "textRaw": "`histogram.record(val)`", "type": "method", "name": "record", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`val` {number|bigint} The amount to record in the histogram.", "name": "val", "type": "number|bigint", "desc": "The amount to record in the histogram." } ] } ] }, { "textRaw": "`histogram.recordDelta()`", "type": "method", "name": "recordDelta", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calculates the amount of time (in nanoseconds) that has passed since the\nprevious call to recordDelta() and records that amount in the histogram.

\n

Examples

" } ], "modules": [ { "textRaw": "Measuring the duration of async operations", "name": "measuring_the_duration_of_async_operations", "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).

\n
'use strict';\nconst async_hooks = require('async_hooks');\nconst {\n  performance,\n  PerformanceObserver\n} = require('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  observer.disconnect();\n});\nobs.observe({ entryTypes: ['measure'], buffered: true });\n\nsetTimeout(() => {}, 1000);\n
", "type": "module", "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", "desc": "

The following example measures the duration of require() operations to load\ndependencies:

\n\n
'use strict';\nconst {\n  performance,\n  PerformanceObserver\n} = require('perf_hooks');\nconst mod = require('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  obs.disconnect();\n});\nobs.observe({ entryTypes: ['function'], buffered: true });\n\nrequire('some-module');\n
", "type": "module", "displayName": "Measuring how long it takes to load dependencies" } ] } ], "methods": [ { "textRaw": "`perf_hooks.createHistogram([options])`", "type": "method", "name": "createHistogram", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {RecordableHistogram}", "name": "return", "type": "RecordableHistogram" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`min` {number|bigint} The minimum recordable value. Must be an integer value greater than 0. **Default:** `1`.", "name": "min", "type": "number|bigint", "default": "`1`", "desc": "The minimum recordable value. Must be an integer value greater than 0." }, { "textRaw": "`max` {number|bigint} The maximum recordable value. Must be an integer value greater than `min`. **Default:** `Number.MAX_SAFE_INTEGER`.", "name": "max", "type": "number|bigint", "default": "`Number.MAX_SAFE_INTEGER`", "desc": "The maximum recordable value. Must be an integer value greater than `min`." }, { "textRaw": "`figures` {number} The number of accuracy digits. Must be a number between `1` and `5`. **Default:** `3`.", "name": "figures", "type": "number", "default": "`3`", "desc": "The number of accuracy digits. Must be a number between `1` and `5`." } ] } ] } ], "desc": "

Returns a <RecordableHistogram>.

" }, { "textRaw": "`perf_hooks.monitorEventLoopDelay([options])`", "type": "method", "name": "monitorEventLoopDelay", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {IntervalHistogram}", "name": "return", "type": "IntervalHistogram" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`resolution` {number} The sampling rate in milliseconds. Must be greater than zero. **Default:** `10`.", "name": "resolution", "type": "number", "default": "`10`", "desc": "The sampling rate in milliseconds. Must be greater than zero." } ] } ] } ], "desc": "

This property is an extension by Node.js. It is not available in Web browsers.

\n

Creates an IntervalHistogram object that samples and reports the event loop\ndelay over time. The delays will be reported in nanoseconds.

\n

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.

\n
const { monitorEventLoopDelay } = require('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
" } ], "type": "module", "displayName": "Performance measurement APIs", "source": "doc/api/perf_hooks.md" }, { "textRaw": "Punycode", "name": "punycode", "meta": { "deprecated": [ "v7.0.0" ], "changes": [] }, "introduced_in": "v0.10.0", "stability": 0, "stabilityText": "Deprecated", "desc": "

Source Code: lib/punycode.js

\n

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.

\n

The punycode module is a bundled version of the Punycode.js module. It\ncan be accessed using:

\n
const punycode = require('punycode');\n
\n

Punycode 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'.

\n

The punycode module provides a simple implementation of the Punycode standard.

\n

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.

", "methods": [ { "textRaw": "`punycode.decode(string)`", "type": "method", "name": "decode", "meta": { "added": [ "v0.5.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`string` {string}", "name": "string", "type": "string" } ] } ], "desc": "

The punycode.decode() method converts a Punycode string of ASCII-only\ncharacters to the equivalent string of Unicode codepoints.

\n
punycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n
" }, { "textRaw": "`punycode.encode(string)`", "type": "method", "name": "encode", "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.

\n
punycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n
" }, { "textRaw": "`punycode.toASCII(domain)`", "type": "method", "name": "toASCII", "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.

\n
// 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)`", "type": "method", "name": "toUnicode", "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.

\n
// 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", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "methods": [ { "textRaw": "`punycode.ucs2.decode(string)`", "type": "method", "name": "decode", "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.

\n
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)`", "type": "method", "name": "encode", "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.

\n
punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'\n
" } ] }, { "textRaw": "`version` {string}", "type": "string", "name": "version", "meta": { "added": [ "v0.6.1" ], "changes": [] }, "desc": "

Returns a string identifying the current Punycode.js version number.

" } ], "type": "module", "displayName": "Punycode", "source": "doc/api/punycode.md" }, { "textRaw": "Query string", "name": "querystring", "introduced_in": "v0.1.25", "stability": 3, "stabilityText": "Legacy", "desc": "

Source Code: lib/querystring.js

\n

The querystring module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:

\n
const querystring = require('querystring');\n
\n

The querystring API is considered Legacy. While it is still maintained,\nnew code should use the <URLSearchParams> API instead.

", "methods": [ { "textRaw": "`querystring.decode()`", "type": "method", "name": "decode", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The querystring.decode() function is an alias for querystring.parse().

" }, { "textRaw": "`querystring.encode()`", "type": "method", "name": "encode", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The querystring.encode() function is an alias for querystring.stringify().

" }, { "textRaw": "`querystring.escape(str)`", "type": "method", "name": "escape", "meta": { "added": [ "v0.1.25" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`str` {string}", "name": "str", "type": "string" } ] } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`querystring.parse(str[, sep[, eq[, options]]])`", "type": "method", "name": "parse", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10967", "description": "Multiple empty entries are now parsed correctly (e.g. `&=&=`)." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6055", "description": "The returned object no longer inherits from `Object.prototype`." }, { "version": [ "v6.0.0", "v4.2.4" ], "pr-url": "https://github.com/nodejs/node/pull/3807", "description": "The `eq` parameter may now have a length of more than `1`." } ] }, "signatures": [ { "params": [ { "textRaw": "`str` {string} The URL query string to parse", "name": "str", "type": "string", "desc": "The URL query string to parse" }, { "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." }, { "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." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`decodeURIComponent` {Function} The function to use when decoding percent-encoded characters in the query string. **Default:** `querystring.unescape()`.", "name": "decodeURIComponent", "type": "Function", "default": "`querystring.unescape()`", "desc": "The function to use when decoding percent-encoded characters in the query string." }, { "textRaw": "`maxKeys` {number} Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. **Default:** `1000`.", "name": "maxKeys", "type": "number", "default": "`1000`", "desc": "Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations." } ] } ] } ], "desc": "

The querystring.parse() method parses a URL query string (str) into a\ncollection of key and value pairs.

\n

For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:

\n\n
{\n  foo: 'bar',\n  abc: ['xyz', '123']\n}\n
\n

The 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.

\n

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:

\n
// 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]]])`", "type": "method", "name": "stringify", "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." }, { "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." }, { "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." } ] } ] } ], "desc": "

The querystring.stringify() method produces a URL query string from a\ngiven obj by iterating through the object's \"own properties\".

\n

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.

\n
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
\n

By 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:

\n
// Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n                      { encodeURIComponent: gbkEncodeURIComponent });\n
" }, { "textRaw": "`querystring.unescape(str)`", "type": "method", "name": "unescape", "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.

\n

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.

\n

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.

" } ], "type": "module", "displayName": "querystring", "source": "doc/api/querystring.md" }, { "textRaw": "Readline", "name": "readline", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/readline.js

\n

The readline module provides an interface for reading data from a Readable\nstream (such as process.stdin) one line at a time. It can be accessed\nusing:

\n
const readline = require('readline');\n
\n

The following simple example illustrates the basic use of the readline module.

\n
const readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\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
\n

Once 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.

", "classes": [ { "textRaw": "Class: `Interface`", "type": "class", "name": "Interface", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when one of the following occur:

\n
    \n
  • The rl.close() method is called and the readline.Interface instance has\nrelinquished control over the input and output streams;
  • \n
  • The input stream receives its 'end' event;
  • \n
  • The input stream receives Ctrl+D to signal\nend-of-transmission (EOT);
  • \n
  • The input stream receives Ctrl+C to signal SIGINT\nand there is no 'SIGINT' event listener registered on the\nreadline.Interface instance.
  • \n
\n

The listener function is called without passing any arguments.

\n

The readline.Interface instance is finished once the 'close' event is\nemitted.

" }, { "textRaw": "Event: `'line'`", "type": "event", "name": "line", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "params": [], "desc": "

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.

\n

The listener function is called with a string containing the single line of\nreceived input.

\n
rl.on('line', (input) => {\n  console.log(`Received: ${input}`);\n});\n
" }, { "textRaw": "Event: `'history'`", "type": "event", "name": "history", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "params": [], "desc": "

The 'history' event is emitted whenever the history array has changed.

\n

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.

\n

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.

\n
rl.on('history', (history) => {\n  console.log(`Received: ${history}`);\n});\n
" }, { "textRaw": "Event: `'pause'`", "type": "event", "name": "pause", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'pause' event is emitted when one of the following occur:

\n
    \n
  • The input stream is paused.
  • \n
  • The input stream is not paused and receives the 'SIGCONT' event. (See\nevents 'SIGTSTP' and 'SIGCONT'.)
  • \n
\n

The listener function is called without passing any arguments.

\n
rl.on('pause', () => {\n  console.log('Readline paused.');\n});\n
" }, { "textRaw": "Event: `'resume'`", "type": "event", "name": "resume", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'resume' event is emitted whenever the input stream is resumed.

\n

The listener function is called without passing any arguments.

\n
rl.on('resume', () => {\n  console.log('Readline resumed.');\n});\n
" }, { "textRaw": "Event: `'SIGCONT'`", "type": "event", "name": "SIGCONT", "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).

\n

If the input stream was paused before the SIGTSTP request, this event will\nnot be emitted.

\n

The listener function is invoked without passing any arguments.

\n
rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});\n
\n

The 'SIGCONT' event is not supported on Windows.

" }, { "textRaw": "Event: `'SIGINT'`", "type": "event", "name": "SIGINT", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "params": [], "desc": "

The 'SIGINT' event is emitted whenever the input stream receives a\nCtrl+C input, known typically as SIGINT. If there are no 'SIGINT'\nevent listeners registered when the input stream receives a SIGINT, the\n'pause' event will be emitted.

\n

The listener function is invoked without passing any arguments.

\n
rl.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'`", "type": "event", "name": "SIGTSTP", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "params": [], "desc": "

The 'SIGTSTP' event is emitted when the input stream receives a\nCtrl+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.

\n

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.

\n

The 'pause' and 'SIGCONT' events will not be emitted if the input was\npaused before the process was sent to the background.

\n

The listener function is invoked without passing any arguments.

\n
rl.on('SIGTSTP', () => {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});\n
\n

The 'SIGTSTP' event is not supported on Windows.

" } ], "methods": [ { "textRaw": "`rl.close()`", "type": "method", "name": "close", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.close() method closes the readline.Interface instance and\nrelinquishes control over the input and output streams. When called,\nthe 'close' event will be emitted.

\n

Calling rl.close() does not immediately stop other events (including 'line')\nfrom being emitted by the readline.Interface instance.

" }, { "textRaw": "`rl.pause()`", "type": "method", "name": "pause", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.pause() method pauses the input stream, allowing it to be resumed\nlater if necessary.

\n

Calling rl.pause() does not immediately pause other events (including\n'line') from being emitted by the readline.Interface instance.

" }, { "textRaw": "`rl.prompt([preserveCursor])`", "type": "method", "name": "prompt", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`preserveCursor` {boolean} If `true`, prevents the cursor placement from being reset to `0`.", "name": "preserveCursor", "type": "boolean", "desc": "If `true`, prevents the cursor placement from being reset to `0`." } ] } ], "desc": "

The rl.prompt() method writes the readline.Interface instances configured\nprompt to a new line in output in order to provide a user with a new\nlocation at which to provide input.

\n

When called, rl.prompt() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the prompt is not written.

" }, { "textRaw": "`rl.question(query[, options], callback)`", "type": "method", "name": "question", "meta": { "added": [ "v0.3.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`query` {string} A statement or query to write to `output`, prepended to the prompt.", "name": "query", "type": "string", "desc": "A statement or query to write to `output`, prepended to the prompt." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`signal` {AbortSignal} Optionally allows the `question()` to be canceled using an `AbortController`.", "name": "signal", "type": "AbortSignal", "desc": "Optionally allows the `question()` to be canceled using an `AbortController`." } ] }, { "textRaw": "`callback` {Function} A callback function that is invoked with the user's input in response to the `query`.", "name": "callback", "type": "Function", "desc": "A callback function that is invoked with the user's input in response to the `query`." } ] } ], "desc": "

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.

\n

When called, rl.question() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the query is not written.

\n

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.

\n

Example usage:

\n
rl.question('What is your favorite food? ', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});\n
\n

Using an AbortController to cancel a question.

\n
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
\n

If this method is invoked as it's util.promisify()ed version, it returns a\nPromise that fulfills with the answer. If the question is canceled using\nan AbortController it will reject with an AbortError.

\n
const util = require('util');\nconst question = util.promisify(rl.question).bind(rl);\n\nasync function questionExample() {\n  try {\n    const answer = await question('What is you favorite food? ');\n    console.log(`Oh, so your favorite food is ${answer}`);\n  } catch (err) {\n    console.error('Question rejected', err);\n  }\n}\nquestionExample();\n
" }, { "textRaw": "`rl.resume()`", "type": "method", "name": "resume", "meta": { "added": [ "v0.3.4" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The rl.resume() method resumes the input stream if it has been paused.

" }, { "textRaw": "`rl.setPrompt(prompt)`", "type": "method", "name": "setPrompt", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`prompt` {string}", "name": "prompt", "type": "string" } ] } ], "desc": "

The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.

" }, { "textRaw": "`rl.getPrompt()`", "type": "method", "name": "getPrompt", "meta": { "added": [ "v15.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string} the current prompt string", "name": "return", "type": "string", "desc": "the current prompt string" }, "params": [] } ], "desc": "

The rl.getPrompt() method returns the current prompt used by rl.prompt().

" }, { "textRaw": "`rl.write(data[, key])`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`data` {string}", "name": "data", "type": "string" }, { "textRaw": "`key` {Object}", "name": "key", "type": "Object", "options": [ { "textRaw": "`ctrl` {boolean} `true` to indicate the Ctrl key.", "name": "ctrl", "type": "boolean", "desc": "`true` to indicate the Ctrl key." }, { "textRaw": "`meta` {boolean} `true` to indicate the Meta key.", "name": "meta", "type": "boolean", "desc": "`true` to indicate the Meta key." }, { "textRaw": "`shift` {boolean} `true` to indicate the Shift key.", "name": "shift", "type": "boolean", "desc": "`true` to indicate the Shift key." }, { "textRaw": "`name` {string} The name of the a key.", "name": "name", "type": "string", "desc": "The name of the a key." } ] } ] } ], "desc": "

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.

\n

If key is specified, data is ignored.

\n

When called, rl.write() will resume the input stream if it has been\npaused.

\n

If the readline.Interface was created with output set to null or\nundefined the data and key are not written.

\n
rl.write('Delete this!');\n// Simulate Ctrl+U to delete the line written previously\nrl.write(null, { ctrl: true, name: 'u' });\n
\n

The rl.write() method will write the data to the readline Interface's\ninput as if it were provided by the user.

" }, { "textRaw": "`rl[Symbol.asyncIterator]()`", "type": "method", "name": "[Symbol.asyncIterator]", "meta": { "added": [ "v11.4.0", "v10.16.0" ], "changes": [ { "version": [ "v11.14.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/26989", "description": "Symbol.asyncIterator support is no longer experimental." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator}", "name": "return", "type": "AsyncIterator" }, "params": [] } ], "desc": "

Create an AsyncIterator object that iterates through each line in the input\nstream as a string. This method allows asynchronous iteration of\nreadline.Interface objects through for await...of loops.

\n

Errors in the input stream are not forwarded.

\n

If the loop is terminated with break, throw, or return,\nrl.close() will be called. In other words, iterating over a\nreadline.Interface will always consume the input stream fully.

\n

Performance is not on par with the traditional 'line' event API. Use 'line'\ninstead for performance-sensitive applications.

\n
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
\n

readline.createInterface() will start to consume the input stream once\ninvoked. Having asynchronous operations between interface creation and\nasynchronous iteration may result in missed lines.

" }, { "textRaw": "`rl.getCursorPos()`", "type": "method", "name": "getCursorPos", "meta": { "added": [ "v13.5.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`rows` {number} the row of the prompt the cursor currently lands on", "name": "rows", "type": "number", "desc": "the row of the prompt the cursor currently lands on" }, { "textRaw": "`cols` {number} the screen column the cursor currently lands on", "name": "cols", "type": "number", "desc": "the screen column the cursor currently lands on" } ] }, "params": [] } ], "desc": "

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": "`line` {string}", "type": "string", "name": "line", "meta": { "added": [ "v0.1.98" ], "changes": [ { "version": "v15.8.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.

\n

This 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.

\n

Be aware that modifying the value during the instance runtime may have\nunintended consequences if rl.cursor is not also controlled.

\n

If not using a TTY stream for input, use the 'line' event.

\n

One possible use case would be as follows:

\n
const 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": "`cursor` {number|undefined}", "type": "number|undefined", "name": "cursor", "meta": { "added": [ "v0.1.98" ], "changes": [] }, "desc": "

The cursor position relative to rl.line.

\n

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.

" } ] } ], "methods": [ { "textRaw": "`readline.clearLine(stream, dir[, callback])`", "type": "method", "name": "clearLine", "meta": { "added": [ "v0.7.7" ], "changes": [ { "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": [ { "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`." }, "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." } ] } ], "desc": "

The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.

" }, { "textRaw": "`readline.clearScreenDown(stream[, callback])`", "type": "method", "name": "clearScreenDown", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28641", "description": "The stream's write() callback and return value are exposed." } ] }, "signatures": [ { "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`." }, "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.

" }, { "textRaw": "`readline.createInterface(options)`", "type": "method", "name": "createInterface", "meta": { "added": [ "v0.1.98" ], "changes": [ { "version": "v15.14.0", "pr-url": "https://github.com/nodejs/node/pull/37932", "description": "The `signal` option is supported now." }, { "version": "v15.8.0", "pr-url": "https://github.com/nodejs/node/pull/33662", "description": "The `history` option is supported now." }, { "version": "v13.9.0", "pr-url": "https://github.com/nodejs/node/pull/31318", "description": "The `tabSize` option is supported now." }, { "version": [ "v8.3.0", "v6.11.4" ], "pr-url": "https://github.com/nodejs/node/pull/13497", "description": "Remove max limit of `crlfDelay` option." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8109", "description": "The `crlfDelay` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/7125", "description": "The `prompt` option is supported now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6352", "description": "The `historySize` option can be `0` now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {readline.Interface}", "name": "return", "type": "readline.Interface" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`input` {stream.Readable} The [Readable][] stream to listen to. This option is *required*.", "name": "input", "type": "stream.Readable", "desc": "The [Readable][] stream to listen to. This option is *required*." }, { "textRaw": "`output` {stream.Writable} The [Writable][] stream to write readline data to.", "name": "output", "type": "stream.Writable", "desc": "The [Writable][] stream to write readline data to." }, { "textRaw": "`completer` {Function} An optional function used for Tab autocompletion.", "name": "completer", "type": "Function", "desc": "An optional function used for Tab autocompletion." }, { "textRaw": "`terminal` {boolean} `true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. **Default:** checking `isTTY` on the `output` stream upon instantiation.", "name": "terminal", "type": "boolean", "default": "checking `isTTY` on the `output` stream upon instantiation", "desc": "`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it." }, { "textRaw": "`history` {string[]} Initial list of history lines. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all. **Default:** `[]`.", "name": "history", "type": "string[]", "default": "`[]`", "desc": "Initial list of history lines. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all." }, { "textRaw": "`historySize` {number} Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all. **Default:** `30`.", "name": "historySize", "type": "number", "default": "`30`", "desc": "Maximum number of history lines retained. To disable the history set this value to `0`. This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check, otherwise the history caching mechanism is not initialized at all." }, { "textRaw": "`removeHistoryDuplicates` {boolean} If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list. **Default:** `false`.", "name": "removeHistoryDuplicates", "type": "boolean", "default": "`false`", "desc": "If `true`, when a new input line added to the history list duplicates an older one, this removes the older line from the list." }, { "textRaw": "`prompt` {string} The prompt string to use. **Default:** `'> '`.", "name": "prompt", "type": "string", "default": "`'> '`", "desc": "The prompt string to use." }, { "textRaw": "`crlfDelay` {number} If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter). **Default:** `100`.", "name": "crlfDelay", "type": "number", "default": "`100`", "desc": "If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. `crlfDelay` will be coerced to a number no less than `100`. It can be set to `Infinity`, in which case `\\r` followed by `\\n` will always be considered a single newline (which may be reasonable for [reading files][] with `\\r\\n` line delimiter)." }, { "textRaw": "`escapeCodeTimeout` {number} The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence). **Default:** `500`.", "name": "escapeCodeTimeout", "type": "number", "default": "`500`", "desc": "The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence)." }, { "textRaw": "`tabSize` {integer} The number of spaces a tab is equal to (minimum 1). **Default:** `8`.", "name": "tabSize", "type": "integer", "default": "`8`", "desc": "The number of spaces a tab is equal to (minimum 1)." }, { "textRaw": "`signal` {AbortSignal} Allows closing the interface using an AbortSignal. Aborting the signal will internally call `close` on the interface.", "name": "signal", "type": "AbortSignal", "desc": "Allows closing the interface using an AbortSignal. Aborting the signal will internally call `close` on the interface." } ] } ] } ], "desc": "

The readline.createInterface() method creates a new readline.Interface\ninstance.

\n
const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n
\n

Once the readline.Interface instance is created, the most common case is to\nlisten for the 'line' event:

\n
rl.on('line', (line) => {\n  console.log(`Received: ${line}`);\n});\n
\n

If 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).

\n

When creating a readline.Interface using stdin as input, the program\nwill not terminate until it receives EOF (Ctrl+D on\nLinux/macOS, Ctrl+Z followed by Return on\nWindows).\nIf you want your application to exit without waiting for user input, you can\nunref() the standard input stream:

\n
process.stdin.unref();\n
", "modules": [ { "textRaw": "Use of the `completer` function", "name": "use_of_the_`completer`_function", "desc": "

The completer function takes the current line entered by the user\nas an argument, and returns an Array with 2 entries:

\n
    \n
  • An Array with matching entries for the completion.
  • \n
  • The substring that was used for the matching.
  • \n
\n

For instance: [[substr1, substr2, ...], originalsubstring].

\n
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
\n

The completer function can be called asynchronously if it accepts two\narguments:

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}\n
", "type": "module", "displayName": "Use of the `completer` function" } ] }, { "textRaw": "`readline.cursorTo(stream, x[, y][, callback])`", "type": "method", "name": "cursorTo", "meta": { "added": [ "v0.7.7" ], "changes": [ { "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": [ { "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`." }, "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`x` {number}", "name": "x", "type": "number" }, { "textRaw": "`y` {number}", "name": "y", "type": "number" }, { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.

" }, { "textRaw": "`readline.emitKeypressEvents(stream[, interface])`", "type": "method", "name": "emitKeypressEvents", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Readable}", "name": "stream", "type": "stream.Readable" }, { "textRaw": "`interface` {readline.Interface}", "name": "interface", "type": "readline.Interface" } ] } ], "desc": "

The readline.emitKeypressEvents() method causes the given Readable\nstream to begin emitting 'keypress' events corresponding to received input.

\n

Optionally, interface specifies a readline.Interface instance for which\nautocompletion is disabled when copy-pasted input is detected.

\n

If the stream is a TTY, then it must be in raw mode.

\n

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.

\n
readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n  process.stdin.setRawMode(true);\n
" }, { "textRaw": "`readline.moveCursor(stream, dx, dy[, callback])`", "type": "method", "name": "moveCursor", "meta": { "added": [ "v0.7.7" ], "changes": [ { "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": [ { "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`." }, "params": [ { "textRaw": "`stream` {stream.Writable}", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`dx` {number}", "name": "dx", "type": "number" }, { "textRaw": "`dy` {number}", "name": "dy", "type": "number" }, { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

The readline.moveCursor() method moves the cursor relative to its current\nposition in a given TTY stream.

\n

Example: Tiny CLI

\n

The following example illustrates the use of readline.Interface class to\nimplement a small command-line interface:

\n
const readline = require('readline');\nconst rl = readline.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
\n

Example: Read file stream line-by-Line

\n

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:

\n
const fs = require('fs');\nconst readline = require('readline');\n\nasync function processLineByLine() {\n  const fileStream = fs.createReadStream('input.txt');\n\n  const rl = readline.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
\n

Alternatively, one could use the 'line' event:

\n
const fs = require('fs');\nconst readline = require('readline');\n\nconst rl = readline.createInterface({\n  input: fs.createReadStream('sample.txt'),\n  crlfDelay: Infinity\n});\n\nrl.on('line', (line) => {\n  console.log(`Line from file: ${line}`);\n});\n
\n

Currently, for await...of loop can be a bit slower. If async / await\nflow and speed are both essential, a mixed approach can be applied:

\n
const { once } = require('events');\nconst { createReadStream } = require('fs');\nconst { createInterface } = require('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
" } ], "modules": [ { "textRaw": "TTY keybindings", "name": "tty_keybindings", "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
KeybindingsDescriptionNotes
Ctrl+Shift+BackspaceDelete line leftDoesn't work on Linux, Mac and Windows
Ctrl+Shift+DeleteDelete line rightDoesn't work on Mac
Ctrl+CEmit SIGINT or close the readline instance
Ctrl+HDelete left
Ctrl+DDelete right or close the readline instance in case the current line is empty / EOFDoesn't work on Windows
Ctrl+UDelete from the current position to the line start
Ctrl+KDelete from the current position to the end of line
Ctrl+AGo to start of line
Ctrl+EGo to to end of line
Ctrl+BBack one character
Ctrl+FForward one character
Ctrl+LClear screen
Ctrl+NNext history item
Ctrl+PPrevious history item
Ctrl+ZMoves running process into background. Type\n fg and press Enter\n to return.Doesn't work on Windows
Ctrl+W or Ctrl\n +BackspaceDelete backward to a word boundaryCtrl+Backspace Doesn't\n work on Linux, Mac and Windows
Ctrl+DeleteDelete forward to a word boundaryDoesn't work on Mac
Ctrl+Left arrow or\n Meta+BWord leftCtrl+Left arrow Doesn't work\n on Mac
Ctrl+Right arrow or\n Meta+FWord rightCtrl+Right arrow Doesn't work\n on Mac
Meta+D or Meta\n +DeleteDelete word rightMeta+Delete Doesn't work\n on windows
Meta+BackspaceDelete word leftDoesn't work on Mac
", "type": "module", "displayName": "TTY keybindings" } ], "type": "module", "displayName": "Readline", "source": "doc/api/readline.md" }, { "textRaw": "REPL", "name": "repl", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/repl.js

\n

The repl module provides a Read-Eval-Print-Loop (REPL) implementation that\nis available both as a standalone program or includible in other applications.\nIt can be accessed using:

\n
const repl = require('repl');\n
", "modules": [ { "textRaw": "Design and features", "name": "design_and_features", "desc": "

The 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.

\n

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.

", "modules": [ { "textRaw": "Commands and special keys", "name": "commands_and_special_keys", "desc": "

The following special commands are supported by all REPL instances:

\n
    \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.
  • \n
  • .clear: Resets the REPL context to an empty object and clears any\nmulti-line expression being input.
  • \n
  • .exit: Close the I/O stream, causing the REPL to exit.
  • \n
  • .help: Show this list of special commands.
  • \n
  • .save: Save the current REPL session to a file:\n> .save ./file/to/save.js
  • \n
  • .load: Load a file into the current REPL session.\n> .load ./file/to/load.js
  • \n
  • .editor: Enter editor mode (Ctrl+D to finish,\nCtrl+C to cancel).
  • \n
\n
> .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
\n

The following key combinations in the REPL have these special effects:

\n
    \n
  • Ctrl+C: When pressed once, has the same effect as the\n.break command.\nWhen pressed twice on a blank line, has the same effect as the .exit\ncommand.
  • \n
  • Ctrl+D: Has the same effect as the .exit command.
  • \n
  • Tab: When pressed on a blank line, displays global and local (scope)\nvariables. When pressed while entering other input, displays relevant\nautocompletion options.
  • \n
\n

For key bindings related to the reverse-i-search, see reverse-i-search.\nFor all other key bindings, see TTY keybindings.

", "type": "module", "displayName": "Commands and special keys" }, { "textRaw": "Default evaluation", "name": "default_evaluation", "desc": "

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.

", "modules": [ { "textRaw": "JavaScript expressions", "name": "javascript_expressions", "desc": "

The default evaluator supports direct evaluation of JavaScript expressions:

\n
> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
\n

Unless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const, let, or var keywords\nare declared at the global scope.

", "type": "module", "displayName": "JavaScript expressions" }, { "textRaw": "Global and local scope", "name": "global_and_local_scope", "desc": "

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:

\n
const repl = require('repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
\n

Properties in the context object appear as local within the REPL:

\n
$ node repl_test.js\n> m\n'message'\n
\n

Context properties are not read-only by default. To specify read-only globals,\ncontext properties must be defined using Object.defineProperty():

\n
const repl = require('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
", "type": "module", "displayName": "Global and local scope" }, { "textRaw": "Accessing core Node.js modules", "name": "accessing_core_node.js_modules", "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('fs').

\n
> fs.createReadStream('./some/file');\n
", "type": "module", "displayName": "Accessing core Node.js modules" }, { "textRaw": "Global uncaught exceptions", "name": "global_uncaught_exceptions", "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.

\n

This use of the domain module in the REPL has these side effects:

\n", "type": "module", "displayName": "Global uncaught exceptions" }, { "textRaw": "Assignment of the `_` (underscore) variable", "name": "assignment_of_the_`_`_(underscore)_variable", "meta": { "changes": [ { "version": "v9.8.0", "pr-url": "https://github.com/nodejs/node/pull/18919", "description": "Added `_error` support." } ] }, "desc": "

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.

\n
> [ '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
\n

Similarly, _error will refer to the last seen error, if there was any.\nExplicitly setting _error to a value will disable this behavior.

\n
> throw new Error('foo');\nError: foo\n> _error.message\n'foo'\n
", "type": "module", "displayName": "Assignment of the `_` (underscore) variable" }, { "textRaw": "`await` keyword", "name": "`await`_keyword", "desc": "

Support for the await keyword is enabled at the top level.

\n
> await Promise.resolve(123)\n123\n> await Promise.reject(new Error('REPL await'))\nError: REPL await\n    at repl:1:45\n> const timeout = util.promisify(setTimeout);\nundefined\n> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);\n1002\nundefined\n
\n

One known limitation of using the await keyword in the REPL is that\nit will invalidate the lexical scoping of the const and let\nkeywords.

\n

For example:

\n
> const m = await Promise.resolve(123)\nundefined\n> m\n123\n> const m = await Promise.resolve(234)\nundefined\n> m\n234\n
\n

--no-experimental-repl-await shall disable top-level await in REPL.

", "type": "module", "displayName": "`await` keyword" } ], "type": "module", "displayName": "Default evaluation" }, { "textRaw": "Reverse-i-search", "name": "reverse-i-search", "meta": { "added": [ "v13.6.0", "v12.17.0" ], "changes": [] }, "desc": "

The REPL supports bi-directional reverse-i-search similar to ZSH. It is\ntriggered with Ctrl+R to search backward and\nCtrl+S to search\nforwards.

\n

Duplicated history entries will be skipped.

\n

Entries are accepted as soon as any key is pressed that doesn't correspond\nwith the reverse search. Cancelling is possible by pressing Esc or\nCtrl+C.

\n

Changing the direction immediately searches for the next entry in the expected\ndirection from the current position on.

", "type": "module", "displayName": "Reverse-i-search" }, { "textRaw": "Custom evaluation functions", "name": "custom_evaluation_functions", "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.

\n

The following illustrates a hypothetical example of a REPL that performs\ntranslation of text from one language to another:

\n
const repl = require('repl');\nconst { Translator } = require('translator');\n\nconst myTranslator = new Translator('en', 'fr');\n\nfunction myEval(cmd, context, filename, callback) {\n  callback(null, myTranslator.translate(cmd));\n}\n\nrepl.start({ prompt: '> ', eval: myEval });\n
", "modules": [ { "textRaw": "Recoverable errors", "name": "recoverable_errors", "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:

\n
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
", "type": "module", "displayName": "Recoverable errors" } ], "type": "module", "displayName": "Custom evaluation functions" }, { "textRaw": "Customizing REPL output", "name": "customizing_repl_output", "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.

\n

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.

\n

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().

\n
> util.inspect.replDefaults.compact = false;\nfalse\n> [1]\n[\n  1\n]\n>\n
\n

To 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:

\n
const repl = require('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
", "type": "module", "displayName": "Customizing REPL output" } ], "type": "module", "displayName": "Design and features" }, { "textRaw": "The Node.js REPL", "name": "the_node.js_repl", "desc": "

Node.js itself uses the repl module to provide its own interactive interface\nfor executing JavaScript. This can be used by executing the Node.js binary\nwithout passing any arguments (or by passing the -i argument):

\n
$ 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", "desc": "

Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:

\n
    \n
  • NODE_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.
  • \n
  • NODE_REPL_HISTORY_SIZE: Controls how many lines of history will be\npersisted if history is available. Must be a positive number.\nDefault: 1000.
  • \n
  • NODE_REPL_MODE: May be either 'sloppy' or 'strict'. Default:\n'sloppy', which will allow non-strict mode code to be run.
  • \n
", "type": "module", "displayName": "Environment variable options" }, { "textRaw": "Persistent history", "name": "persistent_history", "desc": "

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=''.

", "type": "module", "displayName": "Persistent history" }, { "textRaw": "Using the Node.js REPL with advanced line-editors", "name": "using_the_node.js_repl_with_advanced_line-editors", "desc": "

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.

\n

For example, the following can be added to a .bashrc file:

\n
alias node=\"env NODE_NO_READLINE=1 rlwrap node\"\n
", "type": "module", "displayName": "Using the Node.js REPL with advanced line-editors" }, { "textRaw": "Starting multiple REPL instances against a single running instance", "name": "starting_multiple_repl_instances_against_a_single_running_instance", "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 but have\nseparate I/O interfaces.

\n

The following example, for instance, provides separate REPLs on stdin, a Unix\nsocket, and a TCP socket:

\n
const net = require('net');\nconst repl = require('repl');\nlet connections = 0;\n\nrepl.start({\n  prompt: 'Node.js via stdin> ',\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via Unix socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen('/tmp/node-repl-sock');\n\nnet.createServer((socket) => {\n  connections += 1;\n  repl.start({\n    prompt: 'Node.js via TCP socket> ',\n    input: socket,\n    output: socket\n  }).on('exit', () => {\n    socket.end();\n  });\n}).listen(5001);\n
\n

Running 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.

\n

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.

\n

For an example of running a \"full-featured\" (terminal) REPL over\na net.Server and net.Socket instance, see:\nhttps://gist.github.com/TooTallNate/2209310.

\n

For an example of running a REPL instance over curl(1), see:\nhttps://gist.github.com/TooTallNate/2053342.

", "type": "module", "displayName": "Starting multiple REPL instances against a single running instance" } ], "type": "module", "displayName": "The Node.js REPL" } ], "classes": [ { "textRaw": "Class: `REPLServer`", "type": "class", "name": "REPLServer", "meta": { "added": [ "v0.1.91" ], "changes": [] }, "desc": "\n

Instances of repl.REPLServer are created using the repl.start() method\nor directly using the JavaScript new keyword.

\n
const repl = require('repl');\n\nconst options = { useColors: true };\n\nconst firstInstance = repl.start(options);\nconst secondInstance = new repl.REPLServer(options);\n
", "events": [ { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "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.

\n
replServer.on('exit', () => {\n  console.log('Received \"exit\" event from repl!');\n  process.exit();\n});\n
" }, { "textRaw": "Event: `'reset'`", "type": "event", "name": "reset", "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.

\n

This can be used primarily to re-initialize REPL context to some pre-defined\nstate:

\n
const repl = require('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
\n

When this code is executed, the global 'm' variable can be modified but then\nreset to its initial value using the .clear command:

\n
$ ./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)`", "type": "method", "name": "defineCommand", "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:

\n
    \n
  • help <string> Help text to be displayed when .help is entered (Optional).
  • \n
  • action <Function> The function to execute, optionally accepting a single\nstring argument.
  • \n
\n

The following example shows two new commands added to the REPL instance:

\n
const repl = require('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
\n

The 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])`", "type": "method", "name": "displayPrompt", "meta": { "added": [ "v0.1.91" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`preserveCursor` {boolean}", "name": "preserveCursor", "type": "boolean" } ] } ], "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.

\n

When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.

\n

When preserveCursor is true, the cursor placement will not be reset to 0.

\n

The replServer.displayPrompt method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand() method.

" }, { "textRaw": "`replServer.clearBufferedCommand()`", "type": "method", "name": "clearBufferedCommand", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

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.

" }, { "textRaw": "`replServer.parseREPLKeyword(keyword[, rest])`", "type": "method", "name": "parseREPLKeyword", "meta": { "added": [ "v0.8.9" ], "deprecated": [ "v9.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`keyword` {string} the potential keyword to parse and execute", "name": "keyword", "type": "string", "desc": "the potential keyword to parse and execute" }, { "textRaw": "`rest` {any} any parameters to the keyword command", "name": "rest", "type": "any", "desc": "any parameters to the keyword command" } ] } ], "desc": "

An internal method used to parse and execute REPLServer keywords.\nReturns true if keyword is a valid keyword, otherwise false.

" }, { "textRaw": "`replServer.setupHistory(historyPath, callback)`", "type": "method", "name": "setupHistory", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`historyPath` {string} the path to the history file", "name": "historyPath", "type": "string", "desc": "the path to the history file" }, { "textRaw": "`callback` {Function} called when history writes are ready or upon error", "name": "callback", "type": "Function", "desc": "called when history writes are ready or upon error", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`repl` {repl.REPLServer}", "name": "repl", "type": "repl.REPLServer" } ] } ] } ], "desc": "

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": "`builtinModules` {string[]}", "type": "string[]", "name": "builtinModules", "meta": { "added": [ "v14.5.0" ], "changes": [] }, "desc": "

A list of the names of all Node.js modules, e.g., 'http'.

" } ], "methods": [ { "textRaw": "`repl.start([options])`", "type": "method", "name": "start", "meta": { "added": [ "v0.1.91" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {repl.REPLServer}", "name": "return", "type": "repl.REPLServer" }, "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.", "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", "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." } ] } ] } ], "desc": "

The repl.start() method creates and starts a repl.REPLServer instance.

\n

If options is a string, then it specifies the input prompt:

\n
const repl = require('repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n
" } ], "type": "module", "displayName": "REPL", "source": "doc/api/repl.md" }, { "textRaw": "Stream", "name": "stream", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/stream.js

\n

A stream is an abstract interface for working with streaming data in Node.js.\nThe stream module provides an API for implementing the stream interface.

\n

There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.

\n

Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.

\n

To access the stream module:

\n
const stream = require('stream');\n
\n

The stream module is useful for creating new types of stream instances. It is\nusually not necessary to use the stream module to consume streams.

", "modules": [ { "textRaw": "Organization of this document", "name": "organization_of_this_document", "desc": "

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.

", "type": "module", "displayName": "Organization of this document" }, { "textRaw": "Types of streams", "name": "types_of_streams", "desc": "

There are four fundamental stream types within Node.js:

\n\n

Additionally, this module includes the utility functions\nstream.pipeline(), stream.finished(), stream.Readable.from()\nand stream.addAbortSignal().

", "modules": [ { "textRaw": "Streams Promises API", "name": "streams_promises_api", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

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('stream/promises')\nor require('stream').promises.

", "type": "module", "displayName": "Streams Promises API" }, { "textRaw": "Object mode", "name": "object_mode", "desc": "

All streams created by Node.js APIs operate exclusively on strings and Buffer\n(or Uint8Array) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of null,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".

\n

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.

", "type": "module", "displayName": "Object mode" } ], "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

Both Writable and Readable streams will store data in an internal\nbuffer.

\n

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.

\n

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.

\n

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).

\n

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.

\n

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.

\n

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.

\n

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.

\n

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.

" } ], "type": "module", "displayName": "Types of streams" } ], "methods": [ { "textRaw": "`stream.finished(stream[, options], callback)`", "type": "method", "name": "finished", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "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." }, "params": [ { "textRaw": "`stream` {Stream} A readable and/or writable stream.", "name": "stream", "type": "Stream", "desc": "A readable and/or writable stream." }, { "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." } ] }, { "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." } ] } ], "desc": "

A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

\n
const { finished } = require('stream');\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
\n

Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

\n

The finished API provides promise version:

\n
const { finished } = require('stream/promises');\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
\n

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:

\n
const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
" }, { "textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {Stream}", "name": "return", "type": "Stream" }, "params": [ { "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", "name": "streams", "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" }, { "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", "name": "source", "type": "Stream|Iterable|AsyncIterable|Function", "options": [ { "textRaw": "Returns: {Iterable|AsyncIterable}", "name": "return", "type": "Iterable|AsyncIterable" } ] }, { "textRaw": "`...transforms` {Stream|Function}", "name": "...transforms", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable}", "name": "return", "type": "AsyncIterable" } ] }, { "textRaw": "`destination` {Stream|Function}", "name": "destination", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable|Promise}", "name": "return", "type": "AsyncIterable|Promise" } ] }, { "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`." } ] } ] } ], "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.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('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
\n

The pipeline API provides a promise version, which can also\nreceive an options argument as the last parameter with a\nsignal <AbortSignal> property. When the signal is aborted,\ndestroy will be called on the underlying pipeline, with an\nAbortError.

\n
const { pipeline } = require('stream/promises');\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
\n

To use an AbortSignal, pass it inside an options object,\nas the last argument:

\n
const { pipeline } = require('stream/promises');\n\nasync function run() {\n  const ac = new AbortController();\n  const options = {\n    signal: ac.signal,\n  };\n\n  setTimeout(() => ac.abort(), 1);\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    options,\n  );\n}\n\nrun().catch(console.error); // AbortError\n
\n

The pipeline API also supports async generators:

\n
const { pipeline } = require('stream/promises');\nconst fs = require('fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield chunk.toUpperCase();\n      }\n    },\n    fs.createWriteStream('uppercase.txt')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
\n

stream.pipeline() will call stream.destroy(err) on all streams except:

\n
    \n
  • Readable streams which have emitted 'end' or 'close'.
  • \n
  • Writable streams which have emitted 'finish' or 'close'.
  • \n
\n

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.

" }, { "textRaw": "`stream.pipeline(streams, callback)`", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {Stream}", "name": "return", "type": "Stream" }, "params": [ { "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", "name": "streams", "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" }, { "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", "name": "source", "type": "Stream|Iterable|AsyncIterable|Function", "options": [ { "textRaw": "Returns: {Iterable|AsyncIterable}", "name": "return", "type": "Iterable|AsyncIterable" } ] }, { "textRaw": "`...transforms` {Stream|Function}", "name": "...transforms", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable}", "name": "return", "type": "AsyncIterable" } ] }, { "textRaw": "`destination` {Stream|Function}", "name": "destination", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable|Promise}", "name": "return", "type": "AsyncIterable|Promise" } ] }, { "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`." } ] } ] } ], "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.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('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
\n

The pipeline API provides a promise version, which can also\nreceive an options argument as the last parameter with a\nsignal <AbortSignal> property. When the signal is aborted,\ndestroy will be called on the underlying pipeline, with an\nAbortError.

\n
const { pipeline } = require('stream/promises');\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
\n

To use an AbortSignal, pass it inside an options object,\nas the last argument:

\n
const { pipeline } = require('stream/promises');\n\nasync function run() {\n  const ac = new AbortController();\n  const options = {\n    signal: ac.signal,\n  };\n\n  setTimeout(() => ac.abort(), 1);\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    options,\n  );\n}\n\nrun().catch(console.error); // AbortError\n
\n

The pipeline API also supports async generators:

\n
const { pipeline } = require('stream/promises');\nconst fs = require('fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield chunk.toUpperCase();\n      }\n    },\n    fs.createWriteStream('uppercase.txt')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
\n

stream.pipeline() will call stream.destroy(err) on all streams except:

\n
    \n
  • Readable streams which have emitted 'end' or 'close'.
  • \n
  • Writable streams which have emitted 'finish' or 'close'.
  • \n
\n

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.

" }, { "textRaw": "`stream.Readable.from(iterable, [options])`", "type": "method", "name": "from", "meta": { "added": [ "v12.3.0", "v10.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Readable}", "name": "return", "type": "stream.Readable" }, "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`." } ] } ], "desc": "

A utility method for creating readable streams out of iterators.

\n
const { Readable } = require('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
\n

Calling 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.

" }, { "textRaw": "`stream.addAbortSignal(signal, stream)`", "type": "method", "name": "addAbortSignal", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`signal` {AbortSignal} A signal representing possible cancellation", "name": "signal", "type": "AbortSignal", "desc": "A signal representing possible cancellation" }, { "textRaw": "`stream` {Stream} a stream to attach a signal to", "name": "stream", "type": "Stream", "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.

\n

Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the stream.

\n
const fs = require('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
\n

Or using an AbortSignal with a readable stream as an async iterable:

\n
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
" }, { "textRaw": "`readable.read(0)`", "type": "method", "name": "read", "signatures": [ { "params": [] } ], "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.

\n

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.

\n

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.

" }, { "textRaw": "`readable.push('')`", "type": "method", "name": "push", "signatures": [ { "params": [] } ], "desc": "

Use of readable.push('') is not recommended.

\n

Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because 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.

" } ], "miscs": [ { "textRaw": "API for stream consumers", "name": "API for stream consumers", "type": "misc", "desc": "

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:

\n
const http = require('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 in JSON at position 1\n
\n

Writable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.

\n

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.

\n

Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.

\n

Duplex and Transform streams are both Writable and\nReadable.

\n

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('stream').

\n

Developers wishing to implement new types of streams should refer to the\nsection API for stream implementers.

", "miscs": [ { "textRaw": "Writable streams", "name": "writable_streams", "desc": "

Writable streams are an abstraction for a destination to which data is\nwritten.

\n

Examples of Writable streams include:

\n\n

Some of these examples are actually Duplex streams that implement the\nWritable interface.

\n

All Writable streams implement the interface defined by the\nstream.Writable class.

\n

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:

\n
const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
", "classes": [ { "textRaw": "Class: `stream.Writable`", "type": "class", "name": "stream.Writable", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "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.

\n

A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

" }, { "textRaw": "Event: `'drain'`", "type": "event", "name": "drain", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

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.

\n
// 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'`", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "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.

\n

The stream is closed when the 'error' event is emitted unless the\nautoDestroy option was set to false when creating the\nstream.

\n

After 'error', no further events other than 'close' should be emitted\n(including 'error' events).

" }, { "textRaw": "Event: `'finish'`", "type": "event", "name": "finish", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.

\n
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'`", "type": "event", "name": "pipe", "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.

\n
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'`", "type": "event", "name": "unpipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "`src` {stream.Readable} The source stream that [unpiped][`stream.unpipe()`] this writable", "name": "src", "type": "stream.Readable", "desc": "The source stream that [unpiped][`stream.unpipe()`] 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.

\n

This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.

\n
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()`", "type": "method", "name": "cork", "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.

\n

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.

\n

See also: writable.uncork(), writable._writev().

" }, { "textRaw": "`writable.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/29197", "description": "Work as a no-op on a stream that has already been destroyed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error} Optional, an error to emit with `'error'` event.", "name": "error", "type": "Error", "desc": "Optional, an error to emit with `'error'` event." } ] } ], "desc": "

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.

\n
const { Writable } = require('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
\n
const { Writable } = require('stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});\n
\n
const { Writable } = require('stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED\n
\n

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'.

\n

Implementors should not override this method,\nbut instead implement writable._destroy().

" }, { "textRaw": "`writable.end([chunk[, encoding]][, callback])`", "type": "method", "name": "end", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/34101", "description": "The `callback` is invoked before 'finish' or on error." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/29747", "description": "The `callback` is invoked if 'finish' or 'error' is emitted." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `writable`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "name": "chunk", "type": "string|Buffer|Uint8Array|any", "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." }, { "textRaw": "`encoding` {string} The encoding if `chunk` is a string", "name": "encoding", "type": "string", "desc": "The encoding if `chunk` is a string" }, { "textRaw": "`callback` {Function} Callback for when the stream is finished.", "name": "callback", "type": "Function", "desc": "Callback for when the stream is finished." } ] } ], "desc": "

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.

\n

Calling the stream.write() method after calling\nstream.end() will raise an error.

\n
// Write 'hello, ' and then end with 'world!'.\nconst fs = require('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)`", "type": "method", "name": "setDefaultEncoding", "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": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`encoding` {string} The new default encoding", "name": "encoding", "type": "string", "desc": "The new default encoding" } ] } ], "desc": "

The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.

" }, { "textRaw": "`writable.uncork()`", "type": "method", "name": "uncork", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The writable.uncork() method flushes all data buffered since\nstream.cork() was called.

\n

When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, it is recommended that calls to writable.uncork() be\ndeferred using process.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.

\n
stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
\n

If 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.

\n
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
\n

See also: writable.cork().

" }, { "textRaw": "`writable.write(chunk[, encoding][, callback])`", "type": "method", "name": "write", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6170", "description": "Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the 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 the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "name": "chunk", "type": "string|Buffer|Uint8Array|any", "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." }, { "textRaw": "`encoding` {string|null} The encoding, if `chunk` is a string. **Default:** `'utf8'`", "name": "encoding", "type": "string|null", "default": "`'utf8'`", "desc": "The encoding, if `chunk` is a string." }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed.", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed." } ] } ], "desc": "

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.

\n

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.

\n

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.\nIt is recommended that once write() returns false, no more chunks be written\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.

\n

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.

\n

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:

\n
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
\n

A Writable stream in object mode will always ignore the encoding argument.

" } ], "properties": [ { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

Is true after writable.destroy() has been called.

\n
const { Writable } = require('stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true\n
" }, { "textRaw": "`writable` {boolean}", "type": "boolean", "name": "writable", "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.

" }, { "textRaw": "`writableEnded` {boolean}", "type": "boolean", "name": "writableEnded", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`writableCorked` {integer}", "type": "integer", "name": "writableCorked", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "desc": "

Number of times writable.uncork() needs to be\ncalled in order to fully uncork the stream.

" }, { "textRaw": "`writableFinished` {boolean}", "type": "boolean", "name": "writableFinished", "meta": { "added": [ "v12.6.0" ], "changes": [] }, "desc": "

Is set to true immediately before the 'finish' event is emitted.

" }, { "textRaw": "`writableHighWaterMark` {number}", "type": "number", "name": "writableHighWaterMark", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "desc": "

Return the value of highWaterMark passed when creating this Writable.

" }, { "textRaw": "`writableLength` {number}", "type": "number", "name": "writableLength", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`writableNeedDrain` {boolean}", "type": "boolean", "name": "writableNeedDrain", "meta": { "added": [ "v15.2.0" ], "changes": [] }, "desc": "

Is true if the stream's buffer has been full and stream will emit 'drain'.

" }, { "textRaw": "`writableObjectMode` {boolean}", "type": "boolean", "name": "writableObjectMode", "meta": { "added": [ "v12.3.0" ], "changes": [] }, "desc": "

Getter for the property objectMode of a given Writable stream.

" } ] } ], "type": "misc", "displayName": "Writable streams" }, { "textRaw": "Readable streams", "name": "readable_streams", "desc": "

Readable streams are an abstraction for a source from which data is\nconsumed.

\n

Examples of Readable streams include:

\n\n

All Readable streams implement the interface defined by the\nstream.Readable class.

", "modules": [ { "textRaw": "Two reading modes", "name": "two_reading_modes", "desc": "

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.

\n
    \n
  • \n

    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.

    \n
  • \n
  • \n

    In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.

    \n
  • \n
\n

All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:

\n\n

The Readable can switch back to paused mode using one of the following:

\n
    \n
  • If there are no pipe destinations, by calling the\nstream.pause() method.
  • \n
  • If there are pipe destinations, by removing all pipe destinations.\nMultiple pipe destinations may be removed by calling the\nstream.unpipe() method.
  • \n
\n

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.

\n

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.

\n

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.

\n

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.

", "type": "module", "displayName": "Two reading modes" }, { "textRaw": "Three states", "name": "three_states", "desc": "

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.

\n

Specifically, at any given point in time, every Readable is in one of three\npossible states:

\n
    \n
  • readable.readableFlowing === null
  • \n
  • readable.readableFlowing === false
  • \n
  • readable.readableFlowing === true
  • \n
\n

When 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.

\n

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.

\n
const { PassThrough, Writable } = require('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()); });\npass.write('ok');  // Will not emit 'data'.\npass.resume();     // Must be called to make stream emit 'data'.\n
\n

While readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.

", "type": "module", "displayName": "Three states" }, { "textRaw": "Choose one API style", "name": "choose_one_api_style", "desc": "

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.

\n

Use of the readable.pipe() method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the EventEmitter and readable.on('readable')/readable.read()\nor the readable.pause()/readable.resume() APIs.

", "type": "module", "displayName": "Choose one API style" } ], "classes": [ { "textRaw": "Class: `stream.Readable`", "type": "class", "name": "stream.Readable", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "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.

\n

A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

" }, { "textRaw": "Event: `'data'`", "type": "event", "name": "data", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "`chunk` {Buffer|string|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`.", "name": "chunk", "type": "Buffer|string|any", "desc": "The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`." } ], "desc": "

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.

\n

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.

\n

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.

\n
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\n
" }, { "textRaw": "Event: `'end'`", "type": "event", "name": "end", "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.

\n

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.

\n
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'`", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "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.

\n

The listener callback will be passed a single Error object.

" }, { "textRaw": "Event: `'pause'`", "type": "event", "name": "pause", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

The 'pause' event is emitted when stream.pause() is called\nand readableFlowing is not false.

" }, { "textRaw": "Event: `'readable'`", "type": "event", "name": "readable", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17979", "description": "The `'readable'` is always emitted in the next tick after `.push()` is called." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18994", "description": "Using `'readable'` requires calling `.read()`." } ] }, "params": [], "desc": "

The 'readable' event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the 'readable' event will\ncause some amount of data to be read into an internal buffer.

\n
const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // There is some data to read now.\n  let data;\n\n  while (data = this.read()) {\n    console.log(data);\n  }\n});\n
\n

The 'readable' event will also be emitted once the end of the stream data\nhas been reached but before the 'end' event is emitted.

\n

Effectively, the 'readable' event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, stream.read() will return the\navailable data. In the latter case, stream.read() will return\nnull. For instance, in the following example, foo.txt is an empty file:

\n
const fs = require('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
\n

The output of running this script is:

\n
$ node test.js\nreadable: null\nend\n
\n

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.

\n

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().

" }, { "textRaw": "Event: `'resume'`", "type": "event", "name": "resume", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

The 'resume' event is emitted when stream.resume() is\ncalled and readableFlowing is not true.

" } ], "methods": [ { "textRaw": "`readable.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/29197", "description": "Work as a no-op on a stream that has already been destroyed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error} Error which will be passed as payload in `'error'` event", "name": "error", "type": "Error", "desc": "Error which will be passed as payload in `'error'` event" } ] } ], "desc": "

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.

\n

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'.

\n

Implementors should not override this method, but instead implement\nreadable._destroy().

" }, { "textRaw": "`readable.isPaused()`", "type": "method", "name": "isPaused", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

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.

\n
const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n
" }, { "textRaw": "`readable.pause()`", "type": "method", "name": "pause", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [] } ], "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.

\n
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
\n

The readable.pause() method has no effect if there is a 'readable'\nevent listener.

" }, { "textRaw": "`readable.pipe(destination[, options])`", "type": "method", "name": "pipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream", "name": "return", "type": "stream.Writable", "desc": "The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream" }, "params": [ { "textRaw": "`destination` {stream.Writable} The destination for writing data", "name": "destination", "type": "stream.Writable", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options", "name": "options", "type": "Object", "desc": "Pipe options", "options": [ { "textRaw": "`end` {boolean} End the writer when the reader ends. **Default:** `true`.", "name": "end", "type": "boolean", "default": "`true`", "desc": "End the writer when the reader ends." } ] } ] } ], "desc": "

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.

\n

The following example pipes all of the data from the readable into a file\nnamed file.txt:

\n
const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n
\n

It is possible to attach multiple Writable streams to a single Readable\nstream.

\n

The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:

\n
const fs = require('fs');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
\n

By 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:

\n
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});\n
\n

One 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.

\n

The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.

" }, { "textRaw": "`readable.read([size])`", "type": "method", "name": "read", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer|null|any}", "name": "return", "type": "string|Buffer|null|any" }, "params": [ { "textRaw": "`size` {number} Optional argument to specify how much data to read.", "name": "size", "type": "number", "desc": "Optional argument to specify how much data to read." } ] } ], "desc": "

The readable.read() method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, null is returned. By default,\nthe data will be returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.

\n

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.

\n

If the size argument is not specified, all of the data contained in the\ninternal buffer will be returned.

\n

The size argument must be less than or equal to 1 GiB.

\n

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.

\n
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
\n

Each call to readable.read() returns a chunk of data, or null. The chunks\nare not concatenated. A while loop is necessary to consume all data\ncurrently in the buffer. When reading a large file .read() may return null,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new 'readable' event will be emitted\nwhen there is more data in the buffer. Finally the 'end' event will be\nemitted when there is no more data to come.

\n

Therefore to read a file's whole contents from a readable, it is necessary\nto collect chunks across multiple 'readable' events:

\n
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
\n

A 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.

\n

If the readable.read() method returns a chunk of data, a 'data' event will\nalso be emitted.

\n

Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.

" }, { "textRaw": "`readable.resume()`", "type": "method", "name": "resume", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18994", "description": "The `resume()` has no effect if there is a `'readable'` event listening." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [] } ], "desc": "

The readable.resume() method causes an explicitly paused Readable stream to\nresume emitting 'data' events, switching the stream into flowing mode.

\n

The readable.resume() method can be used to fully consume the data from a\nstream without actually processing any of that data:

\n
getReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });\n
\n

The readable.resume() method has no effect if there is a 'readable'\nevent listener.

" }, { "textRaw": "`readable.setEncoding(encoding)`", "type": "method", "name": "setEncoding", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`encoding` {string} The encoding to use.", "name": "encoding", "type": "string", "desc": "The encoding to use." } ] } ], "desc": "

The readable.setEncoding() method sets the character encoding for\ndata read from the Readable stream.

\n

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.

\n

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.

\n
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])`", "type": "method", "name": "unpipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe", "name": "destination", "type": "stream.Writable", "desc": "Optional specific stream to unpipe" } ] } ], "desc": "

The readable.unpipe() method detaches a Writable stream previously attached\nusing the stream.pipe() method.

\n

If the destination is not specified, then all pipes are detached.

\n

If the destination is specified, but no pipe is set up for it, then\nthe method does nothing.

\n
const fs = require('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])`", "type": "method", "name": "unshift", "meta": { "added": [ "v0.9.11" ], "changes": [ { "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|Uint8Array|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`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value.", "name": "chunk", "type": "Buffer|Uint8Array|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`, `Uint8Array` 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'`." } ] } ], "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.

\n

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.

\n

The stream.unshift(chunk) method cannot be called after the 'end' event\nhas been emitted or a runtime error will be thrown.

\n

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.

\n
// 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('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.match(/\\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      } else {\n        // Still reading the header.\n        header += str;\n      }\n    }\n  }\n}\n
\n

Unlike 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.

" }, { "textRaw": "`readable.wrap(stream)`", "type": "method", "name": "wrap", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] } ], "desc": "

Prior to Node.js 0.10, streams did not implement the entire stream module API\nas it is currently defined. (See Compatibility for more information.)

\n

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.

\n

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.

\n
const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('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]()`", "type": "method", "name": "[Symbol.asyncIterator]", "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": [ { "return": { "textRaw": "Returns: {AsyncIterator} to fully consume the stream.", "name": "return", "type": "AsyncIterator", "desc": "to fully consume the stream." }, "params": [] } ], "desc": "
const fs = require('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
\n

If 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 KB of data because no highWaterMark option is provided to\nfs.createReadStream().

" }, { "textRaw": "`readable.iterator([options])`", "type": "method", "name": "iterator", "meta": { "added": [ "v16.3.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator} to consume the stream.", "name": "return", "type": "AsyncIterator", "desc": "to consume the stream." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`destroyOnReturn` {boolean} When set to `false`, calling `return` on the async iterator, or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. **Default:** `true`.", "name": "destroyOnReturn", "type": "boolean", "default": "`true`", "desc": "When set to `false`, calling `return` on the async iterator, or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream." }, { "textRaw": "`destroyOnError` {boolean} When set to `false`, if the stream emits an error while it's being iterated, the iterator will not destroy the stream. **Default:** `true`.", "name": "destroyOnError", "type": "boolean", "default": "`true`", "desc": "When set to `false`, if the stream emits an error while it's being iterated, the iterator will not destroy the stream." } ] } ] } ], "desc": "

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.

\n
const { Readable } = require('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
" } ], "properties": [ { "textRaw": "`destroyed` {boolean}", "type": "boolean", "name": "destroyed", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

Is true after readable.destroy() has been called.

" }, { "textRaw": "`readable` {boolean}", "type": "boolean", "name": "readable", "meta": { "added": [ "v11.4.0" ], "changes": [] }, "desc": "

Is true if it is safe to call readable.read(), which means\nthe stream has not been destroyed or emitted 'error' or 'end'.

" }, { "textRaw": "`readableDidRead` {boolean}", "type": "boolean", "name": "readableDidRead", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "desc": "

Allows determining if the stream has been or is about to be read.\nReturns true if 'data', 'end', 'error' or 'close' has been\nemitted.

" }, { "textRaw": "`readableEncoding` {null|string}", "type": "null|string", "name": "readableEncoding", "meta": { "added": [ "v12.7.0" ], "changes": [] }, "desc": "

Getter for the property encoding of a given Readable stream. The encoding\nproperty can be set using the readable.setEncoding() method.

" }, { "textRaw": "`readableEnded` {boolean}", "type": "boolean", "name": "readableEnded", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

Becomes true when 'end' event is emitted.

" }, { "textRaw": "`readableFlowing` {boolean}", "type": "boolean", "name": "readableFlowing", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

This property reflects the current state of a Readable stream as described\nin the Three states section.

" }, { "textRaw": "`readableHighWaterMark` {number}", "type": "number", "name": "readableHighWaterMark", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "desc": "

Returns the value of highWaterMark passed when creating this Readable.

" }, { "textRaw": "`readableLength` {number}", "type": "number", "name": "readableLength", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "`readableObjectMode` {boolean}", "type": "boolean", "name": "readableObjectMode", "meta": { "added": [ "v12.3.0" ], "changes": [] }, "desc": "

Getter for the property objectMode of a given Readable stream.

" } ] } ], "type": "misc", "displayName": "Readable streams" }, { "textRaw": "Duplex and transform streams", "name": "duplex_and_transform_streams", "classes": [ { "textRaw": "Class: `stream.Duplex`", "type": "class", "name": "stream.Duplex", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v6.8.0", "pr-url": "https://github.com/nodejs/node/pull/8834", "description": "Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`." } ] }, "desc": "

Duplex streams are streams that implement both the Readable and\nWritable interfaces.

\n

Examples of Duplex streams include:

\n" }, { "textRaw": "Class: `stream.Transform`", "type": "class", "name": "stream.Transform", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "desc": "

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.

\n

Examples of Transform streams include:

\n", "methods": [ { "textRaw": "`transform.destroy([error])`", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/29197", "description": "Work as a no-op on a stream that has already been destroyed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ] } ], "desc": "

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.

\n

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'.

" } ] } ], "type": "misc", "displayName": "Duplex and transform streams" } ], "methods": [ { "textRaw": "`stream.finished(stream[, options], callback)`", "type": "method", "name": "finished", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "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." }, "params": [ { "textRaw": "`stream` {Stream} A readable and/or writable stream.", "name": "stream", "type": "Stream", "desc": "A readable and/or writable stream." }, { "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." } ] }, { "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." } ] } ], "desc": "

A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

\n
const { finished } = require('stream');\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
\n

Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

\n

The finished API provides promise version:

\n
const { finished } = require('stream/promises');\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
\n

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:

\n
const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n
" }, { "textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {Stream}", "name": "return", "type": "Stream" }, "params": [ { "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", "name": "streams", "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" }, { "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", "name": "source", "type": "Stream|Iterable|AsyncIterable|Function", "options": [ { "textRaw": "Returns: {Iterable|AsyncIterable}", "name": "return", "type": "Iterable|AsyncIterable" } ] }, { "textRaw": "`...transforms` {Stream|Function}", "name": "...transforms", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable}", "name": "return", "type": "AsyncIterable" } ] }, { "textRaw": "`destination` {Stream|Function}", "name": "destination", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable|Promise}", "name": "return", "type": "AsyncIterable|Promise" } ] }, { "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`." } ] } ] } ], "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.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('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
\n

The pipeline API provides a promise version, which can also\nreceive an options argument as the last parameter with a\nsignal <AbortSignal> property. When the signal is aborted,\ndestroy will be called on the underlying pipeline, with an\nAbortError.

\n
const { pipeline } = require('stream/promises');\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
\n

To use an AbortSignal, pass it inside an options object,\nas the last argument:

\n
const { pipeline } = require('stream/promises');\n\nasync function run() {\n  const ac = new AbortController();\n  const options = {\n    signal: ac.signal,\n  };\n\n  setTimeout(() => ac.abort(), 1);\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    options,\n  );\n}\n\nrun().catch(console.error); // AbortError\n
\n

The pipeline API also supports async generators:

\n
const { pipeline } = require('stream/promises');\nconst fs = require('fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield chunk.toUpperCase();\n      }\n    },\n    fs.createWriteStream('uppercase.txt')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
\n

stream.pipeline() will call stream.destroy(err) on all streams except:

\n
    \n
  • Readable streams which have emitted 'end' or 'close'.
  • \n
  • Writable streams which have emitted 'finish' or 'close'.
  • \n
\n

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.

" }, { "textRaw": "`stream.pipeline(streams, callback)`", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [ { "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": [ { "return": { "textRaw": "Returns: {Stream}", "name": "return", "type": "Stream" }, "params": [ { "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", "name": "streams", "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" }, { "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", "name": "source", "type": "Stream|Iterable|AsyncIterable|Function", "options": [ { "textRaw": "Returns: {Iterable|AsyncIterable}", "name": "return", "type": "Iterable|AsyncIterable" } ] }, { "textRaw": "`...transforms` {Stream|Function}", "name": "...transforms", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable}", "name": "return", "type": "AsyncIterable" } ] }, { "textRaw": "`destination` {Stream|Function}", "name": "destination", "type": "Stream|Function", "options": [ { "textRaw": "`source` {AsyncIterable}", "name": "source", "type": "AsyncIterable" }, { "textRaw": "Returns: {AsyncIterable|Promise}", "name": "return", "type": "AsyncIterable|Promise" } ] }, { "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`." } ] } ] } ], "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.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('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
\n

The pipeline API provides a promise version, which can also\nreceive an options argument as the last parameter with a\nsignal <AbortSignal> property. When the signal is aborted,\ndestroy will be called on the underlying pipeline, with an\nAbortError.

\n
const { pipeline } = require('stream/promises');\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
\n

To use an AbortSignal, pass it inside an options object,\nas the last argument:

\n
const { pipeline } = require('stream/promises');\n\nasync function run() {\n  const ac = new AbortController();\n  const options = {\n    signal: ac.signal,\n  };\n\n  setTimeout(() => ac.abort(), 1);\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    options,\n  );\n}\n\nrun().catch(console.error); // AbortError\n
\n

The pipeline API also supports async generators:

\n
const { pipeline } = require('stream/promises');\nconst fs = require('fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield chunk.toUpperCase();\n      }\n    },\n    fs.createWriteStream('uppercase.txt')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
\n

stream.pipeline() will call stream.destroy(err) on all streams except:

\n
    \n
  • Readable streams which have emitted 'end' or 'close'.
  • \n
  • Writable streams which have emitted 'finish' or 'close'.
  • \n
\n

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.

" }, { "textRaw": "`stream.Readable.from(iterable, [options])`", "type": "method", "name": "from", "meta": { "added": [ "v12.3.0", "v10.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Readable}", "name": "return", "type": "stream.Readable" }, "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`." } ] } ], "desc": "

A utility method for creating readable streams out of iterators.

\n
const { Readable } = require('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
\n

Calling 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.

" }, { "textRaw": "`stream.addAbortSignal(signal, stream)`", "type": "method", "name": "addAbortSignal", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`signal` {AbortSignal} A signal representing possible cancellation", "name": "signal", "type": "AbortSignal", "desc": "A signal representing possible cancellation" }, { "textRaw": "`stream` {Stream} a stream to attach a signal to", "name": "stream", "type": "Stream", "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.

\n

Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the stream.

\n
const fs = require('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
\n

Or using an AbortSignal with a readable stream as an async iterable:

\n
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
" } ] }, { "textRaw": "API for stream implementers", "name": "API for stream implementers", "type": "misc", "desc": "

The stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.

\n

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:

\n\n
const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor({ highWaterMark, ...options }) {\n    super({ highWaterMark });\n    // ...\n  }\n}\n
\n

When 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.

\n

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-caseClassMethod(s) to implement
Reading onlyReadable_read()
Writing onlyWritable_write(), _writev(), _final()
Reading and writingDuplex_read(), _write(), _writev(), _final()
Operate on written data, then read the resultTransform_transform(), _flush(), _final()
\n

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.

\n

Avoid 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.

", "miscs": [ { "textRaw": "Simplified construction", "name": "simplified_construction", "meta": { "added": [ "v1.2.0" ], "changes": [] }, "desc": "

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.

\n
const { Writable } = require('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
", "type": "misc", "displayName": "Simplified construction" }, { "textRaw": "Implementing a writable stream", "name": "implementing_a_writable_stream", "desc": "

The stream.Writable class is extended to implement a Writable stream.

\n

Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() and/or writable._writev()\nmethod.

", "ctors": [ { "textRaw": "`new stream.Writable([options])`", "type": "ctor", "name": "stream.Writable", "meta": { "changes": [ { "version": "v15.5.0", "pr-url": "https://github.com/nodejs/node/pull/36431", "description": "support passing in an AbortSignal." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30623", "description": "Change `autoDestroy` option default to `true`." }, { "version": [ "v11.2.0", "v10.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/22795", "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors." }, { "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." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16 KB), or `16` for `objectMode` streams.", "name": "highWaterMark", "type": "number", "default": "`16384` (16 KB), or `16` for `objectMode` streams", "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`." }, { "textRaw": "`decodeStrings` {boolean} Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted. **Default:** `true`.", "name": "decodeStrings", "type": "boolean", "default": "`true`", "desc": "Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted." }, { "textRaw": "`defaultEncoding` {string} The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]. **Default:** `'utf8'`.", "name": "defaultEncoding", "type": "string", "default": "`'utf8'`", "desc": "The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]." }, { "textRaw": "`objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation. **Default:** `false`.", "name": "objectMode", "type": "boolean", "default": "`false`", "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation." }, { "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", "name": "emitClose", "type": "boolean", "default": "`true`", "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." }, { "textRaw": "`write` {Function} Implementation for the [`stream._write()`][stream-_write] method.", "name": "write", "type": "Function", "desc": "Implementation for the [`stream._write()`][stream-_write] method." }, { "textRaw": "`writev` {Function} Implementation for the [`stream._writev()`][stream-_writev] method.", "name": "writev", "type": "Function", "desc": "Implementation for the [`stream._writev()`][stream-_writev] method." }, { "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][writable-_destroy] method.", "name": "destroy", "type": "Function", "desc": "Implementation for the [`stream._destroy()`][writable-_destroy] method." }, { "textRaw": "`final` {Function} Implementation for the [`stream._final()`][stream-_final] method.", "name": "final", "type": "Function", "desc": "Implementation for the [`stream._final()`][stream-_final] method." }, { "textRaw": "`construct` {Function} Implementation for the [`stream._construct()`][writable-_construct] method.", "name": "construct", "type": "Function", "desc": "Implementation for the [`stream._construct()`][writable-_construct] method." }, { "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `true`.", "name": "autoDestroy", "type": "boolean", "default": "`true`", "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." }, { "textRaw": "`signal` {AbortSignal} A signal representing possible cancellation.", "name": "signal", "type": "AbortSignal", "desc": "A signal representing possible cancellation." } ] } ] } ], "desc": "\n
const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Writable } = require('stream');\nconst util = require('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
\n

Or, using the simplified constructor approach:

\n
const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  }\n});\n
\n

Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the writeable stream.

\n
const { Writable } = require('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)`", "type": "method", "name": "_construct", "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.

\n

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.

\n
const { Writable } = require('stream');\nconst fs = require('fs');\n\nclass WriteStream extends Writable {\n  constructor(filename) {\n    super();\n    this.filename = filename;\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  _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)`", "type": "method", "name": "_write", "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()`][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()`][stream-write].", "name": "chunk", "type": "Buffer|string|any", "desc": "The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][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()`][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.

\n

Transform streams provide their own implementation of the\nwritable._write().

\n

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.

\n

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.

\n

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.

\n

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.

\n

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.

" }, { "textRaw": "`writable._writev(chunks, callback)`", "type": "method", "name": "_writev", "signatures": [ { "params": [ { "textRaw": "`chunks` {Object[]} The data to be written. The value is an array of {Object} that each represent a discrete chunk of data to write. The properties of these objects are:", "name": "chunks", "type": "Object[]", "desc": "The data to be written. The value is an array of {Object} that each represent a discrete chunk of data to write. The properties of these objects are:", "options": [ { "textRaw": "`chunk` {Buffer|string} A buffer instance or string containing the data to be written. The `chunk` will be a string if the `Writable` was created with the `decodeStrings` option set to `false` and a string was passed to `write()`.", "name": "chunk", "type": "Buffer|string", "desc": "A buffer instance or string containing the data to be written. The `chunk` will be a string if the `Writable` was created with the `decodeStrings` option set to `false` and a string was passed to `write()`." }, { "textRaw": "`encoding` {string} The character encoding of the `chunk`. If `chunk` is a `Buffer`, the `encoding` will be `'buffer'`.", "name": "encoding", "type": "string", "desc": "The character encoding of the `chunk`. If `chunk` is a `Buffer`, the `encoding` will be `'buffer'`." } ] }, { "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks." } ] } ], "desc": "

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.

\n

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().

\n

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.

" }, { "textRaw": "`writable._destroy(err, callback)`", "type": "method", "name": "_destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {Error} A possible error.", "name": "err", "type": "Error", "desc": "A possible error." }, { "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." } ] } ], "desc": "

The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.

" }, { "textRaw": "`writable._final(callback)`", "type": "method", "name": "_final", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when finished writing any remaining data.", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when finished writing any remaining data." } ] } ], "desc": "

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.

\n

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.

" } ], "modules": [ { "textRaw": "Errors while writing", "name": "errors_while_writing", "desc": "

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.

\n

If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.

\n
const { Writable } = require('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
", "type": "module", "displayName": "Errors while writing" }, { "textRaw": "An example writable stream", "name": "an_example_writable_stream", "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:

\n
const { Writable } = require('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
", "type": "module", "displayName": "An example writable stream" }, { "textRaw": "Decoding buffers in a writable stream", "name": "decoding_buffers_in_a_writable_stream", "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.

\n
const { Writable } = require('stream');\nconst { StringDecoder } = require('string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(options && 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
", "type": "module", "displayName": "Decoding buffers in a writable stream" } ], "type": "misc", "displayName": "Implementing a writable stream" }, { "textRaw": "Implementing a readable stream", "name": "implementing_a_readable_stream", "desc": "

The stream.Readable class is extended to implement a Readable stream.

\n

Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.

", "ctors": [ { "textRaw": "`new stream.Readable([options])`", "type": "ctor", "name": "stream.Readable", "meta": { "changes": [ { "version": "v15.5.0", "pr-url": "https://github.com/nodejs/node/pull/36431", "description": "support passing in an AbortSignal." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30623", "description": "Change `autoDestroy` option default to `true`." }, { "version": [ "v11.2.0", "v10.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/22795", "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. **Default:** `16384` (16 KB), or `16` for `objectMode` streams.", "name": "highWaterMark", "type": "number", "default": "`16384` (16 KB), or `16` for `objectMode` streams", "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource." }, { "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. **Default:** `null`.", "name": "encoding", "type": "string", "default": "`null`", "desc": "If specified, then buffers will be decoded to strings using the specified encoding." }, { "textRaw": "`objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`. **Default:** `false`.", "name": "objectMode", "type": "boolean", "default": "`false`", "desc": "Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`." }, { "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", "name": "emitClose", "type": "boolean", "default": "`true`", "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." }, { "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method.", "name": "read", "type": "Function", "desc": "Implementation for the [`stream._read()`][stream-_read] method." }, { "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][readable-_destroy] method.", "name": "destroy", "type": "Function", "desc": "Implementation for the [`stream._destroy()`][readable-_destroy] method." }, { "textRaw": "`construct` {Function} Implementation for the [`stream._construct()`][readable-_construct] method.", "name": "construct", "type": "Function", "desc": "Implementation for the [`stream._construct()`][readable-_construct] method." }, { "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `true`.", "name": "autoDestroy", "type": "boolean", "default": "`true`", "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." }, { "textRaw": "`signal` {AbortSignal} A signal representing possible cancellation.", "name": "signal", "type": "AbortSignal", "desc": "A signal representing possible cancellation." } ] } ] } ], "desc": "\n
const { Readable } = require('stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor.\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Readable } = require('stream');\nconst util = require('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
\n

Or, using the simplified constructor approach:

\n
const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  }\n});\n
\n

Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the readable created.

\n
const { Readable } = require('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)`", "type": "method", "name": "_construct", "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.

\n

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.

\n
const { Readable } = require('stream');\nconst fs = require('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)`", "type": "method", "name": "_read", "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.

\n

All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.

\n

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.

\n

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.

\n

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).

\n

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.

" }, { "textRaw": "`readable._destroy(err, callback)`", "type": "method", "name": "_destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {Error} A possible error.", "name": "err", "type": "Error", "desc": "A possible error." }, { "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." } ] } ], "desc": "

The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.

" }, { "textRaw": "`readable.push(chunk[, encoding])`", "type": "method", "name": "push", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if additional chunks of data may continue to be pushed; `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if additional chunks of data may continue to be pushed; `false` otherwise." }, "params": [ { "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value.", "name": "chunk", "type": "Buffer|Uint8Array|string|null|any", "desc": "Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. 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'`." } ] } ], "desc": "

When chunk is a Buffer, Uint8Array or string, the chunk of data will\nbe 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.

\n

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.

\n

When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.

\n

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:

\n
// `_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
\n

The readable.push() method is used to push the content\ninto the internal buffer. It can be driven by the readable._read() method.

\n

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.

" } ], "modules": [ { "textRaw": "Errors while reading", "name": "errors_while_reading", "desc": "

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.

\n
const { Readable } = require('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
", "type": "module", "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.

\n
const { Readable } = require('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
" } ], "type": "misc", "displayName": "Implementing a readable stream" }, { "textRaw": "Implementing a duplex stream", "name": "implementing_a_duplex_stream", "desc": "

A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.

\n

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).

\n

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.

\n

Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.

", "ctors": [ { "textRaw": "`new stream.Duplex(options)`", "type": "ctor", "name": "stream.Duplex", "meta": { "changes": [ { "version": "v8.4.0", "pr-url": "https://github.com/nodejs/node/pull/14636", "description": "The `readableHighWaterMark` and `writableHighWaterMark` options are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "name": "options", "type": "Object", "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "options": [ { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. **Default:** `true`.", "name": "allowHalfOpen", "type": "boolean", "default": "`true`", "desc": "If set to `false`, then the stream will automatically end the writable side when the readable side ends." }, { "textRaw": "`readable` {boolean} Sets whether the `Duplex` should be readable. **Default:** `true`.", "name": "readable", "type": "boolean", "default": "`true`", "desc": "Sets whether the `Duplex` should be readable." }, { "textRaw": "`writable` {boolean} Sets whether the `Duplex` should be writable. **Default:** `true`.", "name": "writable", "type": "boolean", "default": "`true`", "desc": "Sets whether the `Duplex` should be writable." }, { "textRaw": "`readableObjectMode` {boolean} Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", "name": "readableObjectMode", "type": "boolean", "default": "`false`", "desc": "Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`writableObjectMode` {boolean} Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", "name": "writableObjectMode", "type": "boolean", "default": "`false`", "desc": "Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`readableHighWaterMark` {number} Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.", "name": "readableHighWaterMark", "type": "number", "desc": "Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided." }, { "textRaw": "`writableHighWaterMark` {number} Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.", "name": "writableHighWaterMark", "type": "number", "desc": "Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided." } ] } ] } ], "desc": "\n
const { Duplex } = require('stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Duplex } = require('stream');\nconst util = require('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
\n

Or, using the simplified constructor approach:

\n
const { Duplex } = require('stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
\n

When using pipeline:

\n
const { Transform, pipeline } = require('stream');\nconst fs = require('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      } 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", "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.

\n
const { Duplex } = require('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
\n

The 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.

", "type": "module", "displayName": "An example duplex stream" }, { "textRaw": "Object mode duplex streams", "name": "object_mode_duplex_streams", "desc": "

For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.

\n

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.

\n
const { Transform } = require('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
", "type": "module", "displayName": "Object mode duplex streams" } ], "type": "misc", "displayName": "Implementing a duplex stream" }, { "textRaw": "Implementing a transform stream", "name": "implementing_a_transform_stream", "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.

\n

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.

\n

The stream.Transform class is extended to implement a Transform stream.

\n

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.

\n

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.

", "ctors": [ { "textRaw": "`new stream.Transform([options])`", "type": "ctor", "name": "stream.Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "name": "options", "type": "Object", "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "options": [ { "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method.", "name": "transform", "type": "Function", "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." }, { "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method.", "name": "flush", "type": "Function", "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." } ] } ] } ], "desc": "\n
const { Transform } = require('stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Transform } = require('stream');\nconst util = require('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
\n

Or, using the simplified constructor approach:

\n
const { Transform } = require('stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  }\n});\n
" } ], "events": [ { "textRaw": "Event: `'end'`", "type": "event", "name": "end", "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.

" }, { "textRaw": "Event: `'finish'`", "type": "event", "name": "finish", "params": [], "desc": "

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.

" } ], "methods": [ { "textRaw": "`transform._flush(callback)`", "type": "method", "name": "_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed." } ] } ], "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.

\n

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.

\n

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.

\n

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.

\n

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.

" }, { "textRaw": "`transform._transform(chunk, encoding, callback)`", "type": "method", "name": "_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][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()`][stream-write].", "name": "chunk", "type": "Buffer|string|any", "desc": "The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][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()`][stream-write]." }, { "textRaw": "`encoding` {string} If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case.", "name": "encoding", "type": "string", "desc": "If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case." }, { "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed." } ] } ], "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.

\n

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.

\n

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.

\n

It is possible that no output is generated from any given chunk of input data.

\n

The 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. In other words, the following are equivalent:

\n
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
\n

The 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.

\n

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.

" } ], "classes": [ { "textRaw": "Class: `stream.PassThrough`", "type": "class", "name": "stream.PassThrough", "desc": "

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.

" } ], "type": "misc", "displayName": "Implementing a transform stream" } ] }, { "textRaw": "Additional notes", "name": "Additional notes", "type": "misc", "miscs": [ { "textRaw": "Streams compatibility with async generators and async iterators", "name": "streams_compatibility_with_async_generators_and_async_iterators", "desc": "

With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.

\n

Some 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", "desc": "
(async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();\n
\n

Async iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.

", "type": "module", "displayName": "Consuming readable streams with async iterators" }, { "textRaw": "Creating readable streams with async generators", "name": "creating_readable_streams_with_async_generators", "desc": "

A Node.js readable stream can be created from an asynchronous generator using\nthe Readable.from() utility method:

\n
const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'a';\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
", "type": "module", "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:

\n
const fs = require('fs');\nconst { pipeline } = require('stream');\nconst { pipeline: pipelinePromise } = require('stream/promises');\n\nconst writable = fs.createWriteStream('./file');\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});\n\n// Promise Pattern\npipelinePromise(iterator, writable)\n  .then((value) => {\n    console.log(value, 'value returned');\n  })\n  .catch(console.error);\n
" } ], "type": "misc", "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.

\n
    \n
  • Rather than waiting for calls to the 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.
  • \n
  • The 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.
  • \n
\n

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.

\n

While most applications will continue to function normally, this introduces an\nedge case in the following conditions:

\n
    \n
  • No 'data' event listener is added.
  • \n
  • The stream.resume() method is never called.
  • \n
  • The stream is not piped to any writable destination.
  • \n
\n

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
\n

Prior 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.

\n

The workaround in this situation is to call the\nstream.resume() method to begin the flow of data:

\n
// 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
\n

In 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.

" }, { "textRaw": "`highWaterMark` discrepancy after calling `readable.setEncoding()`", "name": "`highwatermark`_discrepancy_after_calling_`readable.setencoding()`", "desc": "

The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.

\n

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.

\n

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.

", "type": "misc", "displayName": "`highWaterMark` discrepancy after calling `readable.setEncoding()`" } ], "methods": [ { "textRaw": "`readable.read(0)`", "type": "method", "name": "read", "signatures": [ { "params": [] } ], "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.

\n

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.

\n

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.

" }, { "textRaw": "`readable.push('')`", "type": "method", "name": "push", "signatures": [ { "params": [] } ], "desc": "

Use of readable.push('') is not recommended.

\n

Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because 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.

" } ] } ], "type": "module", "displayName": "Stream", "source": "doc/api/stream.md" }, { "textRaw": "String decoder", "name": "string_decoder", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/string_decoder.js

\n

The string_decoder module provides an API for decoding Buffer objects into\nstrings in a manner that preserves encoded multi-byte UTF-8 and UTF-16\ncharacters. It can be accessed using:

\n
const { StringDecoder } = require('string_decoder');\n
\n

The following example shows the basic use of the StringDecoder class.

\n
const { StringDecoder } = require('string_decoder');\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));\n
\n

When 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.

\n

In the following example, the three UTF-8 encoded bytes of the European Euro\nsymbol () are written over three separate operations:

\n
const { StringDecoder } = require('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])));\n
", "classes": [ { "textRaw": "Class: `StringDecoder`", "type": "class", "name": "StringDecoder", "methods": [ { "textRaw": "`stringDecoder.end([buffer])`", "type": "method", "name": "end", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." } ] } ], "desc": "

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.

\n

If 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.

" }, { "textRaw": "`stringDecoder.write(buffer)`", "type": "method", "name": "write", "meta": { "added": [ "v0.1.99" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/9618", "description": "Each invalid character is now replaced by a single replacement character instead of one for each individual byte." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode." } ] } ], "desc": "

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().

" } ], "signatures": [ { "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." } ], "desc": "

Creates a new StringDecoder instance.

" } ] } ], "type": "module", "displayName": "String decoder", "source": "doc/api/string_decoder.md" }, { "textRaw": "Timers", "name": "timers", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/timers.js

\n

The timer module exposes a global API for scheduling functions to\nbe called at some future period of time. Because the timer functions are\nglobals, there is no need to call require('timers') to use the API.

\n

The timer functions within Node.js implement a similar API as the timers API\nprovided by Web Browsers but use a different internal implementation that is\nbuilt around the Node.js Event Loop.

", "classes": [ { "textRaw": "Class: `Immediate`", "type": "class", "name": "Immediate", "desc": "

This object is created internally and is returned from setImmediate(). It\ncan be passed to clearImmediate() in order to cancel the scheduled\nactions.

\n

By default, when an immediate is scheduled, the Node.js event loop will continue\nrunning as long as the immediate is active. The Immediate object returned by\nsetImmediate() exports both immediate.ref() and immediate.unref()\nfunctions that can be used to control this default behavior.

", "methods": [ { "textRaw": "`immediate.hasRef()`", "type": "method", "name": "hasRef", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

If true, the Immediate object will keep the Node.js event loop active.

" }, { "textRaw": "`immediate.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v9.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Immediate} a reference to `immediate`", "name": "return", "type": "Immediate", "desc": "a reference to `immediate`" }, "params": [] } ], "desc": "

When called, requests that the Node.js event loop not exit so long as the\nImmediate is active. Calling immediate.ref() multiple times will have no\neffect.

\n

By default, all Immediate objects are \"ref'ed\", making it normally unnecessary\nto call immediate.ref() unless immediate.unref() had been called previously.

" }, { "textRaw": "`immediate.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v9.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Immediate} a reference to `immediate`", "name": "return", "type": "Immediate", "desc": "a reference to `immediate`" }, "params": [] } ], "desc": "

When called, the active Immediate object will not require the Node.js event\nloop to remain active. If there is no other activity keeping the event loop\nrunning, the process may exit before the Immediate object's callback is\ninvoked. Calling immediate.unref() multiple times will have no effect.

" } ] }, { "textRaw": "Class: `Timeout`", "type": "class", "name": "Timeout", "desc": "

This object is created internally and is returned from setTimeout() and\nsetInterval(). It can be passed to either clearTimeout() or\nclearInterval() in order to cancel the scheduled actions.

\n

By default, when a timer is scheduled using either setTimeout() or\nsetInterval(), the Node.js event loop will continue running as long as the\ntimer is active. Each of the Timeout objects returned by these functions\nexport both timeout.ref() and timeout.unref() functions that can be used to\ncontrol this default behavior.

", "methods": [ { "textRaw": "`timeout.hasRef()`", "type": "method", "name": "hasRef", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

If true, the Timeout object will keep the Node.js event loop active.

" }, { "textRaw": "`timeout.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} a reference to `timeout`", "name": "return", "type": "Timeout", "desc": "a reference to `timeout`" }, "params": [] } ], "desc": "

When called, requests that the Node.js event loop not exit so long as the\nTimeout is active. Calling timeout.ref() multiple times will have no effect.

\n

By default, all Timeout objects are \"ref'ed\", making it normally unnecessary\nto call timeout.ref() unless timeout.unref() had been called previously.

" }, { "textRaw": "`timeout.refresh()`", "type": "method", "name": "refresh", "meta": { "added": [ "v10.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} a reference to `timeout`", "name": "return", "type": "Timeout", "desc": "a reference to `timeout`" }, "params": [] } ], "desc": "

Sets the timer's start time to the current time, and reschedules the timer to\ncall its callback at the previously specified duration adjusted to the current\ntime. This is useful for refreshing a timer without allocating a new\nJavaScript object.

\n

Using this on a timer that has already called its callback will reactivate the\ntimer.

" }, { "textRaw": "`timeout.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} a reference to `timeout`", "name": "return", "type": "Timeout", "desc": "a reference to `timeout`" }, "params": [] } ], "desc": "

When called, the active Timeout object will not require the Node.js event loop\nto remain active. If there is no other activity keeping the event loop running,\nthe process may exit before the Timeout object's callback is invoked. Calling\ntimeout.unref() multiple times will have no effect.

\n

Calling timeout.unref() creates an internal timer that will wake the Node.js\nevent loop. Creating too many of these can adversely impact performance\nof the Node.js application.

" }, { "textRaw": "`timeout[Symbol.toPrimitive]()`", "type": "method", "name": "[Symbol.toPrimitive]", "meta": { "added": [ "v14.9.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} a number that can be used to reference this `timeout`", "name": "return", "type": "integer", "desc": "a number that can be used to reference this `timeout`" }, "params": [] } ], "desc": "

Coerce a Timeout to a primitive. The primitive can be used to\nclear the Timeout. The primitive can only be used in the\nsame thread where the timeout was created. Therefore, to use it\nacross worker_threads it must first be passed to the correct\nthread. This allows enhanced compatibility with browser\nsetTimeout() and setInterval() implementations.

" } ] } ], "modules": [ { "textRaw": "Scheduling timers", "name": "scheduling_timers", "desc": "

A timer in Node.js is an internal construct that calls a given function after\na certain period of time. When a timer's function is called varies depending on\nwhich method was used to create the timer and what other work the Node.js\nevent loop is doing.

", "methods": [ { "textRaw": "`setImmediate(callback[, ...args])`", "type": "method", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Immediate} for use with [`clearImmediate()`][]", "name": "return", "type": "Immediate", "desc": "for use with [`clearImmediate()`][]" }, "params": [ { "textRaw": "`callback` {Function} The function to call at the end of this turn of the Node.js [Event Loop][]", "name": "callback", "type": "Function", "desc": "The function to call at the end of this turn of the Node.js [Event Loop][]" }, { "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", "name": "...args", "type": "any", "desc": "Optional arguments to pass when the `callback` is called." } ] } ], "desc": "

Schedules the \"immediate\" execution of the callback after I/O events'\ncallbacks.

\n

When multiple calls to setImmediate() are made, the callback functions are\nqueued for execution in the order in which they are created. The entire callback\nqueue is processed every event loop iteration. If an immediate timer is queued\nfrom inside an executing callback, that timer will not be triggered until the\nnext event loop iteration.

\n

If callback is not a function, a TypeError will be thrown.

\n

This method has a custom variant for promises that is available using\ntimersPromises.setImmediate().

" }, { "textRaw": "`setInterval(callback[, delay[, ...args]])`", "type": "method", "name": "setInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} for use with [`clearInterval()`][]", "name": "return", "type": "Timeout", "desc": "for use with [`clearInterval()`][]" }, "params": [ { "textRaw": "`callback` {Function} The function to call when the timer elapses.", "name": "callback", "type": "Function", "desc": "The function to call when the timer elapses." }, { "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`. **Default:** `1`.", "name": "delay", "type": "number", "default": "`1`", "desc": "The number of milliseconds to wait before calling the `callback`." }, { "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", "name": "...args", "type": "any", "desc": "Optional arguments to pass when the `callback` is called." } ] } ], "desc": "

Schedules repeated execution of callback every delay milliseconds.

\n

When delay is larger than 2147483647 or less than 1, the delay will be\nset to 1. Non-integer delays are truncated to an integer.

\n

If callback is not a function, a TypeError will be thrown.

\n

This method has a custom variant for promises that is available using\ntimersPromises.setInterval().

" }, { "textRaw": "`setTimeout(callback[, delay[, ...args]])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Timeout} for use with [`clearTimeout()`][]", "name": "return", "type": "Timeout", "desc": "for use with [`clearTimeout()`][]" }, "params": [ { "textRaw": "`callback` {Function} The function to call when the timer elapses.", "name": "callback", "type": "Function", "desc": "The function to call when the timer elapses." }, { "textRaw": "`delay` {number} The number of milliseconds to wait before calling the `callback`. **Default:** `1`.", "name": "delay", "type": "number", "default": "`1`", "desc": "The number of milliseconds to wait before calling the `callback`." }, { "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called.", "name": "...args", "type": "any", "desc": "Optional arguments to pass when the `callback` is called." } ] } ], "desc": "

Schedules execution of a one-time callback after delay milliseconds.

\n

The callback will likely not be invoked in precisely delay milliseconds.\nNode.js makes no guarantees about the exact timing of when callbacks will fire,\nnor of their ordering. The callback will be called as close as possible to the\ntime specified.

\n

When delay is larger than 2147483647 or less than 1, the delay\nwill be set to 1. Non-integer delays are truncated to an integer.

\n

If callback is not a function, a TypeError will be thrown.

\n

This method has a custom variant for promises that is available using\ntimersPromises.setTimeout().

" } ], "type": "module", "displayName": "Scheduling timers" }, { "textRaw": "Cancelling timers", "name": "cancelling_timers", "desc": "

The setImmediate(), setInterval(), and setTimeout() methods\neach return objects that represent the scheduled timers. These can be used to\ncancel the timer and prevent it from triggering.

\n

For the promisified variants of setImmediate() and setTimeout(),\nan AbortController may be used to cancel the timer. When canceled, the\nreturned Promises will be rejected with an 'AbortError'.

\n

For setImmediate():

\n
const { setImmediate: setImmediatePromise } = require('timers/promises');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nsetImmediatePromise('foobar', { signal })\n  .then(console.log)\n  .catch((err) => {\n    if (err.name === 'AbortError')\n      console.log('The immediate was aborted');\n  });\n\nac.abort();\n
\n

For setTimeout():

\n
const { setTimeout: setTimeoutPromise } = require('timers/promises');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nsetTimeoutPromise(1000, 'foobar', { signal })\n  .then(console.log)\n  .catch((err) => {\n    if (err.name === 'AbortError')\n      console.log('The timeout was aborted');\n  });\n\nac.abort();\n
", "methods": [ { "textRaw": "`clearImmediate(immediate)`", "type": "method", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`immediate` {Immediate} An `Immediate` object as returned by [`setImmediate()`][].", "name": "immediate", "type": "Immediate", "desc": "An `Immediate` object as returned by [`setImmediate()`][]." } ] } ], "desc": "

Cancels an Immediate object created by setImmediate().

" }, { "textRaw": "`clearInterval(timeout)`", "type": "method", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`timeout` {Timeout|string|number} A `Timeout` object as returned by [`setInterval()`][] or the [primitive][] of the `Timeout` object as a string or a number.", "name": "timeout", "type": "Timeout|string|number", "desc": "A `Timeout` object as returned by [`setInterval()`][] or the [primitive][] of the `Timeout` object as a string or a number." } ] } ], "desc": "

Cancels a Timeout object created by setInterval().

" }, { "textRaw": "`clearTimeout(timeout)`", "type": "method", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`timeout` {Timeout|string|number} A `Timeout` object as returned by [`setTimeout()`][] or the [primitive][] of the `Timeout` object as a string or a number.", "name": "timeout", "type": "Timeout|string|number", "desc": "A `Timeout` object as returned by [`setTimeout()`][] or the [primitive][] of the `Timeout` object as a string or a number." } ] } ], "desc": "

Cancels a Timeout object created by setTimeout().

" } ], "type": "module", "displayName": "Cancelling timers" }, { "textRaw": "Timers Promises API", "name": "timers_promises_api", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/38112", "description": "Graduated from experimental." } ] }, "desc": "

The timers/promises API provides an alternative set of timer functions\nthat return Promise objects. The API is accessible via\nrequire('timers/promises').

\n
import {\n  setTimeout,\n  setImmediate,\n  setInterval,\n} from 'timers/promises';\n
\n
const {\n  setTimeout,\n  setImmediate,\n  setInterval,\n} = require('timers/promises');\n
", "methods": [ { "textRaw": "`timersPromises.setTimeout([delay[, value[, options]]])`", "type": "method", "name": "setTimeout", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`delay` {number} The number of milliseconds to wait before fulfilling the promise. **Default:** `1`.", "name": "delay", "type": "number", "default": "`1`", "desc": "The number of milliseconds to wait before fulfilling the promise." }, { "textRaw": "`value` {any} A value with which the promise is fulfilled.", "name": "value", "type": "any", "desc": "A value with which the promise is fulfilled." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` should not require the Node.js event loop to remain active. **Default:** `true`.", "name": "ref", "type": "boolean", "default": "`true`", "desc": "Set to `false` to indicate that the scheduled `Timeout` should not require the Node.js event loop to remain active." }, { "textRaw": "`signal` {AbortSignal} An optional `AbortSignal` that can be used to cancel the scheduled `Timeout`.", "name": "signal", "type": "AbortSignal", "desc": "An optional `AbortSignal` that can be used to cancel the scheduled `Timeout`." } ] } ] } ], "desc": "
import {\n  setTimeout,\n} from 'timers/promises';\n\nconst res = await setTimeout(100, 'result');\n\nconsole.log(res);  // Prints 'result'\n
\n
const {\n  setTimeout,\n} = require('timers/promises');\n\nsetTimeout(100, 'result').then((res) => {\n  console.log(res);  // Prints 'result'\n});\n
" }, { "textRaw": "`timersPromises.setImmediate([value[, options]])`", "type": "method", "name": "setImmediate", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} A value with which the promise is fulfilled.", "name": "value", "type": "any", "desc": "A value with which the promise is fulfilled." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ref` {boolean} Set to `false` to indicate that the scheduled `Immediate` should not require the Node.js event loop to remain active. **Default:** `true`.", "name": "ref", "type": "boolean", "default": "`true`", "desc": "Set to `false` to indicate that the scheduled `Immediate` should not require the Node.js event loop to remain active." }, { "textRaw": "`signal` {AbortSignal} An optional `AbortSignal` that can be used to cancel the scheduled `Immediate`.", "name": "signal", "type": "AbortSignal", "desc": "An optional `AbortSignal` that can be used to cancel the scheduled `Immediate`." } ] } ] } ], "desc": "
import {\n  setImmediate,\n} from 'timers/promises';\n\nconst res = await setImmediate('result');\n\nconsole.log(res);  // Prints 'result'\n
\n
const {\n  setImmediate,\n} = require('timers/promises');\n\nsetImmediate('result').then((res) => {\n  console.log(res);  // Prints 'result'\n});\n
" }, { "textRaw": "`timersPromises.setInterval([delay[, value[, options]]])`", "type": "method", "name": "setInterval", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Returns an async iterator that generates values in an interval of delay ms.

\n
    \n
  • delay <number> The number of milliseconds to wait between iterations.\nDefault: 1.
  • \n
  • value <any> A value with which the iterator returns.
  • \n
  • options <Object>\n
      \n
    • ref <boolean> Set to false to indicate that the scheduled Timeout\nbetween iterations should not require the Node.js event loop to\nremain active.\nDefault: true.
    • \n
    • signal <AbortSignal> An optional AbortSignal that can be used to\ncancel the scheduled Timeout between operations.
    • \n
    \n
  • \n
\n
import {\n  setInterval,\n} from 'timers/promises';\n\nconst interval = 100;\nfor await (const startTime of setInterval(interval, Date.now())) {\n  const now = Date.now();\n  console.log(now);\n  if ((now - startTime) > 1000)\n    break;\n}\nconsole.log(Date.now());\n
\n
const {\n  setInterval,\n} = require('timers/promises');\nconst interval = 100;\n\n(async function() {\n  for await (const startTime of setInterval(interval, Date.now())) {\n    const now = Date.now();\n    console.log(now);\n    if ((now - startTime) > 1000)\n      break;\n  }\n  console.log(Date.now());\n})();\n
" } ], "type": "module", "displayName": "Timers Promises API" } ], "type": "module", "displayName": "Timers", "source": "doc/api/timers.md" }, { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/tls.js

\n

The tls module provides an implementation of the Transport Layer Security\n(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.\nThe module can be accessed using:

\n
const tls = require('tls');\n
", "modules": [ { "textRaw": "TLS/SSL concepts", "name": "tls/ssl_concepts", "desc": "

The TLS/SSL is a public/private key infrastructure (PKI). For most common\ncases, each client and server must have a private key.

\n

Private keys can be generated in multiple ways. The example below illustrates\nuse of the OpenSSL command-line interface to generate a 2048-bit RSA private\nkey:

\n
openssl genrsa -out ryans-key.pem 2048\n
\n

With TLS/SSL, all servers (and some clients) must have a certificate.\nCertificates are public keys that correspond to a private key, and that are\ndigitally signed either by a Certificate Authority or by the owner of the\nprivate key (such certificates are referred to as \"self-signed\"). The first\nstep to obtaining a certificate is to create a Certificate Signing Request\n(CSR) file.

\n

The OpenSSL command-line interface can be used to generate a CSR for a private\nkey:

\n
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
\n

Once the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.

\n

Creating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
\n

Once the certificate is generated, it can be used to generate a .pfx or\n.p12 file:

\n
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n      -certfile ca-cert.pem -out ryans.pfx\n
\n

Where:

\n
    \n
  • in: is the signed certificate
  • \n
  • inkey: is the associated private key
  • \n
  • certfile: is a concatenation of all Certificate Authority (CA) certs into\na single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • \n
", "miscs": [ { "textRaw": "Perfect forward secrecy", "name": "Perfect forward secrecy", "type": "misc", "desc": "

The term forward secrecy or perfect forward secrecy describes a feature\nof key-agreement (i.e., key-exchange) methods. That is, the server and client\nkeys are used to negotiate new temporary keys that are used specifically and\nonly for the current communication session. Practically, this means that even\nif the server's private key is compromised, communication can only be decrypted\nby eavesdroppers if the attacker manages to obtain the key-pair specifically\ngenerated for the session.

\n

Perfect forward secrecy is achieved by randomly generating a key pair for\nkey-agreement on every TLS/SSL handshake (in contrast to using the same key for\nall sessions). Methods implementing this technique are called \"ephemeral\".

\n

Currently two methods are commonly used to achieve perfect forward secrecy (note\nthe character \"E\" appended to the traditional abbreviations):

\n
    \n
  • DHE: An ephemeral version of the Diffie-Hellman key-agreement protocol.
  • \n
  • ECDHE: An ephemeral version of the Elliptic Curve Diffie-Hellman\nkey-agreement protocol.
  • \n
\n

Ephemeral methods may have some performance drawbacks, because key generation\nis expensive.

\n

To use perfect forward secrecy using DHE with the tls module, it is required\nto generate Diffie-Hellman parameters and specify them with the dhparam\noption to tls.createSecureContext(). The following illustrates the use of\nthe OpenSSL command-line interface to generate such parameters:

\n
openssl dhparam -outform PEM -out dhparam.pem 2048\n
\n

If using perfect forward secrecy using ECDHE, Diffie-Hellman parameters are\nnot required and a default ECDHE curve will be used. The ecdhCurve property\ncan be used when creating a TLS Server to specify the list of names of supported\ncurves to use, see tls.createServer() for more info.

\n

Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for\nTLSv1.3, because all TLSv1.3 cipher suites use ECDHE.

" }, { "textRaw": "ALPN and SNI", "name": "ALPN and SNI", "type": "misc", "desc": "

ALPN (Application-Layer Protocol Negotiation Extension) and\nSNI (Server Name Indication) are TLS handshake extensions:

\n
    \n
  • ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)
  • \n
  • SNI: Allows the use of one TLS server for multiple hostnames with different\nSSL certificates.
  • \n
" }, { "textRaw": "Pre-shared keys", "name": "Pre-shared keys", "type": "misc", "desc": "

TLS-PSK support is available as an alternative to normal certificate-based\nauthentication. It uses a pre-shared key instead of certificates to\nauthenticate a TLS connection, providing mutual authentication.\nTLS-PSK and public key infrastructure are not mutually exclusive. Clients and\nservers can accommodate both, choosing either of them during the normal cipher\nnegotiation step.

\n

TLS-PSK is only a good choice where means exist to securely share a\nkey with every connecting machine, so it does not replace PKI\n(Public Key Infrastructure) for the majority of TLS uses.\nThe TLS-PSK implementation in OpenSSL has seen many security flaws in\nrecent years, mostly because it is used only by a minority of applications.\nPlease consider all alternative solutions before switching to PSK ciphers.\nUpon generating PSK it is of critical importance to use sufficient entropy as\ndiscussed in RFC 4086. Deriving a shared secret from a password or other\nlow-entropy sources is not secure.

\n

PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly\nspecifying a cipher suite with the ciphers option. The list of available\nciphers can be retrieved via openssl ciphers -v 'PSK'. All TLS 1.3\nciphers are eligible for PSK but currently only those that use SHA256 digest are\nsupported they can be retrieved via openssl ciphers -v -s -tls1_3 -psk.

\n

According to the RFC 4279, PSK identities up to 128 bytes in length and\nPSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0\nmaximum identity size is 128 bytes, and maximum PSK length is 256 bytes.

\n

The current implementation doesn't support asynchronous PSK callbacks due to the\nlimitations of the underlying OpenSSL API.

" }, { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

The TLS protocol allows clients to renegotiate certain aspects of the TLS\nsession. Unfortunately, session renegotiation requires a disproportionate amount\nof server-side resources, making it a potential vector for denial-of-service\nattacks.

\n

To mitigate the risk, renegotiation is limited to three times every ten minutes.\nAn 'error' event is emitted on the tls.TLSSocket instance when this\nthreshold is exceeded. The limits are configurable:

\n
    \n
  • tls.CLIENT_RENEG_LIMIT <number> Specifies the number of renegotiation\nrequests. Default: 3.
  • \n
  • tls.CLIENT_RENEG_WINDOW <number> Specifies the time renegotiation window\nin seconds. Default: 600 (10 minutes).
  • \n
\n

The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.

\n

TLSv1.3 does not support renegotiation.

" } ], "modules": [ { "textRaw": "Session resumption", "name": "session_resumption", "desc": "

Establishing a TLS session can be relatively slow. The process can be sped\nup by saving and later reusing the session state. There are several mechanisms\nto do so, discussed here from oldest to newest (and preferred).

", "modules": [ { "textRaw": "Session identifiers", "name": "session_identifiers", "desc": "

Servers generate a unique ID for new connections and\nsend it to the client. Clients and servers save the session state. When\nreconnecting, clients send the ID of their saved session state and if the server\nalso has the state for that ID, it can agree to use it. Otherwise, the server\nwill create a new session. See RFC 2246 for more information, page 23 and\n30.

\n

Resumption using session identifiers is supported by most web browsers when\nmaking HTTPS requests.

\n

For Node.js, clients wait for the 'session' event to get the session data,\nand provide the data to the session option of a subsequent tls.connect()\nto reuse the session. Servers must\nimplement handlers for the 'newSession' and 'resumeSession' events\nto save and restore the session data using the session ID as the lookup key to\nreuse sessions. To reuse sessions across load balancers or cluster workers,\nservers must use a shared session cache (such as Redis) in their session\nhandlers.

", "type": "module", "displayName": "Session identifiers" }, { "textRaw": "Session tickets", "name": "session_tickets", "desc": "

The servers encrypt the entire session state and send it\nto the client as a \"ticket\". When reconnecting, the state is sent to the server\nin the initial connection. This mechanism avoids the need for server-side\nsession cache. If the server doesn't use the ticket, for any reason (failure\nto decrypt it, it's too old, etc.), it will create a new session and send a new\nticket. See RFC 5077 for more information.

\n

Resumption using session tickets is becoming commonly supported by many web\nbrowsers when making HTTPS requests.

\n

For Node.js, clients use the same APIs for resumption with session identifiers\nas for resumption with session tickets. For debugging, if\ntls.TLSSocket.getTLSTicket() returns a value, the session data contains a\nticket, otherwise it contains client-side session state.

\n

With TLSv1.3, be aware that multiple tickets may be sent by the server,\nresulting in multiple 'session' events, see 'session' for more\ninformation.

\n

Single process servers need no specific implementation to use session tickets.\nTo use session tickets across server restarts or load balancers, servers must\nall have the same ticket keys. There are three 16-byte keys internally, but the\ntls API exposes them as a single 48-byte buffer for convenience.

\n

Its possible to get the ticket keys by calling server.getTicketKeys() on\none server instance and then distribute them, but it is more reasonable to\nsecurely generate 48 bytes of secure random data and set them with the\nticketKeys option of tls.createServer(). The keys should be regularly\nregenerated and server's keys can be reset with\nserver.setTicketKeys().

\n

Session ticket keys are cryptographic keys, and they must be stored\nsecurely. With TLS 1.2 and below, if they are compromised all sessions that\nused tickets encrypted with them can be decrypted. They should not be stored\non disk, and they should be regenerated regularly.

\n

If clients advertise support for tickets, the server will send them. The\nserver can disable tickets by supplying\nrequire('constants').SSL_OP_NO_TICKET in secureOptions.

\n

Both session identifiers and session tickets timeout, causing the server to\ncreate new sessions. The timeout can be configured with the sessionTimeout\noption of tls.createServer().

\n

For all the mechanisms, when resumption fails, servers will create new sessions.\nSince failing to resume the session does not cause TLS/HTTPS connection\nfailures, it is easy to not notice unnecessarily poor TLS performance. The\nOpenSSL CLI can be used to verify that servers are resuming sessions. Use the\n-reconnect option to openssl s_client, for example:

\n
$ openssl s_client -connect localhost:443 -reconnect\n
\n

Read through the debug output. The first connection should say \"New\", for\nexample:

\n
New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
\n

Subsequent connections should say \"Reused\", for example:

\n
Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256\n
", "type": "module", "displayName": "Session tickets" } ], "type": "module", "displayName": "Session resumption" } ], "type": "module", "displayName": "TLS/SSL concepts" }, { "textRaw": "Modifying the default TLS cipher suite", "name": "modifying_the_default_tls_cipher_suite", "desc": "

Node.js is built with a default suite of enabled and disabled TLS ciphers. This\ndefault cipher list can be configured when building Node.js to allow\ndistributions to provide their own default list.

\n

The following command can be used to show the default cipher suite:

\n
node -p crypto.constants.defaultCoreCipherList | tr ':' '\\n'\nTLS_AES_256_GCM_SHA384\nTLS_CHACHA20_POLY1305_SHA256\nTLS_AES_128_GCM_SHA256\nECDHE-RSA-AES128-GCM-SHA256\nECDHE-ECDSA-AES128-GCM-SHA256\nECDHE-RSA-AES256-GCM-SHA384\nECDHE-ECDSA-AES256-GCM-SHA384\nDHE-RSA-AES128-GCM-SHA256\nECDHE-RSA-AES128-SHA256\nDHE-RSA-AES128-SHA256\nECDHE-RSA-AES256-SHA384\nDHE-RSA-AES256-SHA384\nECDHE-RSA-AES256-SHA256\nDHE-RSA-AES256-SHA256\nHIGH\n!aNULL\n!eNULL\n!EXPORT\n!DES\n!RC4\n!MD5\n!PSK\n!SRP\n!CAMELLIA\n
\n

This default can be replaced entirely using the --tls-cipher-list\ncommand-line switch (directly, or via the NODE_OPTIONS environment\nvariable). For instance, the following makes ECDHE-RSA-AES128-GCM-SHA256:!RC4\nthe default TLS cipher suite:

\n
node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js\n\nexport NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'\nnode server.js\n
\n

The default can also be replaced on a per client or server basis using the\nciphers option from tls.createSecureContext(), which is also available\nin tls.createServer(), tls.connect(), and when creating new\ntls.TLSSockets.

\n

The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones\nthat start with 'TLS_', and specifications for TLSv1.2 and below cipher\nsuites. The TLSv1.2 ciphers support a legacy specification format, consult\nthe OpenSSL cipher list format documentation for details, but those\nspecifications do not apply to TLSv1.3 ciphers. The TLSv1.3 suites can only\nbe enabled by including their full name in the cipher list. They cannot, for\nexample, be enabled or disabled by using the legacy TLSv1.2 'EECDH' or\n'!EECDH' specification.

\n

Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3\nprotocol is significantly more secure than TLSv1.2, and will always be chosen\nover TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3\ncipher suites are enabled.

\n

The default cipher suite included within Node.js has been carefully\nselected to reflect current security best practices and risk mitigation.\nChanging the default cipher suite can have a significant impact on the security\nof an application. The --tls-cipher-list switch and ciphers option should by\nused only if absolutely necessary.

\n

The default cipher suite prefers GCM ciphers for Chrome's 'modern\ncryptography' setting and also prefers ECDHE and DHE ciphers for perfect\nforward secrecy, while offering some backward compatibility.

\n

128 bit AES is preferred over 192 and 256 bit AES in light of specific\nattacks affecting larger AES key sizes.

\n

Old clients that rely on insecure and deprecated RC4 or DES-based ciphers\n(like Internet Explorer 6) cannot complete the handshaking process with\nthe default configuration. If these clients must be supported, the\nTLS recommendations may offer a compatible cipher suite. For more details\non the format, see the OpenSSL cipher list format documentation.

\n

There are only 5 TLSv1.3 cipher suites:

\n
    \n
  • 'TLS_AES_256_GCM_SHA384'
  • \n
  • 'TLS_CHACHA20_POLY1305_SHA256'
  • \n
  • 'TLS_AES_128_GCM_SHA256'
  • \n
  • 'TLS_AES_128_CCM_SHA256'
  • \n
  • 'TLS_AES_128_CCM_8_SHA256'
  • \n
\n

The first 3 are enabled by default. The last 2 CCM-based suites are supported\nby TLSv1.3 because they may be more performant on constrained systems, but they\nare not enabled by default since they offer less security.

", "type": "module", "displayName": "Modifying the default TLS cipher suite" }, { "textRaw": "X509 Certificate Error codes", "name": "x509_certificate_error_codes", "desc": "

Multiple functions can fail due to certificate errors that are reported by\nOpenSSL. In such a case, the function provides an <Error> via its callback that\nhas the property code which can take one of the following values:

\n\n
    \n
  • 'UNABLE_TO_GET_ISSUER_CERT': Unable to get issuer certificate.
  • \n
  • 'UNABLE_TO_GET_CRL': Unable to get certificate CRL.
  • \n
  • 'UNABLE_TO_DECRYPT_CERT_SIGNATURE': Unable to decrypt certificate's\nsignature.
  • \n
  • 'UNABLE_TO_DECRYPT_CRL_SIGNATURE': Unable to decrypt CRL's signature.
  • \n
  • 'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY': Unable to decode issuer public key.
  • \n
  • 'CERT_SIGNATURE_FAILURE': Certificate signature failure.
  • \n
  • 'CRL_SIGNATURE_FAILURE': CRL signature failure.
  • \n
  • 'CERT_NOT_YET_VALID': Certificate is not yet valid.
  • \n
  • 'CERT_HAS_EXPIRED': Certificate has expired.
  • \n
  • 'CRL_NOT_YET_VALID': CRL is not yet valid.
  • \n
  • 'CRL_HAS_EXPIRED': CRL has expired.
  • \n
  • 'ERROR_IN_CERT_NOT_BEFORE_FIELD': Format error in certificate's notBefore\nfield.
  • \n
  • 'ERROR_IN_CERT_NOT_AFTER_FIELD': Format error in certificate's notAfter\nfield.
  • \n
  • 'ERROR_IN_CRL_LAST_UPDATE_FIELD': Format error in CRL's lastUpdate field.
  • \n
  • 'ERROR_IN_CRL_NEXT_UPDATE_FIELD': Format error in CRL's nextUpdate field.
  • \n
  • 'OUT_OF_MEM': Out of memory.
  • \n
  • 'DEPTH_ZERO_SELF_SIGNED_CERT': Self signed certificate.
  • \n
  • 'SELF_SIGNED_CERT_IN_CHAIN': Self signed certificate in certificate chain.
  • \n
  • 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY': Unable to get local issuer certificate.
  • \n
  • 'UNABLE_TO_VERIFY_LEAF_SIGNATURE': Unable to verify the first certificate.
  • \n
  • 'CERT_CHAIN_TOO_LONG': Certificate chain too long.
  • \n
  • 'CERT_REVOKED': Certificate revoked.
  • \n
  • 'INVALID_CA': Invalid CA certificate.
  • \n
  • 'PATH_LENGTH_EXCEEDED': Path length constraint exceeded.
  • \n
  • 'INVALID_PURPOSE': Unsupported certificate purpose.
  • \n
  • 'CERT_UNTRUSTED': Certificate not trusted.
  • \n
  • 'CERT_REJECTED': Certificate rejected.
  • \n
  • 'HOSTNAME_MISMATCH': Hostname mismatch.
  • \n
", "type": "module", "displayName": "X509 Certificate Error codes" } ], "classes": [ { "textRaw": "Class: `tls.CryptoStream`", "type": "class", "name": "tls.CryptoStream", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

The tls.CryptoStream class represents a stream of encrypted data. This class\nis deprecated and should no longer be used.

", "properties": [ { "textRaw": "`cryptoStream.bytesWritten`", "name": "bytesWritten", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "desc": "

The cryptoStream.bytesWritten property returns the total number of bytes\nwritten to the underlying socket including the bytes required for the\nimplementation of the TLS protocol.

" } ] }, { "textRaw": "Class: `tls.SecurePair`", "type": "class", "name": "tls.SecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

Returned by tls.createSecurePair().

", "events": [ { "textRaw": "Event: `'secure'`", "type": "event", "name": "secure", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [] }, "params": [], "desc": "

The 'secure' event is emitted by the SecurePair object once a secure\nconnection has been established.

\n

As with checking for the server\n'secureConnection'\nevent, pair.cleartext.authorized should be inspected to confirm whether the\ncertificate used is properly authorized.

" } ] }, { "textRaw": "Class: `tls.Server`", "type": "class", "name": "tls.Server", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "desc": "\n

Accepts encrypted connections using TLS or SSL.

", "events": [ { "textRaw": "Event: `'connection'`", "type": "event", "name": "connection", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

This event can also be explicitly emitted by users to inject connections\ninto the TLS server. In that case, any Duplex stream can be passed.

" }, { "textRaw": "Event: `'keylog'`", "type": "event", "name": "keylog", "meta": { "added": [ "v12.3.0", "v10.20.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": "

The keylog event is emitted when key material is generated or received by\na connection to this server (typically before handshake has completed, but not\nnecessarily). This keying material can be stored for debugging, as it allows\ncaptured TLS traffic to be decrypted. It may be emitted multiple times for\neach socket.

\n

A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

\n
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\nserver.on('keylog', (line, tlsSocket) => {\n  if (tlsSocket.remoteAddress !== '...')\n    return; // Only log keys for a particular IP\n  logFile.write(line);\n});\n
" }, { "textRaw": "Event: `'newSession'`", "type": "event", "name": "newSession", "meta": { "added": [ "v0.9.2" ], "changes": [ { "version": "v0.11.12", "pr-url": "https://github.com/nodejs/node-v0.x-archive/pull/7118", "description": "The `callback` argument is now supported." } ] }, "params": [], "desc": "

The 'newSession' event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The data should be provided to\nthe 'resumeSession' callback.

\n

The listener callback is passed three arguments when called:

\n
    \n
  • sessionId <Buffer> The TLS session identifier
  • \n
  • sessionData <Buffer> The TLS session data
  • \n
  • callback <Function> A callback function taking no arguments that must be\ninvoked in order for data to be sent or received over the secure connection.
  • \n
\n

Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

" }, { "textRaw": "Event: `'OCSPRequest'`", "type": "event", "name": "OCSPRequest", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "params": [], "desc": "

The 'OCSPRequest' event is emitted when the client sends a certificate status\nrequest. The listener callback is passed three arguments when called:

\n
    \n
  • certificate <Buffer> The server certificate
  • \n
  • issuer <Buffer> The issuer's certificate
  • \n
  • callback <Function> A callback function that must be invoked to provide\nthe results of the OCSP request.
  • \n
\n

The server's current certificate can be parsed to obtain the OCSP URL\nand certificate ID; after obtaining an OCSP response, callback(null, resp) is\nthen invoked, where resp is a Buffer instance containing the OCSP response.\nBoth certificate and issuer are Buffer DER-representations of the\nprimary and issuer's certificates. These can be used to obtain the OCSP\ncertificate ID and OCSP endpoint URL.

\n

Alternatively, callback(null, null) may be called, indicating that there was\nno OCSP response.

\n

Calling callback(err) will result in a socket.destroy(err) call.

\n

The typical flow of an OCSP Request is as follows:

\n
    \n
  1. Client connects to the server and sends an 'OCSPRequest' (via the status\ninfo extension in ClientHello).
  2. \n
  3. Server receives the request and emits the 'OCSPRequest' event, calling the\nlistener if registered.
  4. \n
  5. Server extracts the OCSP URL from either the certificate or issuer and\nperforms an OCSP request to the CA.
  6. \n
  7. Server receives 'OCSPResponse' from the CA and sends it back to the client\nvia the callback argument
  8. \n
  9. Client validates the response and either destroys the socket or performs a\nhandshake.
  10. \n
\n

The issuer can be null if the certificate is either self-signed or the\nissuer is not in the root certificates list. (An issuer may be provided\nvia the ca option when establishing the TLS connection.)

\n

Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

\n

An npm module like asn1.js may be used to parse the certificates.

" }, { "textRaw": "Event: `'resumeSession'`", "type": "event", "name": "resumeSession", "meta": { "added": [ "v0.9.2" ], "changes": [] }, "params": [], "desc": "

The 'resumeSession' event is emitted when the client requests to resume a\nprevious TLS session. The listener callback is passed two arguments when\ncalled:

\n
    \n
  • sessionId <Buffer> The TLS session identifier
  • \n
  • callback <Function> A callback function to be called when the prior session\nhas been recovered: callback([err[, sessionData]])\n\n
  • \n
\n

The event listener should perform a lookup in external storage for the\nsessionData saved by the 'newSession' event handler using the given\nsessionId. If found, call callback(null, sessionData) to resume the session.\nIf not found, the session cannot be resumed. callback() must be called\nwithout sessionData so that the handshake can continue and a new session can\nbe created. It is possible to call callback(err) to terminate the incoming\nconnection and destroy the socket.

\n

Listening for this event will have an effect only on connections established\nafter the addition of the event listener.

\n

The following illustrates resuming a TLS session:

\n
const tlsSessionStore = {};\nserver.on('newSession', (id, data, cb) => {\n  tlsSessionStore[id.toString('hex')] = data;\n  cb();\n});\nserver.on('resumeSession', (id, cb) => {\n  cb(null, tlsSessionStore[id.toString('hex')] || null);\n});\n
" }, { "textRaw": "Event: `'secureConnection'`", "type": "event", "name": "secureConnection", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "params": [], "desc": "

The 'secureConnection' event is emitted after the handshaking process for a\nnew connection has successfully completed. The listener callback is passed a\nsingle argument when called:

\n\n

The tlsSocket.authorized property is a boolean indicating whether the\nclient has been verified by one of the supplied Certificate Authorities for the\nserver. If tlsSocket.authorized is false, then socket.authorizationError\nis set to describe how authorization failed. Depending on the settings\nof the TLS server, unauthorized connections may still be accepted.

\n

The tlsSocket.alpnProtocol property is a string that contains the selected\nALPN protocol. When ALPN has no selected protocol, tlsSocket.alpnProtocol\nequals false.

\n

The tlsSocket.servername property is a string containing the server name\nrequested via SNI.

" }, { "textRaw": "Event: `'tlsClientError'`", "type": "event", "name": "tlsClientError", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "params": [], "desc": "

The 'tlsClientError' event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:

\n
    \n
  • exception <Error> The Error object describing the error
  • \n
  • tlsSocket <tls.TLSSocket> The tls.TLSSocket instance from which the\nerror originated.
  • \n
" } ], "methods": [ { "textRaw": "`server.addContext(hostname, context)`", "type": "method", "name": "addContext", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} A SNI host name or wildcard (e.g. `'*'`)", "name": "hostname", "type": "string", "desc": "A SNI host name or wildcard (e.g. `'*'`)" }, { "textRaw": "`context` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", "name": "context", "type": "Object", "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." } ] } ], "desc": "

The server.addContext() method adds a secure context that will be used if\nthe client request's SNI name matches the supplied hostname (or wildcard).

\n

When there are multiple matching contexts, the most recently added one is\nused.

" }, { "textRaw": "`server.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns the bound address, the address family name, and port of the\nserver as reported by the operating system. See net.Server.address() for\nmore information.

" }, { "textRaw": "`server.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.3.2" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {tls.Server}", "name": "return", "type": "tls.Server" }, "params": [ { "textRaw": "`callback` {Function} A listener callback that will be registered to listen for the server instance's `'close'` event.", "name": "callback", "type": "Function", "desc": "A listener callback that will be registered to listen for the server instance's `'close'` event." } ] } ], "desc": "

The server.close() method stops the server from accepting new connections.

\n

This function operates asynchronously. The 'close' event will be emitted\nwhen the server has no more open connections.

" }, { "textRaw": "`server.getTicketKeys()`", "type": "method", "name": "getTicketKeys", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A 48-byte buffer containing the session ticket keys.", "name": "return", "type": "Buffer", "desc": "A 48-byte buffer containing the session ticket keys." }, "params": [] } ], "desc": "

Returns the session ticket keys.

\n

See Session Resumption for more information.

" }, { "textRaw": "`server.listen()`", "type": "method", "name": "listen", "signatures": [ { "params": [] } ], "desc": "

Starts the server listening for encrypted connections.\nThis method is identical to server.listen() from net.Server.

" }, { "textRaw": "`server.setSecureContext(options)`", "type": "method", "name": "setSecureContext", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc).", "name": "options", "type": "Object", "desc": "An object containing any of the possible properties from the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`, `ca`, etc)." } ] } ], "desc": "

The server.setSecureContext() method replaces the secure context of an\nexisting server. Existing connections to the server are not interrupted.

" }, { "textRaw": "`server.setTicketKeys(keys)`", "type": "method", "name": "setTicketKeys", "meta": { "added": [ "v3.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`keys` {Buffer|TypedArray|DataView} A 48-byte buffer containing the session ticket keys.", "name": "keys", "type": "Buffer|TypedArray|DataView", "desc": "A 48-byte buffer containing the session ticket keys." } ] } ], "desc": "

Sets the session ticket keys.

\n

Changes to the ticket keys are effective only for future server connections.\nExisting or currently pending server connections will use the previous keys.

\n

See Session Resumption for more information.

" } ] }, { "textRaw": "Class: `tls.TLSSocket`", "type": "class", "name": "tls.TLSSocket", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "\n

Performs transparent encryption of written data and all required TLS\nnegotiation.

\n

Instances of tls.TLSSocket implement the duplex Stream interface.

\n

Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate() will only return data while the\nconnection is open.

", "events": [ { "textRaw": "Event: `'keylog'`", "type": "event", "name": "keylog", "meta": { "added": [ "v12.3.0", "v10.20.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." } ], "desc": "

The keylog event is emitted on a tls.TLSSocket when key material\nis generated or received by the socket. This keying material can be stored\nfor debugging, as it allows captured TLS traffic to be decrypted. It may\nbe emitted multiple times, before or after the handshake completes.

\n

A typical use case is to append received lines to a common text file, which\nis later used by software (such as Wireshark) to decrypt the traffic:

\n
const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });\n// ...\ntlsSocket.on('keylog', (line) => logFile.write(line));\n
" }, { "textRaw": "Event: `'OCSPResponse'`", "type": "event", "name": "OCSPResponse", "meta": { "added": [ "v0.11.13" ], "changes": [] }, "params": [], "desc": "

The 'OCSPResponse' event is emitted if the requestOCSP option was set\nwhen the tls.TLSSocket was created and an OCSP response has been received.\nThe listener callback is passed a single argument when called:

\n
    \n
  • response <Buffer> The server's OCSP response
  • \n
\n

Typically, the response is a digitally signed object from the server's CA that\ncontains information about server's certificate revocation status.

" }, { "textRaw": "Event: `'secureConnect'`", "type": "event", "name": "secureConnect", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "params": [], "desc": "

The 'secureConnect' event is emitted after the handshaking process for a new\nconnection has successfully completed. The listener callback will be called\nregardless of whether or not the server's certificate has been authorized. It\nis the client's responsibility to check the tlsSocket.authorized property to\ndetermine if the server certificate was signed by one of the specified CAs. If\ntlsSocket.authorized === false, then the error can be found by examining the\ntlsSocket.authorizationError property. If ALPN was used, the\ntlsSocket.alpnProtocol property can be checked to determine the negotiated\nprotocol.

\n

The 'secureConnect' event is not emitted when a <tls.TLSSocket> is created\nusing the new tls.TLSSocket() constructor.

" }, { "textRaw": "Event: `'session'`", "type": "event", "name": "session", "meta": { "added": [ "v11.10.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {Buffer}", "name": "session", "type": "Buffer" } ], "desc": "

The 'session' event is emitted on a client tls.TLSSocket when a new session\nor TLS ticket is available. This may or may not be before the handshake is\ncomplete, depending on the TLS protocol version that was negotiated. The event\nis not emitted on the server, or if a new session was not created, for example,\nwhen the connection was resumed. For some TLS protocol versions the event may be\nemitted multiple times, in which case all the sessions can be used for\nresumption.

\n

On the client, the session can be provided to the session option of\ntls.connect() to resume the connection.

\n

See Session Resumption for more information.

\n

For TLSv1.2 and below, tls.TLSSocket.getSession() can be called once\nthe handshake is complete. For TLSv1.3, only ticket-based resumption is allowed\nby the protocol, multiple tickets are sent, and the tickets aren't sent until\nafter the handshake completes. So it is necessary to wait for the\n'session' event to get a resumable session. Applications\nshould use the 'session' event instead of getSession() to ensure\nthey will work for all TLS versions. Applications that only expect to\nget or use one session should listen for this event only once:

\n
tlsSocket.once('session', (session) => {\n  // The session can be used immediately or later.\n  tls.connect({\n    session: session,\n    // Other connect options...\n  });\n});\n
" } ], "methods": [ { "textRaw": "`tlsSocket.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns the bound address, the address family name, and port of the\nunderlying socket as reported by the operating system:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }.

" }, { "textRaw": "`tlsSocket.disableRenegotiation()`", "type": "method", "name": "disableRenegotiation", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Disables TLS renegotiation for this TLSSocket instance. Once called, attempts\nto renegotiate will trigger an 'error' event on the TLSSocket.

" }, { "textRaw": "`tlsSocket.enableTrace()`", "type": "method", "name": "enableTrace", "meta": { "added": [ "v12.2.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

When enabled, TLS packet trace information is written to stderr. This can be\nused to debug TLS connection problems.

\n

Note: The format of the output is identical to the output of openssl s_client -trace or openssl s_server -trace. While it is produced by OpenSSL's\nSSL_trace() function, the format is undocumented, can change without notice,\nand should not be relied on.

" }, { "textRaw": "`tlsSocket.exportKeyingMaterial(length, label[, context])`", "type": "method", "name": "exportKeyingMaterial", "meta": { "added": [ "v13.10.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} requested bytes of the keying material", "name": "return", "type": "Buffer", "desc": "requested bytes of the keying material" }, "params": [ { "textRaw": "`length` {number} number of bytes to retrieve from keying material", "name": "length", "type": "number", "desc": "number of bytes to retrieve from keying material" }, { "textRaw": "`label` {string} an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).", "name": "label", "type": "string", "desc": "an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels)." }, { "textRaw": "`context` {Buffer} Optionally provide a context.", "name": "context", "type": "Buffer", "desc": "Optionally provide a context." } ] } ], "desc": "

Keying material is used for validations to prevent different kind of attacks in\nnetwork protocols, for example in the specifications of IEEE 802.1X.

\n

Example

\n
const keyingMaterial = tlsSocket.exportKeyingMaterial(\n  128,\n  'client finished');\n\n/**\n Example return value of keyingMaterial:\n <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9\n    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91\n    74 ef 2c ... 78 more bytes>\n*/\n
\n

See the OpenSSL SSL_export_keying_material documentation for more\ninformation.

" }, { "textRaw": "`tlsSocket.getCertificate()`", "type": "method", "name": "getCertificate", "meta": { "added": [ "v11.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object representing the local certificate. The returned object has\nsome properties corresponding to the fields of the certificate.

\n

See tls.TLSSocket.getPeerCertificate() for an example of the certificate\nstructure.

\n

If there is no local certificate, an empty object will be returned. If the\nsocket has been destroyed, null will be returned.

" }, { "textRaw": "`tlsSocket.getCipher()`", "type": "method", "name": "getCipher", "meta": { "added": [ "v0.11.4" ], "changes": [ { "version": [ "v13.4.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30637", "description": "Return the IETF cipher name as `standardName`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26625", "description": "Return the minimum cipher version, instead of a fixed string (`'TLSv1/SSLv3'`)." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`name` {string} OpenSSL name for the cipher suite.", "name": "name", "type": "string", "desc": "OpenSSL name for the cipher suite." }, { "textRaw": "`standardName` {string} IETF name for the cipher suite.", "name": "standardName", "type": "string", "desc": "IETF name for the cipher suite." }, { "textRaw": "`version` {string} The minimum TLS protocol version supported by this cipher suite.", "name": "version", "type": "string", "desc": "The minimum TLS protocol version supported by this cipher suite." } ] }, "params": [] } ], "desc": "

Returns an object containing information on the negotiated cipher suite.

\n

For example:

\n
{\n    \"name\": \"AES128-SHA256\",\n    \"standardName\": \"TLS_RSA_WITH_AES_128_CBC_SHA256\",\n    \"version\": \"TLSv1.2\"\n}\n
\n

See\nSSL_CIPHER_get_name\nfor more information.

" }, { "textRaw": "`tlsSocket.getEphemeralKeyInfo()`", "type": "method", "name": "getEphemeralKeyInfo", "meta": { "added": [ "v5.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in perfect forward secrecy on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket; null is returned\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname property is available only when type is 'ECDH'.

\n

For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

" }, { "textRaw": "`tlsSocket.getFinished()`", "type": "method", "name": "getFinished", "meta": { "added": [ "v9.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.", "name": "return", "type": "Buffer|undefined", "desc": "The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet." }, "params": [] } ], "desc": "

As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

\n

Corresponds to the SSL_get_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

" }, { "textRaw": "`tlsSocket.getPeerCertificate([detailed])`", "type": "method", "name": "getPeerCertificate", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} A certificate object.", "name": "return", "type": "Object", "desc": "A certificate object." }, "params": [ { "textRaw": "`detailed` {boolean} Include the full certificate chain if `true`, otherwise include just the peer's certificate.", "name": "detailed", "type": "boolean", "desc": "Include the full certificate chain if `true`, otherwise include just the peer's certificate." } ] } ], "desc": "

Returns an object representing the peer's certificate. If the peer does not\nprovide a certificate, an empty object will be returned. If the socket has been\ndestroyed, null will be returned.

\n

If the full certificate chain was requested, each certificate will include an\nissuerCertificate property containing an object representing its issuer's\ncertificate.

", "modules": [ { "textRaw": "Certificate object", "name": "certificate_object", "meta": { "changes": [ { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24358", "description": "Support Elliptic Curve public key info." } ] }, "desc": "

A certificate object has properties corresponding to the fields of the\ncertificate.

\n
    \n
  • raw <Buffer> The DER encoded X.509 certificate data.
  • \n
  • subject <Object> The certificate subject, described in terms of\nCountry (C:), StateOrProvince (ST), Locality (L), Organization (O),\nOrganizationalUnit (OU), and CommonName (CN). The CommonName is typically\na DNS name with TLS certificates. Example:\n{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}.
  • \n
  • issuer <Object> The certificate issuer, described in the same terms as the\nsubject.
  • \n
  • valid_from <string> The date-time the certificate is valid from.
  • \n
  • valid_to <string> The date-time the certificate is valid to.
  • \n
  • serialNumber <string> The certificate serial number, as a hex string.\nExample: 'B9B0D332A1AA5635'.
  • \n
  • fingerprint <string> The SHA-1 digest of the DER encoded certificate. It is\nreturned as a : separated hexadecimal string. Example: '2A:7A:C2:DD:...'.
  • \n
  • fingerprint256 <string> The SHA-256 digest of the DER encoded certificate.\nIt is returned as a : separated hexadecimal string. Example:\n'2A:7A:C2:DD:...'.
  • \n
  • ext_key_usage <Array> (Optional) The extended key usage, a set of OIDs.
  • \n
  • subjectaltname <string> (Optional) A string containing concatenated names\nfor the subject, an alternative to the subject names.
  • \n
  • infoAccess <Array> (Optional) An array describing the AuthorityInfoAccess,\nused with OCSP.
  • \n
  • issuerCertificate <Object> (Optional) The issuer certificate object. For\nself-signed certificates, this may be a circular reference.
  • \n
\n

The certificate may contain information about the public key, depending on\nthe key type.

\n

For RSA keys, the following properties may be defined:

\n
    \n
  • bits <number> The RSA bit size. Example: 1024.
  • \n
  • exponent <string> The RSA exponent, as a string in hexadecimal number\nnotation. Example: '0x010001'.
  • \n
  • modulus <string> The RSA modulus, as a hexadecimal string. Example:\n'B56CE45CB7...'.
  • \n
  • pubkey <Buffer> The public key.
  • \n
\n

For EC keys, the following properties may be defined:

\n
    \n
  • pubkey <Buffer> The public key.
  • \n
  • bits <number> The key size in bits. Example: 256.
  • \n
  • asn1Curve <string> (Optional) The ASN.1 name of the OID of the elliptic\ncurve. Well-known curves are identified by an OID. While it is unusual, it is\npossible that the curve is identified by its mathematical properties, in which\ncase it will not have an OID. Example: 'prime256v1'.
  • \n
  • nistCurve <string> (Optional) The NIST name for the elliptic curve, if it\nhas one (not all well-known curves have been assigned names by NIST). Example:\n'P-256'.
  • \n
\n

Example certificate:

\n\n
{ subject:\n   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],\n     CN: '*.nodejs.org' },\n  issuer:\n   { C: 'GB',\n     ST: 'Greater Manchester',\n     L: 'Salford',\n     O: 'COMODO CA Limited',\n     CN: 'COMODO RSA Domain Validation Secure Server CA' },\n  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',\n  infoAccess:\n   { 'CA Issuers - URI':\n      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],\n     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },\n  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',\n  exponent: '0x10001',\n  pubkey: <Buffer ... >,\n  valid_from: 'Aug 14 00:00:00 2017 GMT',\n  valid_to: 'Nov 20 23:59:59 2019 GMT',\n  fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D',\n  fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02',\n  ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ],\n  serialNumber: '66593D57F20CBC573E433381B5FEC280',\n  raw: <Buffer ... > }\n
", "type": "module", "displayName": "Certificate object" } ] }, { "textRaw": "`tlsSocket.getPeerFinished()`", "type": "method", "name": "getPeerFinished", "meta": { "added": [ "v9.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|undefined} The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far.", "name": "return", "type": "Buffer|undefined", "desc": "The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so far." }, "params": [] } ], "desc": "

As the Finished messages are message digests of the complete handshake\n(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can\nbe used for external authentication procedures when the authentication\nprovided by SSL/TLS is not desired or is not enough.

\n

Corresponds to the SSL_get_peer_finished routine in OpenSSL and may be used\nto implement the tls-unique channel binding from RFC 5929.

" }, { "textRaw": "`tlsSocket.getPeerX509Certificate()`", "type": "method", "name": "getPeerX509Certificate", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {X509Certificate}", "name": "return", "type": "X509Certificate" }, "params": [] } ], "desc": "

Returns the peer certificate as an <X509Certificate> object.

\n

If there is no peer certificate, or the socket has been destroyed,\nundefined will be returned.

" }, { "textRaw": "`tlsSocket.getProtocol()`", "type": "method", "name": "getProtocol", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|null}", "name": "return", "type": "string|null" }, "params": [] } ], "desc": "

Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. The value 'unknown' will be returned for connected\nsockets that have not completed the handshaking process. The value null will\nbe returned for server sockets or disconnected client sockets.

\n

Protocol versions are:

\n
    \n
  • 'SSLv3'
  • \n
  • 'TLSv1'
  • \n
  • 'TLSv1.1'
  • \n
  • 'TLSv1.2'
  • \n
  • 'TLSv1.3'
  • \n
\n

See the OpenSSL SSL_get_version documentation for more information.

" }, { "textRaw": "`tlsSocket.getSession()`", "type": "method", "name": "getSession", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "{Buffer}", "type": "Buffer" } ] } ], "desc": "

Returns the TLS session data or undefined if no session was\nnegotiated. On the client, the data can be provided to the session option of\ntls.connect() to resume the connection. On the server, it may be useful\nfor debugging.

\n

See Session Resumption for more information.

\n

Note: getSession() works only for TLSv1.2 and below. For TLSv1.3, applications\nmust use the 'session' event (it also works for TLSv1.2 and below).

" }, { "textRaw": "`tlsSocket.getSharedSigalgs()`", "type": "method", "name": "getSharedSigalgs", "meta": { "added": [ "v12.11.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} List of signature algorithms shared between the server and the client in the order of decreasing preference.", "name": "return", "type": "Array", "desc": "List of signature algorithms shared between the server and the client in the order of decreasing preference." }, "params": [] } ], "desc": "

See\nSSL_get_shared_sigalgs\nfor more information.

" }, { "textRaw": "`tlsSocket.getTLSTicket()`", "type": "method", "name": "getTLSTicket", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "{Buffer}", "type": "Buffer" } ] } ], "desc": "

For a client, returns the TLS session ticket if one is available, or\nundefined. For a server, always returns undefined.

\n

It may be useful for debugging.

\n

See Session Resumption for more information.

" }, { "textRaw": "`tlsSocket.getX509Certificate()`", "type": "method", "name": "getX509Certificate", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {X509Certificate}", "name": "return", "type": "X509Certificate" }, "params": [] } ], "desc": "

Returns the local certificate as an <X509Certificate> object.

\n

If there is no local certificate, or the socket has been destroyed,\nundefined will be returned.

" }, { "textRaw": "`tlsSocket.isSessionReused()`", "type": "method", "name": "isSessionReused", "meta": { "added": [ "v0.5.6" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if the session was reused, `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if the session was reused, `false` otherwise." }, "params": [] } ], "desc": "

See Session Resumption for more information.

" }, { "textRaw": "`tlsSocket.renegotiate(options, callback)`", "type": "method", "name": "renegotiate", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if renegotiation was initiated, `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if renegotiation was initiated, `false` otherwise." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", "name": "rejectUnauthorized", "type": "boolean", "default": "`true`", "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." }, { "textRaw": "`requestCert`", "name": "requestCert" } ] }, { "textRaw": "`callback` {Function} If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.", "name": "callback", "type": "Function", "desc": "If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all." } ] } ], "desc": "

The tlsSocket.renegotiate() method initiates a TLS renegotiation process.\nUpon completion, the callback function will be passed a single argument\nthat is either an Error (if the request failed) or null.

\n

This method can be used to request a peer's certificate after the secure\nconnection has been established.

\n

When running as the server, the socket will be destroyed with an error after\nhandshakeTimeout timeout.

\n

For TLSv1.3, renegotiation cannot be initiated, it is not supported by the\nprotocol.

" }, { "textRaw": "`tlsSocket.setMaxSendFragment(size)`", "type": "method", "name": "setMaxSendFragment", "meta": { "added": [ "v0.11.11" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`size` {number} The maximum TLS fragment size. The maximum value is `16384`. **Default:** `16384`.", "name": "size", "type": "number", "default": "`16384`", "desc": "The maximum TLS fragment size. The maximum value is `16384`." } ] } ], "desc": "

The tlsSocket.setMaxSendFragment() method sets the maximum TLS fragment size.\nReturns true if setting the limit succeeded; false otherwise.

\n

Smaller fragment sizes decrease the buffering latency on the client: larger\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.

" } ], "properties": [ { "textRaw": "`tlsSocket.authorizationError`", "name": "authorizationError", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false.

" }, { "textRaw": "`authorized` Returns: {boolean}", "type": "boolean", "name": "return", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns true if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket instance, otherwise false.

" }, { "textRaw": "`tlsSocket.encrypted`", "name": "encrypted", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Always returns true. This may be used to distinguish TLS sockets from regular\nnet.Socket instances.

" }, { "textRaw": "`localAddress` {string}", "type": "string", "name": "localAddress", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the string representation of the local IP address.

" }, { "textRaw": "`localPort` {number}", "type": "number", "name": "localPort", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the numeric representation of the local port.

" }, { "textRaw": "`remoteAddress` {string}", "type": "string", "name": "remoteAddress", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.

" }, { "textRaw": "`remoteFamily` {string}", "type": "string", "name": "remoteFamily", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

" }, { "textRaw": "`remotePort` {number}", "type": "number", "name": "remotePort", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "desc": "

Returns the numeric representation of the remote port. For example, 443.

" } ], "signatures": [ { "params": [ { "textRaw": "`socket` {net.Socket|stream.Duplex} On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used).", "name": "socket", "type": "net.Socket|stream.Duplex", "desc": "On the server side, any `Duplex` stream. On the client side, any instance of [`net.Socket`][] (for generic `Duplex` stream support on the client side, [`tls.connect()`][] must be used)." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`enableTrace`: See [`tls.createServer()`][]", "name": "enableTrace", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server. **Default:** `false`.", "name": "isServer", "default": "`false`", "desc": "The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If `true` the TLS socket will be instantiated as a server." }, { "textRaw": "`server` {net.Server} A [`net.Server`][] instance.", "name": "server", "type": "net.Server", "desc": "A [`net.Server`][] instance." }, { "textRaw": "`requestCert`: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate.", "name": "requestCert", "desc": "Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (`isServer` is true) may set `requestCert` to true to request a client certificate." }, { "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", "name": "rejectUnauthorized", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", "name": "ALPNProtocols", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: See [`tls.createServer()`][]", "name": "SNICallback", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", "name": "session", "type": "Buffer", "desc": "A `Buffer` instance containing a TLS session." }, { "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication", "name": "requestOCSP", "type": "boolean", "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication" }, { "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", "name": "secureContext", "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." }, { "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored.", "name": "...", "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing. Otherwise, they are ignored." } ] } ], "desc": "

Construct a new tls.TLSSocket object from an existing TCP socket.

" } ] } ], "methods": [ { "textRaw": "`tls.checkServerIdentity(hostname, cert)`", "type": "method", "name": "checkServerIdentity", "meta": { "added": [ "v0.8.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Error|undefined}", "name": "return", "type": "Error|undefined" }, "params": [ { "textRaw": "`hostname` {string} The host name or IP address to verify the certificate against.", "name": "hostname", "type": "string", "desc": "The host name or IP address to verify the certificate against." }, { "textRaw": "`cert` {Object} A [certificate object][] representing the peer's certificate.", "name": "cert", "type": "Object", "desc": "A [certificate object][] representing the peer's certificate." } ] } ], "desc": "

Verifies the certificate cert is issued to hostname.

\n

Returns <Error> object, populating it with reason, host, and cert on\nfailure. On success, returns <undefined>.

\n

This function can be overwritten by providing alternative function as part of\nthe options.checkServerIdentity option passed to tls.connect(). The\noverwriting function can call tls.checkServerIdentity() of course, to augment\nthe checks done with additional verification.

\n

This function is only called if the certificate passed all other checks, such as\nbeing issued by trusted CA (options.ca).

" }, { "textRaw": "`tls.connect(options[, callback])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [ { "version": "v15.1.0", "pr-url": "https://github.com/nodejs/node/pull/35753", "description": "Added `onread` option." }, { "version": [ "v14.1.0", "v13.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/32786", "description": "The `highWaterMark` option is accepted now." }, { "version": [ "v13.6.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/23188", "description": "The `pskCallback` option is now supported." }, { "version": "v12.9.0", "pr-url": "https://github.com/nodejs/node/pull/27836", "description": "Support the `allowHalfOpen` option." }, { "version": "v12.4.0", "pr-url": "https://github.com/nodejs/node/pull/27816", "description": "The `hints` option is now supported." }, { "version": "v12.2.0", "pr-url": "https://github.com/nodejs/node/pull/27497", "description": "The `enableTrace` option is now supported." }, { "version": [ "v11.8.0", "v10.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/25517", "description": "The `timeout` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12839", "description": "The `lookup` option is supported now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11984", "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." }, { "version": [ "v5.3.0", "v4.7.0" ], "pr-url": "https://github.com/nodejs/node/pull/4246", "description": "The `secureContext` option is supported now." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {tls.TLSSocket}", "name": "return", "type": "tls.TLSSocket" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`enableTrace`: See [`tls.createServer()`][]", "name": "enableTrace", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`host` {string} Host the client should connect to. **Default:** `'localhost'`.", "name": "host", "type": "string", "default": "`'localhost'`", "desc": "Host the client should connect to." }, { "textRaw": "`port` {number} Port the client should connect to.", "name": "port", "type": "number", "desc": "Port the client should connect to." }, { "textRaw": "`path` {string} Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored.", "name": "path", "type": "string", "desc": "Creates Unix socket connection to path. If this option is specified, `host` and `port` are ignored." }, { "textRaw": "`socket` {stream.Duplex} Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called.", "name": "socket", "type": "stream.Duplex", "desc": "Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of [`net.Socket`][], but any `Duplex` stream is allowed. If this option is specified, `path`, `host` and `port` are ignored, except for certificate validation. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Connection/disconnection/destruction of `socket` is the user's responsibility; calling `tls.connect()` will not cause `net.connect()` to be called." }, { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the socket will automatically end the writable side when the readable side ends. If the `socket` option is set, this option has no effect. See the `allowHalfOpen` option of [`net.Socket`][] for details. **Default:** `false`.", "name": "allowHalfOpen", "type": "boolean", "default": "`false`", "desc": "If set to `false`, then the socket will automatically end the writable side when the readable side ends. If the `socket` option is set, this option has no effect. See the `allowHalfOpen` option of [`net.Socket`][] for details." }, { "textRaw": "`rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`.", "name": "rejectUnauthorized", "type": "boolean", "default": "`true`", "desc": "If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code." }, { "textRaw": "`pskCallback` {Function}When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][].", "name": "pskCallback", "type": "Function", "desc": "When negotiating TLS-PSK (pre-shared keys), this function is called with optional identity `hint` provided by the server or `null` in case of TLS 1.3 where `hint` was removed. It will be necessary to provide a custom `tls.checkServerIdentity()` for the connection as the default one will try to check host name/IP of the server against the certificate but that's not applicable for PSK because there won't be a certificate present. More information can be found in the [RFC 4279][].", "options": [ { "textRaw": "hint: {string} optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used.", "name": "hint", "type": "string", "desc": "optional message sent from the server to help client decide which identity to use during negotiation. Always `null` if TLS 1.3 is used." }, { "textRaw": "Returns: {Object} in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding.", "name": "return", "type": "Object", "desc": "in the form `{ psk: , identity: }` or `null` to stop the negotiation process. `psk` must be compatible with the selected cipher's digest. `identity` must use UTF-8 encoding." } ] }, { "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later.", "name": "ALPNProtocols", "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `'\\x08http/1.1\\x08http/1.0'`, where the `len` byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['http/1.1', 'http/1.0']`. Protocols earlier in the list have higher preference than those later." }, { "textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][].", "name": "servername", "type": "string", "desc": "Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the `SNICallback` option to [`tls.createServer()`][]." }, { "textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified.", "name": "checkServerIdentity(servername,", "desc": "cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's host name (or the provided `servername` when explicitly set) against the certificate. This should return an {Error} if verification fails. The method should return `undefined` if the `servername` and `cert` are verified." }, { "textRaw": "`session` {Buffer} A `Buffer` instance, containing TLS session.", "name": "session", "type": "Buffer", "desc": "A `Buffer` instance, containing TLS session." }, { "textRaw": "`minDHSize` {number} Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. **Default:** `1024`.", "name": "minDHSize", "type": "number", "default": "`1024`", "desc": "Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown." }, { "textRaw": "`highWaterMark`: {number} Consistent with the readable stream `highWaterMark` parameter. **Default:** `16 * 1024`.", "name": "highWaterMark", "type": "number", "default": "`16 * 1024`", "desc": "Consistent with the readable stream `highWaterMark` parameter." }, { "textRaw": "`secureContext`: TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`.", "name": "secureContext", "desc": "TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`." }, { "textRaw": "`onread` {Object} If the `socket` option is missing, incoming data is stored in a single `buffer` and passed to the supplied `callback` when data arrives on the socket, otherwise the option is ignored. See the `onread` option of [`net.Socket`][] for details.", "name": "onread", "type": "Object", "desc": "If the `socket` option is missing, incoming data is stored in a single `buffer` and passed to the supplied `callback` when data arrives on the socket, otherwise the option is ignored. See the `onread` option of [`net.Socket`][] for details." }, { "textRaw": "...: [`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored.", "name": "...", "desc": "[`tls.createSecureContext()`][] options that are used if the `secureContext` option is missing, otherwise they are ignored." }, { "textRaw": "...: Any [`socket.connect()`][] option not already listed.", "name": "...", "desc": "Any [`socket.connect()`][] option not already listed." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

The callback function, if specified, will be added as a listener for the\n'secureConnect' event.

\n

tls.connect() returns a tls.TLSSocket object.

\n

Unlike the https API, tls.connect() does not enable the\nSNI (Server Name Indication) extension by default, which may cause some\nservers to return an incorrect certificate or reject the connection\naltogether. To enable SNI, set the servername option in addition\nto host.

\n

The following illustrates a client for the echo server example from\ntls.createServer():

\n
// Assumes an echo server that is listening on port 8000.\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // Necessary only if the server requires client certificate authentication.\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // Necessary only if the server uses a self-signed certificate.\n  ca: [ fs.readFileSync('server-cert.pem') ],\n\n  // Necessary only if the server's cert isn't for \"localhost\".\n  checkServerIdentity: () => { return null; },\n};\n\nconst socket = tls.connect(8000, options, () => {\n  console.log('client connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(socket);\n  process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', (data) => {\n  console.log(data);\n});\nsocket.on('end', () => {\n  console.log('server ends connection');\n});\n
" }, { "textRaw": "`tls.connect(path[, options][, callback])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {tls.TLSSocket}", "name": "return", "type": "tls.TLSSocket" }, "params": [ { "textRaw": "`path` {string} Default value for `options.path`.", "name": "path", "type": "string", "desc": "Default value for `options.path`." }, { "textRaw": "`options` {Object} See [`tls.connect()`][].", "name": "options", "type": "Object", "desc": "See [`tls.connect()`][]." }, { "textRaw": "`callback` {Function} See [`tls.connect()`][].", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][]." } ] } ], "desc": "

Same as tls.connect() except that path can be provided\nas an argument instead of an option.

\n

A path option, if specified, will take precedence over the path argument.

" }, { "textRaw": "`tls.connect(port[, host][, options][, callback])`", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {tls.TLSSocket}", "name": "return", "type": "tls.TLSSocket" }, "params": [ { "textRaw": "`port` {number} Default value for `options.port`.", "name": "port", "type": "number", "desc": "Default value for `options.port`." }, { "textRaw": "`host` {string} Default value for `options.host`.", "name": "host", "type": "string", "desc": "Default value for `options.host`." }, { "textRaw": "`options` {Object} See [`tls.connect()`][].", "name": "options", "type": "Object", "desc": "See [`tls.connect()`][]." }, { "textRaw": "`callback` {Function} See [`tls.connect()`][].", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][]." } ] } ], "desc": "

Same as tls.connect() except that port and host can be provided\nas arguments instead of options.

\n

A port or host option, if specified, will take precedence over any port or host\nargument.

" }, { "textRaw": "`tls.createSecureContext([options])`", "type": "method", "name": "createSecureContext", "meta": { "added": [ "v0.11.13" ], "changes": [ { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/28973", "description": "Added `privateKeyIdentifier` and `privateKeyEngine` options to get private key from an OpenSSL engine." }, { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29598", "description": "Added `sigalgs` option to override supported signature algorithms." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26209", "description": "TLSv1.3 support added." }, { "version": "v11.5.0", "pr-url": "https://github.com/nodejs/node/pull/24733", "description": "The `ca:` option now supports `BEGIN TRUSTED CERTIFICATE`." }, { "version": [ "v11.4.0", "v10.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/24405", "description": "The `minVersion` and `maxVersion` can be used to restrict the allowed TLS protocol versions." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19794", "description": "The `ecdhCurve` cannot be set to `false` anymore due to a change in OpenSSL." }, { "version": "v9.3.0", "pr-url": "https://github.com/nodejs/node/pull/14903", "description": "The `options` parameter can now include `clientCertEngine`." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15206", "description": "The `ecdhCurve` option can now be multiple `':'` separated curve names or `'auto'`." }, { "version": "v7.3.0", "pr-url": "https://github.com/nodejs/node/pull/10294", "description": "If the `key` option is an array, individual entries do not need a `passphrase` property anymore. `Array` entries can also just be `string`s or `Buffer`s now." }, { "version": "v5.2.0", "pr-url": "https://github.com/nodejs/node/pull/4099", "description": "The `ca` option can now be a single string containing multiple CA certificates." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][].", "name": "ca", "type": "string|string[]|Buffer|Buffer[]", "desc": "Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or `Buffer`, or an `Array` of strings and/or `Buffer`s. Any string or `Buffer` can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the `ca` option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are \"TRUSTED CERTIFICATE\", \"X509 CERTIFICATE\", and \"CERTIFICATE\". See also [`tls.rootCertificates`][]." }, { "textRaw": "`cert` {string|string[]|Buffer|Buffer[]} Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.", "name": "cert", "type": "string|string[]|Buffer|Buffer[]", "desc": "Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private `key`, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see `ca`). When providing multiple cert chains, they do not have to be in the same order as their private keys in `key`. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail." }, { "textRaw": "`sigalgs` {string} Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info.", "name": "sigalgs", "type": "string", "desc": "Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) for more info." }, { "textRaw": "`ciphers` {string} Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them.", "name": "ciphers", "type": "string", "desc": "Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted ciphers can be obtained via [`tls.getCiphers()`][]. Cipher names must be uppercased in order for OpenSSL to accept them." }, { "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", "name": "clientCertEngine", "type": "string", "desc": "Name of an OpenSSL engine which can provide the client certificate." }, { "textRaw": "`crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate Revocation Lists).", "name": "crl", "type": "string|string[]|Buffer|Buffer[]", "desc": "PEM formatted CRLs (Certificate Revocation Lists)." }, { "textRaw": "`dhparam` {string|Buffer} Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.", "name": "dhparam", "type": "string|Buffer", "desc": "Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. The key length must be greater than or equal to 1024 bits or else an error will be thrown. Although 1024 bits is permissible, use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available." }, { "textRaw": "`ecdhCurve` {string} A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. **Default:** [`tls.DEFAULT_ECDH_CURVE`][].", "name": "ecdhCurve", "type": "string", "default": "[`tls.DEFAULT_ECDH_CURVE`][]", "desc": "A string describing a named curve or a colon separated list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for ECDH key agreement. Set to `auto` to select the curve automatically. Use [`crypto.getCurves()`][] to obtain a list of available curve names. On recent releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve." }, { "textRaw": "`honorCipherOrder` {boolean} Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information.", "name": "honorCipherOrder", "type": "boolean", "desc": "Attempt to use the server's cipher suite preferences instead of the client's. When `true`, causes `SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see [OpenSSL Options][] for more information." }, { "textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", "name": "key", "type": "string|string[]|Buffer|Buffer[]|Object[]", "desc": "Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." }, { "textRaw": "`privateKeyEngine` {string} Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`.", "name": "privateKeyEngine", "type": "string", "desc": "Name of an OpenSSL engine to get private key from. Should be used together with `privateKeyIdentifier`." }, { "textRaw": "`privateKeyIdentifier` {string} Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways.", "name": "privateKeyIdentifier", "type": "string", "desc": "Identifier of a private key managed by an OpenSSL engine. Should be used together with `privateKeyEngine`. Should not be set together with `key`, because both options define a private key in different ways." }, { "textRaw": "`maxVersion` {string} Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option; use one or the other. **Default:** [`tls.DEFAULT_MAX_VERSION`][].", "name": "maxVersion", "type": "string", "default": "[`tls.DEFAULT_MAX_VERSION`][]", "desc": "Optionally set the maximum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option; use one or the other." }, { "textRaw": "`minVersion` {string} Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option; use one or the other. Avoid setting to less than TLSv1.2, but it may be required for interoperability. **Default:** [`tls.DEFAULT_MIN_VERSION`][].", "name": "minVersion", "type": "string", "default": "[`tls.DEFAULT_MIN_VERSION`][]", "desc": "Optionally set the minimum TLS version to allow. One of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the `secureProtocol` option; use one or the other. Avoid setting to less than TLSv1.2, but it may be required for interoperability." }, { "textRaw": "`passphrase` {string} Shared passphrase used for a single private key and/or a PFX.", "name": "passphrase", "type": "string", "desc": "Shared passphrase used for a single private key and/or a PFX." }, { "textRaw": "`pfx` {string|string[]|Buffer|Buffer[]|Object[]} PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not.", "name": "pfx", "type": "string|string[]|Buffer|Buffer[]|Object[]", "desc": "PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form `{buf: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted PFX will be decrypted with `object.passphrase` if provided, or `options.passphrase` if it is not." }, { "textRaw": "`secureOptions` {number} Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][].", "name": "secureOptions", "type": "number", "desc": "Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the `SSL_OP_*` options from [OpenSSL Options][]." }, { "textRaw": "`secureProtocol` {string} Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. **Default:** none, see `minVersion`.", "name": "secureProtocol", "type": "string", "default": "none, see `minVersion`", "desc": "Legacy mechanism to select the TLS protocol version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability." }, { "textRaw": "`sessionIdContext` {string} Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.", "name": "sessionIdContext", "type": "string", "desc": "Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients." }, { "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information.", "name": "ticketKeys", "type": "Buffer", "desc": "48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information." }, { "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", "name": "sessionTimeout", "type": "number", "default": "`300`", "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." } ] } ] } ], "desc": "

tls.createServer() sets the default value of the honorCipherOrder option\nto true, other APIs that create secure contexts leave it unset.

\n

tls.createServer() uses a 128 bit truncated SHA1 hash value generated\nfrom process.argv as the default value of the sessionIdContext option, other\nAPIs that create secure contexts have no default value.

\n

The tls.createSecureContext() method creates a SecureContext object. It is\nusable as an argument to several tls APIs, such as tls.createServer()\nand server.addContext(), but has no public methods.

\n

A key is required for ciphers that use certificates. Either key or\npfx can be used to provide it.

\n

If the ca option is not given, then Node.js will default to using\nMozilla's publicly trusted list of CAs.

" }, { "textRaw": "`tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`", "type": "method", "name": "createSecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "signatures": [ { "params": [ { "textRaw": "`context` {Object} A secure context object as returned by `tls.createSecureContext()`", "name": "context", "type": "Object", "desc": "A secure context object as returned by `tls.createSecureContext()`" }, { "textRaw": "`isServer` {boolean} `true` to specify that this TLS connection should be opened as a server.", "name": "isServer", "type": "boolean", "desc": "`true` to specify that this TLS connection should be opened as a server." }, { "textRaw": "`requestCert` {boolean} `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.", "name": "requestCert", "type": "boolean", "desc": "`true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`." }, { "textRaw": "`rejectUnauthorized` {boolean} If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.", "name": "rejectUnauthorized", "type": "boolean", "desc": "If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`." }, { "textRaw": "`options`", "name": "options", "options": [ { "textRaw": "`enableTrace`: See [`tls.createServer()`][]", "name": "enableTrace", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`secureContext`: A TLS context object from [`tls.createSecureContext()`][]", "name": "secureContext", "desc": "A TLS context object from [`tls.createSecureContext()`][]" }, { "textRaw": "`isServer`: If `true` the TLS socket will be instantiated in server-mode. **Default:** `false`.", "name": "isServer", "default": "`false`", "desc": "If `true` the TLS socket will be instantiated in server-mode." }, { "textRaw": "`server` {net.Server} A [`net.Server`][] instance", "name": "server", "type": "net.Server", "desc": "A [`net.Server`][] instance" }, { "textRaw": "`requestCert`: See [`tls.createServer()`][]", "name": "requestCert", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`rejectUnauthorized`: See [`tls.createServer()`][]", "name": "rejectUnauthorized", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: See [`tls.createServer()`][]", "name": "ALPNProtocols", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: See [`tls.createServer()`][]", "name": "SNICallback", "desc": "See [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} A `Buffer` instance containing a TLS session.", "name": "session", "type": "Buffer", "desc": "A `Buffer` instance containing a TLS session." }, { "textRaw": "`requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication.", "name": "requestOCSP", "type": "boolean", "desc": "If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event will be emitted on the socket before establishing a secure communication." } ] } ] } ], "desc": "

Creates a new secure pair object with two streams, one of which reads and writes\nthe encrypted data and the other of which reads and writes the cleartext data.\nGenerally, the encrypted stream is piped to/from an incoming encrypted data\nstream and the cleartext one is used as a replacement for the initial encrypted\nstream.

\n

tls.createSecurePair() returns a tls.SecurePair object with cleartext and\nencrypted stream properties.

\n

Using cleartext has the same API as tls.TLSSocket.

\n

The tls.createSecurePair() method is now deprecated in favor of\ntls.TLSSocket(). For example, the code:

\n
pair = tls.createSecurePair(/* ... */);\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
\n

can be replaced by:

\n
secureSocket = tls.TLSSocket(socket, options);\n
\n

where secureSocket has the same API as pair.cleartext.

" }, { "textRaw": "`tls.createServer([options][, secureConnectionListener])`", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.2" ], "changes": [ { "version": "v12.3.0", "pr-url": "https://github.com/nodejs/node/pull/27665", "description": "The `options` parameter now supports `net.createServer()` options." }, { "version": "v9.3.0", "pr-url": "https://github.com/nodejs/node/pull/14903", "description": "The `options` parameter can now include `clientCertEngine`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11984", "description": "The `ALPNProtocols` option can be a `TypedArray` or `DataView` now." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2564", "description": "ALPN options are supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {tls.Server}", "name": "return", "type": "tls.Server" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)", "name": "ALPNProtocols", "type": "string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| TypedArray|DataView", "desc": "An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. (Protocols should be ordered by their priority.)" }, { "textRaw": "`clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate.", "name": "clientCertEngine", "type": "string", "desc": "Name of an OpenSSL engine which can provide the client certificate." }, { "textRaw": "`enableTrace` {boolean} If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. **Default:** `false`.", "name": "enableTrace", "type": "boolean", "default": "`false`", "desc": "If `true`, [`tls.TLSSocket.enableTrace()`][] will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup." }, { "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out. **Default:** `120000` (120 seconds).", "name": "handshakeTimeout", "type": "number", "default": "`120000` (120 seconds)", "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out." }, { "textRaw": "`rejectUnauthorized` {boolean} If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. **Default:** `true`.", "name": "rejectUnauthorized", "type": "boolean", "default": "`true`", "desc": "If not `false` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`." }, { "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. **Default:** `false`.", "name": "requestCert", "type": "boolean", "default": "`false`", "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate." }, { "textRaw": "`sessionTimeout` {number} The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information. **Default:** `300`.", "name": "sessionTimeout", "type": "number", "default": "`300`", "desc": "The number of seconds after which a TLS session created by the server will no longer be resumable. See [Session Resumption][] for more information." }, { "textRaw": "`SNICallback(servername, callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below).", "name": "SNICallback(servername,", "desc": "callback)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `callback`. `callback` is an error-first callback that takes two optional arguments: `error` and `ctx`. `ctx`, if provided, is a `SecureContext` instance. [`tls.createSecureContext()`][] can be used to get a proper `SecureContext`. If `callback` is called with a falsy `ctx` argument, the default secure context of the server will be used. If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." }, { "textRaw": "`ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information.", "name": "ticketKeys", "type": "Buffer", "desc": "48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information." }, { "textRaw": "`pskCallback` {Function}When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][].", "name": "pskCallback", "type": "Function", "desc": "When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an \"unknown_psk_identity\" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection fail with \"decrypt_error\" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][].", "options": [ { "textRaw": "socket: {tls.TLSSocket} the server [`tls.TLSSocket`][] instance for this connection.", "name": "socket", "type": "tls.TLSSocket", "desc": "the server [`tls.TLSSocket`][] instance for this connection." }, { "textRaw": "identity: {string} identity parameter sent from the client.", "name": "identity", "type": "string", "desc": "identity parameter sent from the client." }, { "textRaw": "Returns: {Buffer|TypedArray|DataView} pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest.", "name": "return", "type": "Buffer|TypedArray|DataView", "desc": "pre-shared key that must either be a buffer or `null` to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest." } ] }, { "textRaw": "`pskIdentityHint` {string} optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code.", "name": "pskIdentityHint", "type": "string", "desc": "optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint `'tlsClientError'` will be emitted with `'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'` code." }, { "textRaw": "...: Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required.", "name": "...", "desc": "Any [`tls.createSecureContext()`][] option can be provided. For servers, the identity options (`pfx`, `key`/`cert` or `pskCallback`) are usually required." }, { "textRaw": "...: Any [`net.createServer()`][] option can be provided.", "name": "...", "desc": "Any [`net.createServer()`][] option can be provided." } ] }, { "textRaw": "`secureConnectionListener` {Function}", "name": "secureConnectionListener", "type": "Function" } ] } ], "desc": "

Creates a new tls.Server. The secureConnectionListener, if provided, is\nautomatically set as a listener for the 'secureConnection' event.

\n

The ticketKeys options is automatically shared between cluster module\nworkers.

\n

The following illustrates a simple echo server:

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses a self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nconst server = tls.createServer(options, (socket) => {\n  console.log('server connected',\n              socket.authorized ? 'authorized' : 'unauthorized');\n  socket.write('welcome!\\n');\n  socket.setEncoding('utf8');\n  socket.pipe(socket);\n});\nserver.listen(8000, () => {\n  console.log('server bound');\n});\n
\n

The server can be tested by connecting to it using the example client from\ntls.connect().

" }, { "textRaw": "`tls.getCiphers()`", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.10.2" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [] } ], "desc": "

Returns an array with the names of the supported TLS ciphers. The names are\nlower-case for historical reasons, but must be uppercased to be used in\nthe ciphers option of tls.createSecureContext().

\n

Cipher names that start with 'tls_' are for TLSv1.3, all the others are for\nTLSv1.2 and below.

\n
console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]\n
" } ], "properties": [ { "textRaw": "`rootCertificates` {string[]}", "type": "string[]", "name": "rootCertificates", "meta": { "added": [ "v12.3.0" ], "changes": [] }, "desc": "

An immutable array of strings representing the root certificates (in PEM format)\nfrom the bundled Mozilla CA store as supplied by current Node.js version.

\n

The 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.

" }, { "textRaw": "`tls.DEFAULT_ECDH_CURVE`", "name": "DEFAULT_ECDH_CURVE", "meta": { "added": [ "v0.11.13" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16853", "description": "Default value changed to `'auto'`." } ] }, "desc": "

The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'auto'. See tls.createSecureContext() for further\ninformation.

" }, { "textRaw": "`DEFAULT_MAX_VERSION` {string} The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.", "type": "string", "name": "DEFAULT_MAX_VERSION", "meta": { "added": [ "v11.4.0" ], "changes": [] }, "default": "`'TLSv1.3'`, unless changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used", "desc": "The default value of the `maxVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." }, { "textRaw": "`DEFAULT_MIN_VERSION` {string} The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used.", "type": "string", "name": "DEFAULT_MIN_VERSION", "meta": { "added": [ "v11.4.0" ], "changes": [] }, "default": "`'TLSv1.2'`, unless changed using CLI options. Using `--tls-min-v1.0` sets the default to `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is used", "shortDesc": "The default value of the `minVersion` option of [`tls.createSecureContext()`][]. It can be assigned any of the supported TLS protocol versions, `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`." } ], "type": "module", "displayName": "TLS (SSL)", "source": "doc/api/tls.md" }, { "textRaw": "Trace events", "name": "trace_events", "introduced_in": "v7.7.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Source Code: lib/trace_events.js

\n

The trace_events module provides a mechanism to centralize tracing information\ngenerated by V8, Node.js core, and userspace code.

\n

Tracing can be enabled with the --trace-event-categories command-line flag\nor by using the trace_events module. The --trace-event-categories flag\naccepts a list of comma-separated category names.

\n

The available categories are:

\n
    \n
  • node: An empty placeholder.
  • \n
  • node.async_hooks: Enables capture of detailed async_hooks trace data.\nThe async_hooks events have a unique asyncId and a special triggerId\ntriggerAsyncId property.
  • \n
  • node.bootstrap: Enables capture of Node.js bootstrap milestones.
  • \n
  • node.console: Enables capture of console.time() and console.count()\noutput.
  • \n
  • node.dns.native: Enables capture of trace data for DNS queries.
  • \n
  • node.environment: Enables capture of Node.js Environment milestones.
  • \n
  • node.fs.sync: Enables capture of trace data for file system sync methods.
  • \n
  • node.perf: Enables capture of Performance API measurements.\n
      \n
    • node.perf.usertiming: Enables capture of only Performance API User Timing\nmeasures and marks.
    • \n
    • node.perf.timerify: Enables capture of only Performance API timerify\nmeasurements.
    • \n
    \n
  • \n
  • node.promises.rejections: Enables capture of trace data tracking the number\nof unhandled Promise rejections and handled-after-rejections.
  • \n
  • node.vm.script: Enables capture of trace data for the vm module's\nrunInNewContext(), runInContext(), and runInThisContext() methods.
  • \n
  • v8: The V8 events are GC, compiling, and execution related.
  • \n
\n

By default the node, node.async_hooks, and v8 categories are enabled.

\n
node --trace-event-categories v8,node,node.async_hooks server.js\n
\n

Prior versions of Node.js required the use of the --trace-events-enabled\nflag to enable trace events. This requirement has been removed. However, the\n--trace-events-enabled flag may still be used and will enable the\nnode, node.async_hooks, and v8 trace event categories by default.

\n
node --trace-events-enabled\n\n# is equivalent to\n\nnode --trace-event-categories v8,node,node.async_hooks\n
\n

Alternatively, trace events may be enabled using the trace_events module:

\n
const trace_events = require('trace_events');\nconst tracing = trace_events.createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category\n
\n

Running Node.js with tracing enabled will produce log files that can be opened\nin the chrome://tracing\ntab of Chrome.

\n

The logging file is by default called node_trace.${rotation}.log, where\n${rotation} is an incrementing log-rotation id. The filepath pattern can\nbe specified with --trace-event-file-pattern that accepts a template\nstring that supports ${rotation} and ${pid}:

\n
node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js\n
\n

The tracing system uses the same time source\nas the one used by process.hrtime().\nHowever the trace-event timestamps are expressed in microseconds,\nunlike process.hrtime() which returns nanoseconds.

\n

The features from this module are not available in Worker threads.

", "modules": [ { "textRaw": "The `trace_events` module", "name": "the_`trace_events`_module", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "modules": [ { "textRaw": "`Tracing` object", "name": "`tracing`_object", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

The Tracing object is used to enable or disable tracing for sets of\ncategories. Instances are created using the trace_events.createTracing()\nmethod.

\n

When created, the Tracing object is disabled. Calling the\ntracing.enable() method adds the categories to the set of enabled trace event\ncategories. Calling tracing.disable() will remove the categories from the\nset of enabled trace event categories.

", "properties": [ { "textRaw": "`categories` {string}", "type": "string", "name": "categories", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

A comma-separated list of the trace event categories covered by this\nTracing object.

" }, { "textRaw": "`enabled` {boolean} `true` only if the `Tracing` object has been enabled.", "type": "boolean", "name": "enabled", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "`true` only if the `Tracing` object has been enabled." } ], "methods": [ { "textRaw": "`tracing.disable()`", "type": "method", "name": "disable", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Disables this Tracing object.

\n

Only trace event categories not covered by other enabled Tracing objects\nand not specified by the --trace-event-categories flag will be disabled.

\n
const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node', 'v8'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(trace_events.getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(trace_events.getEnabledCategories());\n
" }, { "textRaw": "`tracing.enable()`", "type": "method", "name": "enable", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Enables this Tracing object for the set of categories covered by the\nTracing object.

" } ], "type": "module", "displayName": "`Tracing` object" } ], "methods": [ { "textRaw": "`trace_events.createTracing(options)`", "type": "method", "name": "createTracing", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Tracing}.", "name": "return", "type": "Tracing", "desc": "." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`categories` {string[]} An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced.", "name": "categories", "type": "string[]", "desc": "An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced." } ] } ] } ], "desc": "

Creates and returns a Tracing object for the given set of categories.

\n
const trace_events = require('trace_events');\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = trace_events.createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();\n
" }, { "textRaw": "`trace_events.getEnabledCategories()`", "type": "method", "name": "getEnabledCategories", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns a comma-separated list of all currently-enabled trace event\ncategories. The current set of enabled trace event categories is determined\nby the union of all currently-enabled Tracing objects and any categories\nenabled using the --trace-event-categories flag.

\n

Given the file test.js below, the command\nnode --trace-event-categories node.perf test.js will print\n'node.async_hooks,node.perf' to the console.

\n
const trace_events = require('trace_events');\nconst t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });\nconst t2 = trace_events.createTracing({ categories: ['node.perf'] });\nconst t3 = trace_events.createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(trace_events.getEnabledCategories());\n
" } ], "type": "module", "displayName": "The `trace_events` module" } ], "type": "module", "displayName": "Trace events", "source": "doc/api/tracing.md" }, { "textRaw": "TTY", "name": "tty", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/tty.js

\n

The tty module provides the tty.ReadStream and tty.WriteStream classes.\nIn most cases, it will not be necessary or possible to use this module directly.\nHowever, it can be accessed using:

\n
const tty = require('tty');\n
\n

When Node.js detects that it is being run with a text terminal (\"TTY\")\nattached, process.stdin will, by default, be initialized as an instance of\ntty.ReadStream and both process.stdout and process.stderr will, by\ndefault, be instances of tty.WriteStream. The preferred method of determining\nwhether Node.js is being run within a TTY context is to check that the value of\nthe process.stdout.isTTY property is true:

\n
$ node -p -e \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p -e \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
\n

In most cases, there should be little to no reason for an application to\nmanually create instances of the tty.ReadStream and tty.WriteStream\nclasses.

", "classes": [ { "textRaw": "Class: `tty.ReadStream`", "type": "class", "name": "tty.ReadStream", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "\n

Represents the readable side of a TTY. In normal circumstances\nprocess.stdin will be the only tty.ReadStream instance in a Node.js\nprocess and there should be no reason to create additional instances.

", "properties": [ { "textRaw": "`readStream.isRaw`", "name": "isRaw", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

A boolean that is true if the TTY is currently configured to operate as a\nraw device. Defaults to false.

" }, { "textRaw": "`readStream.isTTY`", "name": "isTTY", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

A boolean that is always true for tty.ReadStream instances.

" } ], "methods": [ { "textRaw": "`readStream.setRawMode(mode)`", "type": "method", "name": "setRawMode", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this} The read stream instance.", "name": "return", "type": "this", "desc": "The read stream instance." }, "params": [ { "textRaw": "`mode` {boolean} If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode.", "name": "mode", "type": "boolean", "desc": "If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` property will be set to the resulting mode." } ] } ], "desc": "

Allows configuration of tty.ReadStream so that it operates as a raw device.

\n

When in raw mode, input is always available character-by-character, not\nincluding modifiers. Additionally, all special processing of characters by the\nterminal is disabled, including echoing input characters.\nCtrl+C will no longer cause a SIGINT when in this mode.

" } ] }, { "textRaw": "Class: `tty.WriteStream`", "type": "class", "name": "tty.WriteStream", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "\n

Represents the writable side of a TTY. In normal circumstances,\nprocess.stdout and process.stderr will be the only\ntty.WriteStream instances created for a Node.js process and there\nshould be no reason to create additional instances.

", "events": [ { "textRaw": "Event: `'resize'`", "type": "event", "name": "resize", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [], "desc": "

The 'resize' event is emitted whenever either of the writeStream.columns\nor writeStream.rows properties have changed. No arguments are passed to the\nlistener callback when called.

\n
process.stdout.on('resize', () => {\n  console.log('screen size has changed!');\n  console.log(`${process.stdout.columns}x${process.stdout.rows}`);\n});\n
" } ], "methods": [ { "textRaw": "`writeStream.clearLine(dir[, callback])`", "type": "method", "name": "clearLine", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28721", "description": "The stream's write() callback and return value are exposed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the 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 the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "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." } ] } ], "desc": "

writeStream.clearLine() clears the current line of this WriteStream in a\ndirection identified by dir.

" }, { "textRaw": "`writeStream.clearScreenDown([callback])`", "type": "method", "name": "clearScreenDown", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28721", "description": "The stream's write() callback and return value are exposed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the 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 the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

writeStream.clearScreenDown() clears this WriteStream from the current\ncursor down.

" }, { "textRaw": "`writeStream.cursorTo(x[, y][, callback])`", "type": "method", "name": "cursorTo", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28721", "description": "The stream's write() callback and return value are exposed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the 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 the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "textRaw": "`x` {number}", "name": "x", "type": "number" }, { "textRaw": "`y` {number}", "name": "y", "type": "number" }, { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

writeStream.cursorTo() moves this WriteStream's cursor to the specified\nposition.

" }, { "textRaw": "`writeStream.getColorDepth([env])`", "type": "method", "name": "getColorDepth", "meta": { "added": [ "v9.9.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [ { "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." } ] } ], "desc": "

Returns:

\n
    \n
  • 1 for 2,
  • \n
  • 4 for 16,
  • \n
  • 8 for 256,
  • \n
  • 24 for 16,777,216
  • \n
\n

colors supported.

\n

Use this to determine what colors the terminal supports. Due to the nature of\ncolors in terminals it is possible to either have false positives or false\nnegatives. It depends on process information and the environment variables that\nmay lie about what terminal is used.\nIt is possible to pass in an env object to simulate the usage of a specific\nterminal. This can be useful to check how specific environment settings behave.

\n

To enforce a specific color support, use one of the below environment settings.

\n
    \n
  • 2 colors: FORCE_COLOR = 0 (Disables colors)
  • \n
  • 16 colors: FORCE_COLOR = 1
  • \n
  • 256 colors: FORCE_COLOR = 2
  • \n
  • 16,777,216 colors: FORCE_COLOR = 3
  • \n
\n

Disabling color support is also possible by using the NO_COLOR and\nNODE_DISABLE_COLORS environment variables.

" }, { "textRaw": "`writeStream.getWindowSize()`", "type": "method", "name": "getWindowSize", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number[]}", "name": "return", "type": "number[]" }, "params": [] } ], "desc": "

writeStream.getWindowSize() returns the size of the TTY\ncorresponding to this WriteStream. The array is of the type\n[numColumns, numRows] where numColumns and numRows represent the number\nof columns and rows in the corresponding TTY.

" }, { "textRaw": "`writeStream.hasColors([count][, env])`", "type": "method", "name": "hasColors", "meta": { "added": [ "v11.13.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`count` {integer} The number of colors that are requested (minimum 2). **Default:** 16.", "name": "count", "type": "integer", "default": "16", "desc": "The number of colors that are requested (minimum 2)." }, { "textRaw": "`env` {Object} An object containing the environment variables to check. This enables simulating the usage of a specific terminal. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "An object containing the environment variables to check. This enables simulating the usage of a specific terminal." } ] } ], "desc": "

Returns true if the writeStream supports at least as many colors as provided\nin count. Minimum support is 2 (black and white).

\n

This has the same false positives and negatives as described in\nwriteStream.getColorDepth().

\n
process.stdout.hasColors();\n// Returns true or false depending on if `stdout` supports at least 16 colors.\nprocess.stdout.hasColors(256);\n// Returns true or false depending on if `stdout` supports at least 256 colors.\nprocess.stdout.hasColors({ TMUX: '1' });\n// Returns true.\nprocess.stdout.hasColors(2 ** 24, { TMUX: '1' });\n// Returns false (the environment setting pretends to support 2 ** 8 colors).\n
" }, { "textRaw": "`writeStream.moveCursor(dx, dy[, callback])`", "type": "method", "name": "moveCursor", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v12.7.0", "pr-url": "https://github.com/nodejs/node/pull/28721", "description": "The stream's write() callback and return value are exposed." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the 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 the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "textRaw": "`dx` {number}", "name": "dx", "type": "number" }, { "textRaw": "`dy` {number}", "name": "dy", "type": "number" }, { "textRaw": "`callback` {Function} Invoked once the operation completes.", "name": "callback", "type": "Function", "desc": "Invoked once the operation completes." } ] } ], "desc": "

writeStream.moveCursor() moves this WriteStream's cursor relative to its\ncurrent position.

" } ], "properties": [ { "textRaw": "`writeStream.columns`", "name": "columns", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

A number specifying the number of columns the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

" }, { "textRaw": "`writeStream.isTTY`", "name": "isTTY", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

A boolean that is always true.

" }, { "textRaw": "`writeStream.rows`", "name": "rows", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

A number specifying the number of rows the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

" } ] } ], "methods": [ { "textRaw": "`tty.isatty(fd)`", "type": "method", "name": "isatty", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`fd` {number} A numeric file descriptor", "name": "fd", "type": "number", "desc": "A numeric file descriptor" } ] } ], "desc": "

The tty.isatty() method returns true if the given fd is associated with\na TTY and false if it is not, including whenever fd is not a non-negative\ninteger.

" } ], "type": "module", "displayName": "TTY", "source": "doc/api/tty.md" }, { "textRaw": "UDP/datagram sockets", "name": "dgram", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/dgram.js

\n

The dgram module provides an implementation of UDP datagram sockets.

\n
import dgram from 'dgram';\n\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
\n
const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
", "classes": [ { "textRaw": "Class: `dgram.Socket`", "type": "class", "name": "dgram.Socket", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "desc": "\n

Encapsulates the datagram functionality.

\n

New instances of dgram.Socket are created using dgram.createSocket().\nThe new keyword is not to be used to create dgram.Socket instances.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted after a socket is closed with close().\nOnce triggered, no new 'message' events will be emitted on this socket.

" }, { "textRaw": "Event: `'connect'`", "type": "event", "name": "connect", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "params": [], "desc": "

The 'connect' event is emitted after a socket is associated to a remote\naddress as a result of a successful connect() call.

" }, { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "params": [ { "textRaw": "`exception` {Error}", "name": "exception", "type": "Error" } ], "desc": "

The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.

" }, { "textRaw": "Event: `'listening'`", "type": "event", "name": "listening", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "params": [], "desc": "

The 'listening' event is emitted once the dgram.Socket is addressable and\ncan receive data. This happens either explicitly with socket.bind() or\nimplicitly the first time data is sent using socket.send().\nUntil the dgram.Socket is listening, the underlying system resources do not\nexist and calls such as socket.address() and socket.setTTL() will fail.

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "params": [], "desc": "

The 'message' event is emitted when a new datagram is available on a socket.\nThe event handler function is passed two arguments: msg and rinfo.

\n\n

If the source address of the incoming packet is an IPv6 link-local\naddress, the interface name is added to the address. For\nexample, a packet received on the en0 interface might have the\naddress field set to 'fe80::2618:1234:ab11:3b9c%en0', where '%en0'\nis the interface name as a zone ID suffix.

" } ], "methods": [ { "textRaw": "`socket.addMembership(multicastAddress[, multicastInterface])`", "type": "method", "name": "addMembership", "meta": { "added": [ "v0.6.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {string}", "name": "multicastAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string}", "name": "multicastInterface", "type": "string" } ] } ], "desc": "

Tells the kernel to join a multicast group at the given multicastAddress and\nmulticastInterface using the IP_ADD_MEMBERSHIP socket option. If the\nmulticastInterface argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call addMembership multiple times, once per interface.

\n

When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

\n

When sharing a UDP socket across multiple cluster workers, the\nsocket.addMembership() function must be called only once or an\nEADDRINUSE error will occur:

\n
import cluster from 'cluster';\nimport dgram from 'dgram';\n\nif (cluster.isPrimary) {\n  cluster.fork(); // Works ok.\n  cluster.fork(); // Fails with EADDRINUSE.\n} else {\n  const s = dgram.createSocket('udp4');\n  s.bind(1234, () => {\n    s.addMembership('224.0.0.114');\n  });\n}\n
\n
const cluster = require('cluster');\nconst dgram = require('dgram');\n\nif (cluster.isPrimary) {\n  cluster.fork(); // Works ok.\n  cluster.fork(); // Fails with EADDRINUSE.\n} else {\n  const s = dgram.createSocket('udp4');\n  s.bind(1234, () => {\n    s.addMembership('224.0.0.114');\n  });\n}\n
" }, { "textRaw": "`socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", "type": "method", "name": "addSourceSpecificMembership", "meta": { "added": [ "v13.1.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`sourceAddress` {string}", "name": "sourceAddress", "type": "string" }, { "textRaw": "`groupAddress` {string}", "name": "groupAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string}", "name": "multicastInterface", "type": "string" } ] } ], "desc": "

Tells the kernel to join a source-specific multicast channel at the given\nsourceAddress and groupAddress, using the multicastInterface with the\nIP_ADD_SOURCE_MEMBERSHIP socket option. If the multicastInterface argument\nis not specified, the operating system will choose one interface and will add\nmembership to it. To add membership to every available interface, call\nsocket.addSourceSpecificMembership() multiple times, once per interface.

\n

When called on an unbound socket, this method will implicitly bind to a random\nport, listening on all interfaces.

" }, { "textRaw": "`socket.address()`", "type": "method", "name": "address", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.

\n

This method throws EBADF if called on an unbound socket.

" }, { "textRaw": "`socket.bind([port][, address][, callback])`", "type": "method", "name": "bind", "meta": { "added": [ "v0.1.99" ], "changes": [ { "version": "v0.9.1", "commit": "332fea5ac1816e498030109c4211bca24a7fa667", "description": "The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call." } ] }, "signatures": [ { "params": [ { "textRaw": "`port` {integer}", "name": "port", "type": "integer" }, { "textRaw": "`address` {string}", "name": "address", "type": "string" }, { "textRaw": "`callback` {Function} with no parameters. Called when binding is complete.", "name": "callback", "type": "Function", "desc": "with no parameters. Called when binding is complete." } ] } ], "desc": "

For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address. If port is not\nspecified or is 0, the operating system will attempt to bind to a\nrandom port. If address is not specified, the operating system will\nattempt to listen on all addresses. Once binding is complete, a\n'listening' event is emitted and the optional callback function is\ncalled.

\n

Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

\n

A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

\n

If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

\n

Example of a UDP server listening on port 41234:

\n
import dgram from 'dgram';\n\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
\n
const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  const address = server.address();\n  console.log(`server listening ${address.address}:${address.port}`);\n});\n\nserver.bind(41234);\n// Prints: server listening 0.0.0.0:41234\n
" }, { "textRaw": "`socket.bind(options[, callback])`", "type": "method", "name": "bind", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Required. Supports the following properties:", "name": "options", "type": "Object", "desc": "Required. Supports the following properties:", "options": [ { "textRaw": "`port` {integer}", "name": "port", "type": "integer" }, { "textRaw": "`address` {string}", "name": "address", "type": "string" }, { "textRaw": "`exclusive` {boolean}", "name": "exclusive", "type": "boolean" }, { "textRaw": "`fd` {integer}", "name": "fd", "type": "integer" } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

For UDP sockets, causes the dgram.Socket to listen for datagram\nmessages on a named port and optional address that are passed as\nproperties of an options object passed as the first argument. If\nport is not specified or is 0, the operating system will attempt\nto bind to a random port. If address is not specified, the operating\nsystem will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening' event is emitted and the optional callback\nfunction is called.

\n

The options object may contain a fd property. When a fd greater\nthan 0 is set, it will wrap around an existing socket with the given\nfile descriptor. In this case, the properties of port and address\nwill be ignored.

\n

Specifying both a 'listening' event listener and passing a\ncallback to the socket.bind() method is not harmful but not very\nuseful.

\n

The options object may contain an additional exclusive property that is\nused when using dgram.Socket objects with the cluster module. When\nexclusive is set to false (the default), cluster workers will use the same\nunderlying socket handle allowing connection handling duties to be shared.\nWhen exclusive is true, however, the handle is not shared and attempted\nport sharing results in an error.

\n

A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.

\n

If binding fails, an 'error' event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error may be thrown.

\n

An example socket listening on an exclusive port is shown below.

\n
socket.bind({\n  address: 'localhost',\n  port: 8000,\n  exclusive: true\n});\n
" }, { "textRaw": "`socket.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Called when the socket has been closed.", "name": "callback", "type": "Function", "desc": "Called when the socket has been closed." } ] } ], "desc": "

Close the underlying socket and stop listening for data on it. If a callback is\nprovided, it is added as a listener for the 'close' event.

" }, { "textRaw": "`socket.connect(port[, address][, callback])`", "type": "method", "name": "connect", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`port` {integer}", "name": "port", "type": "integer" }, { "textRaw": "`address` {string}", "name": "address", "type": "string" }, { "textRaw": "`callback` {Function} Called when the connection is completed or on error.", "name": "callback", "type": "Function", "desc": "Called when the connection is completed or on error." } ] } ], "desc": "

Associates the dgram.Socket to a remote address and port. Every\nmessage sent by this handle is automatically sent to that destination. Also,\nthe socket will only receive messages from that remote peer.\nTrying to call connect() on an already connected socket will result\nin an ERR_SOCKET_DGRAM_IS_CONNECTED exception. If address is not\nprovided, '127.0.0.1' (for udp4 sockets) or '::1' (for udp6 sockets)\nwill be used by default. Once the connection is complete, a 'connect' event\nis emitted and the optional callback function is called. In case of failure,\nthe callback is called or, failing this, an 'error' event is emitted.

" }, { "textRaw": "`socket.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

A synchronous function that disassociates a connected dgram.Socket from\nits remote address. Trying to call disconnect() on an unbound or already\ndisconnected socket will result in an ERR_SOCKET_DGRAM_NOT_CONNECTED\nexception.

" }, { "textRaw": "`socket.dropMembership(multicastAddress[, multicastInterface])`", "type": "method", "name": "dropMembership", "meta": { "added": [ "v0.6.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {string}", "name": "multicastAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string}", "name": "multicastInterface", "type": "string" } ] } ], "desc": "

Instructs the kernel to leave a multicast group at multicastAddress using the\nIP_DROP_MEMBERSHIP socket option. This method is automatically called by the\nkernel when the socket is closed or the process terminates, so most apps will\nnever have reason to call this.

\n

If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

" }, { "textRaw": "`socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`", "type": "method", "name": "dropSourceSpecificMembership", "meta": { "added": [ "v13.1.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`sourceAddress` {string}", "name": "sourceAddress", "type": "string" }, { "textRaw": "`groupAddress` {string}", "name": "groupAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string}", "name": "multicastInterface", "type": "string" } ] } ], "desc": "

Instructs the kernel to leave a source-specific multicast channel at the given\nsourceAddress and groupAddress using the IP_DROP_SOURCE_MEMBERSHIP\nsocket option. This method is automatically called by the kernel when the\nsocket is closed or the process terminates, so most apps will never have\nreason to call this.

\n

If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.

" }, { "textRaw": "`socket.getRecvBufferSize()`", "type": "method", "name": "getRecvBufferSize", "meta": { "added": [ "v8.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number} the `SO_RCVBUF` socket receive buffer size in bytes.", "name": "return", "type": "number", "desc": "the `SO_RCVBUF` socket receive buffer size in bytes." }, "params": [] } ], "desc": "

This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

" }, { "textRaw": "`socket.getSendBufferSize()`", "type": "method", "name": "getSendBufferSize", "meta": { "added": [ "v8.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number} the `SO_SNDBUF` socket send buffer size in bytes.", "name": "return", "type": "number", "desc": "the `SO_SNDBUF` socket send buffer size in bytes." }, "params": [] } ], "desc": "

This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

" }, { "textRaw": "`socket.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket}", "name": "return", "type": "dgram.Socket" }, "params": [] } ], "desc": "

By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active. The socket.ref() method adds the socket back to the reference\ncounting and restores the default behavior.

\n

Calling socket.ref() multiples times will have no additional effect.

\n

The socket.ref() method returns a reference to the socket so calls can be\nchained.

" }, { "textRaw": "`socket.remoteAddress()`", "type": "method", "name": "remoteAddress", "meta": { "added": [ "v12.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object containing the address, family, and port of the remote\nendpoint. This method throws an ERR_SOCKET_DGRAM_NOT_CONNECTED exception\nif the socket is not connected.

" }, { "textRaw": "`socket.send(msg[, offset, length][, port][, address][, callback])`", "type": "method", "name": "send", "meta": { "added": [ "v0.1.99" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/22413", "description": "The `msg` parameter can now be any `TypedArray` or `DataView`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26871", "description": "Added support for sending data on connected sockets." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11985", "description": "The `msg` parameter can be an `Uint8Array` now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/10473", "description": "The `address` parameter is always optional now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5929", "description": "On success, `callback` will now be called with an `error` argument of `null` rather than `0`." }, { "version": "v5.7.0", "pr-url": "https://github.com/nodejs/node/pull/4374", "description": "The `msg` parameter can be an array now. Also, the `offset` and `length` parameters are optional now." } ] }, "signatures": [ { "params": [ { "textRaw": "`msg` {Buffer|TypedArray|DataView|string|Array} Message to be sent.", "name": "msg", "type": "Buffer|TypedArray|DataView|string|Array", "desc": "Message to be sent." }, { "textRaw": "`offset` {integer} Offset in the buffer where the message starts.", "name": "offset", "type": "integer", "desc": "Offset in the buffer where the message starts." }, { "textRaw": "`length` {integer} Number of bytes in the message.", "name": "length", "type": "integer", "desc": "Number of bytes in the message." }, { "textRaw": "`port` {integer} Destination port.", "name": "port", "type": "integer", "desc": "Destination port." }, { "textRaw": "`address` {string} Destination host name or IP address.", "name": "address", "type": "string", "desc": "Destination host name or IP address." }, { "textRaw": "`callback` {Function} Called when the message has been sent.", "name": "callback", "type": "Function", "desc": "Called when the message has been sent." } ] } ], "desc": "

Broadcasts a datagram on the socket.\nFor connectionless sockets, the destination port and address must be\nspecified. Connected sockets, on the other hand, will use their associated\nremote endpoint, so the port and address arguments must not be set.

\n

The msg argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg is a Buffer,\nany TypedArray or a DataView,\nthe offset and length specify the offset within the Buffer where the\nmessage begins and the number of bytes in the message, respectively.\nIf msg is a String, then it is automatically converted to a Buffer\nwith 'utf8' encoding. With messages that\ncontain multi-byte characters, offset and length will be calculated with\nrespect to byte length and not the character position.\nIf msg is an array, offset and length must not be specified.

\n

The address argument is a string. If the value of address is a host name,\nDNS will be used to resolve the address of the host. If address is not\nprovided or otherwise falsy, '127.0.0.1' (for udp4 sockets) or '::1'\n(for udp6 sockets) will be used by default.

\n

If the socket has not been previously bound with a call to bind, the socket\nis assigned a random port number and is bound to the \"all interfaces\" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)

\n

An optional callback function may be specified to as a way of reporting\nDNS errors or for determining when it is safe to reuse the buf object.\nDNS lookups delay the time to send for at least one tick of the\nNode.js event loop.

\n

The only way to know for sure that the datagram has been sent is by using a\ncallback. If an error occurs and a callback is given, the error will be\npassed as the first argument to the callback. If a callback is not given,\nthe error is emitted as an 'error' event on the socket object.

\n

Offset and length are optional but both must be set if either are used.\nThey are supported only when the first argument is a Buffer, a TypedArray,\nor a DataView.

\n

This method throws ERR_SOCKET_BAD_PORT if called on an unbound socket.

\n

Example of sending a UDP packet to a port on localhost;

\n
import dgram from 'dgram';\nimport { Buffer } from 'buffer';\n\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n  client.close();\n});\n
\n
const dgram = require('dgram');\nconst { Buffer } = require('buffer');\n\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n  client.close();\n});\n
\n

Example of sending a UDP packet composed of multiple buffers to a port on\n127.0.0.1;

\n
import dgram from 'dgram';\nimport { Buffer } from 'buffer';\n\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, (err) => {\n  client.close();\n});\n
\n
const dgram = require('dgram');\nconst { Buffer } = require('buffer');\n\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, (err) => {\n  client.close();\n});\n
\n

Sending multiple buffers might be faster or slower depending on the\napplication and operating system. Run benchmarks to\ndetermine the optimal strategy on a case-by-case basis. Generally speaking,\nhowever, sending multiple buffers is faster.

\n

Example of sending a UDP packet using a socket connected to a port on\nlocalhost:

\n
import dgram from 'dgram';\nimport { Buffer } from 'buffer';\n\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.connect(41234, 'localhost', (err) => {\n  client.send(message, (err) => {\n    client.close();\n  });\n});\n
\n
const dgram = require('dgram');\nconst { Buffer } = require('buffer');\n\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.connect(41234, 'localhost', (err) => {\n  client.send(message, (err) => {\n    client.close();\n  });\n});\n
", "modules": [ { "textRaw": "Note about UDP datagram size", "name": "note_about_udp_datagram_size", "desc": "

The maximum size of an IPv4/v6 datagram depends on the MTU\n(Maximum Transmission Unit) and on the Payload Length field size.

\n
    \n
  • \n

    The Payload Length field is 16 bits wide, which means that a normal\npayload cannot exceed 64K octets including the internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagram\nmessages are impractical for most hosts and networks.

    \n
  • \n
  • \n

    The MTU is the largest size a given link layer technology can support for\ndatagram messages. For any link, IPv4 mandates a minimum MTU of 68\noctets, while the recommended MTU for IPv4 is 576 (typically recommended\nas the MTU for dial-up type applications), whether they arrive whole or in\nfragments.

    \n

    For IPv6, the minimum MTU is 1280 octets. However, the mandatory minimum\nfragment reassembly buffer size is 1500 octets. The value of 68 octets is\nvery small, since most current link layer technologies, like Ethernet, have a\nminimum MTU of 1500.

    \n
  • \n
\n

It is impossible to know in advance the MTU of each link through which\na packet might travel. Sending a datagram greater than the receiver MTU will\nnot work because the packet will get silently dropped without informing the\nsource that the data did not reach its intended recipient.

", "type": "module", "displayName": "Note about UDP datagram size" } ] }, { "textRaw": "`socket.setBroadcast(flag)`", "type": "method", "name": "setBroadcast", "meta": { "added": [ "v0.6.9" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`flag` {boolean}", "name": "flag", "type": "boolean" } ] } ], "desc": "

Sets or clears the SO_BROADCAST socket option. When set to true, UDP\npackets may be sent to a local interface's broadcast address.

\n

This method throws EBADF if called on an unbound socket.

" }, { "textRaw": "`socket.setMulticastInterface(multicastInterface)`", "type": "method", "name": "setMulticastInterface", "meta": { "added": [ "v8.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`multicastInterface` {string}", "name": "multicastInterface", "type": "string" } ] } ], "desc": "

All references to scope in this section are referring to\nIPv6 Zone Indices, which are defined by RFC 4007. In string form, an IP\nwith a scope index is written as 'IP%scope' where scope is an interface name\nor interface number.

\n

Sets the default outgoing multicast interface of the socket to a chosen\ninterface or back to system interface selection. The multicastInterface must\nbe a valid string representation of an IP from the socket's family.

\n

For IPv4 sockets, this should be the IP configured for the desired physical\ninterface. All packets sent to multicast on the socket will be sent on the\ninterface determined by the most recent successful use of this call.

\n

For IPv6 sockets, multicastInterface should include a scope to indicate the\ninterface as in the examples that follow. In IPv6, individual send calls can\nalso use explicit scope in addresses, so only packets sent to a multicast\naddress without specifying an explicit scope are affected by the most recent\nsuccessful use of this call.

\n

This method throws EBADF if called on an unbound socket.

\n

Example: IPv6 outgoing multicast interface

\n

On most systems, where scope format uses the interface name:

\n
const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%eth1');\n});\n
\n

On Windows, where scope format uses an interface number:

\n
const socket = dgram.createSocket('udp6');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('::%2');\n});\n
\n

Example: IPv4 outgoing multicast interface

\n

All systems use an IP of the host on the desired physical interface:

\n
const socket = dgram.createSocket('udp4');\n\nsocket.bind(1234, () => {\n  socket.setMulticastInterface('10.0.0.2');\n});\n
", "modules": [ { "textRaw": "Call results", "name": "call_results", "desc": "

A call on a socket that is not ready to send or no longer open may throw a Not\nrunning Error.

\n

If multicastInterface can not be parsed into an IP then an EINVAL\nSystem Error is thrown.

\n

On IPv4, if multicastInterface is a valid address but does not match any\ninterface, or if the address does not match the family then\na System Error such as EADDRNOTAVAIL or EPROTONOSUP is thrown.

\n

On IPv6, most errors with specifying or omitting scope will result in the socket\ncontinuing to use (or returning to) the system's default interface selection.

\n

A socket's address family's ANY address (IPv4 '0.0.0.0' or IPv6 '::') can be\nused to return control of the sockets default outgoing interface to the system\nfor future multicast packets.

", "type": "module", "displayName": "Call results" } ] }, { "textRaw": "`socket.setMulticastLoopback(flag)`", "type": "method", "name": "setMulticastLoopback", "meta": { "added": [ "v0.3.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`flag` {boolean}", "name": "flag", "type": "boolean" } ] } ], "desc": "

Sets or clears the IP_MULTICAST_LOOP socket option. When set to true,\nmulticast packets will also be received on the local interface.

\n

This method throws EBADF if called on an unbound socket.

" }, { "textRaw": "`socket.setMulticastTTL(ttl)`", "type": "method", "name": "setMulticastTTL", "meta": { "added": [ "v0.3.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {integer}", "name": "ttl", "type": "integer" } ] } ], "desc": "

Sets the IP_MULTICAST_TTL socket option. While TTL generally stands for\n\"Time to Live\", in this context it specifies the number of IP hops that a\npacket is allowed to travel through, specifically for multicast traffic. Each\nrouter or gateway that forwards a packet decrements the TTL. If the TTL is\ndecremented to 0 by a router, it will not be forwarded.

\n

The ttl argument may be between 0 and 255. The default on most systems is 1.

\n

This method throws EBADF if called on an unbound socket.

" }, { "textRaw": "`socket.setRecvBufferSize(size)`", "type": "method", "name": "setRecvBufferSize", "meta": { "added": [ "v8.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer}", "name": "size", "type": "integer" } ] } ], "desc": "

Sets the SO_RCVBUF socket option. Sets the maximum socket receive buffer\nin bytes.

\n

This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

" }, { "textRaw": "`socket.setSendBufferSize(size)`", "type": "method", "name": "setSendBufferSize", "meta": { "added": [ "v8.7.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer}", "name": "size", "type": "integer" } ] } ], "desc": "

Sets the SO_SNDBUF socket option. Sets the maximum socket send buffer\nin bytes.

\n

This method throws ERR_SOCKET_BUFFER_SIZE if called on an unbound socket.

" }, { "textRaw": "`socket.setTTL(ttl)`", "type": "method", "name": "setTTL", "meta": { "added": [ "v0.1.101" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {integer}", "name": "ttl", "type": "integer" } ] } ], "desc": "

Sets the IP_TTL socket option. While TTL generally stands for \"Time to Live\",\nin this context it specifies the number of IP hops that a packet is allowed to\ntravel through. Each router or gateway that forwards a packet decrements the\nTTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\nChanging TTL values is typically done for network probes or when multicasting.

\n

The ttl argument may be between between 1 and 255. The default on most systems\nis 64.

\n

This method throws EBADF if called on an unbound socket.

" }, { "textRaw": "`socket.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket}", "name": "return", "type": "dgram.Socket" }, "params": [] } ], "desc": "

By default, binding a socket will cause it to block the Node.js process from\nexiting as long as the socket is open. The socket.unref() method can be used\nto exclude the socket from the reference counting that keeps the Node.js\nprocess active, allowing the process to exit even if the socket is still\nlistening.

\n

Calling socket.unref() multiple times will have no addition effect.

\n

The socket.unref() method returns a reference to the socket so calls can be\nchained.

" } ] } ], "modules": [ { "textRaw": "`dgram` module functions", "name": "`dgram`_module_functions", "methods": [ { "textRaw": "`dgram.createSocket(options[, callback])`", "type": "method", "name": "createSocket", "meta": { "added": [ "v0.11.13" ], "changes": [ { "version": "v15.8.0", "pr-url": "https://github.com/nodejs/node/pull/37026", "description": "AbortSignal support was added." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/23798", "description": "The `ipv6Only` option is supported." }, { "version": "v8.7.0", "pr-url": "https://github.com/nodejs/node/pull/13623", "description": "The `recvBufferSize` and `sendBufferSize` options are supported now." }, { "version": "v8.6.0", "pr-url": "https://github.com/nodejs/node/pull/14560", "description": "The `lookup` option is supported." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket}", "name": "return", "type": "dgram.Socket" }, "params": [ { "textRaw": "`options` {Object} Available options are:", "name": "options", "type": "Object", "desc": "Available options are:", "options": [ { "textRaw": "`type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`. Required.", "name": "type", "type": "string", "desc": "The family of socket. Must be either `'udp4'` or `'udp6'`. Required." }, { "textRaw": "`reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it. **Default:** `false`.", "name": "reuseAddr", "type": "boolean", "default": "`false`", "desc": "When `true` [`socket.bind()`][] will reuse the address, even if another process has already bound a socket on it." }, { "textRaw": "`ipv6Only` {boolean} Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound. **Default:** `false`.", "name": "ipv6Only", "type": "boolean", "default": "`false`", "desc": "Setting `ipv6Only` to `true` will disable dual-stack support, i.e., binding to address `::` won't make `0.0.0.0` be bound." }, { "textRaw": "`recvBufferSize` {number} Sets the `SO_RCVBUF` socket value.", "name": "recvBufferSize", "type": "number", "desc": "Sets the `SO_RCVBUF` socket value." }, { "textRaw": "`sendBufferSize` {number} Sets the `SO_SNDBUF` socket value.", "name": "sendBufferSize", "type": "number", "desc": "Sets the `SO_SNDBUF` socket value." }, { "textRaw": "`lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].", "name": "lookup", "type": "Function", "default": "[`dns.lookup()`][]", "desc": "Custom lookup function." }, { "textRaw": "`signal` {AbortSignal} An AbortSignal that may be used to close a socket.", "name": "signal", "type": "AbortSignal", "desc": "An AbortSignal that may be used to close a socket." } ] }, { "textRaw": "`callback` {Function} Attached as a listener for `'message'` events. Optional.", "name": "callback", "type": "Function", "desc": "Attached as a listener for `'message'` events. Optional." } ] } ], "desc": "

Creates a dgram.Socket object. Once the socket is created, calling\nsocket.bind() will instruct the socket to begin listening for datagram\nmessages. When address and port are not passed to socket.bind() the\nmethod will bind the socket to the \"all interfaces\" address on a random port\n(it does the right thing for both udp4 and udp6 sockets). The bound address\nand port can be retrieved using socket.address().address and\nsocket.address().port.

\n

If the signal option is enabled, calling .abort() on the corresponding\nAbortController is similar to calling .close() on the socket:

\n
const controller = new AbortController();\nconst { signal } = controller;\nconst server = dgram.createSocket({ type: 'udp4', signal });\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n// Later, when you want to close the server.\ncontroller.abort();\n
" }, { "textRaw": "`dgram.createSocket(type[, callback])`", "type": "method", "name": "createSocket", "meta": { "added": [ "v0.1.99" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket}", "name": "return", "type": "dgram.Socket" }, "params": [ { "textRaw": "`type` {string} Either `'udp4'` or `'udp6'`.", "name": "type", "type": "string", "desc": "Either `'udp4'` or `'udp6'`." }, { "textRaw": "`callback` {Function} Attached as a listener to `'message'` events.", "name": "callback", "type": "Function", "desc": "Attached as a listener to `'message'` events." } ] } ], "desc": "

Creates a dgram.Socket object of the specified type.

\n

Once the socket is created, calling socket.bind() will instruct the\nsocket to begin listening for datagram messages. When address and port are\nnot passed to socket.bind() the method will bind the socket to the \"all\ninterfaces\" address on a random port (it does the right thing for both udp4\nand udp6 sockets). The bound address and port can be retrieved using\nsocket.address().address and socket.address().port.

" } ], "type": "module", "displayName": "`dgram` module functions" } ], "type": "module", "displayName": "dgram", "source": "doc/api/dgram.md" }, { "textRaw": "URL", "name": "url", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/url.js

\n

The url module provides utilities for URL resolution and parsing. It can be\naccessed using:

\n
import url from 'url';\n
\n
const url = require('url');\n
", "modules": [ { "textRaw": "URL strings and URL objects", "name": "url_strings_and_url_objects", "desc": "

A URL string is a structured string containing multiple meaningful components.\nWhen parsed, a URL object is returned containing properties for each of these\ncomponents.

\n

The url module provides two APIs for working with URLs: a legacy API that is\nNode.js specific, and a newer API that implements the same\nWHATWG URL Standard used by web browsers.

\n

A comparison between the WHATWG and Legacy APIs is provided below. Above the URL\n'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties\nof an object returned by the legacy url.parse() are shown. Below it are\nproperties of a WHATWG URL object.

\n

WHATWG URL's origin property includes protocol and host, but not\nusername or password.

\n
┌────────────────────────────────────────────────────────────────────────────────────────────────┐\n│                                              href                                              │\n├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤\n│ protocol │  │        auth         │          host          │           path            │ hash  │\n│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │\n│          │  │                     │    hostname     │ port │ pathname │     search     │       │\n│          │  │                     │                 │      │          ├─┬──────────────┤       │\n│          │  │                     │                 │      │          │ │    query     │       │\n\"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash \"\n│          │  │          │          │    hostname     │ port │          │                │       │\n│          │  │          │          ├─────────────────┴──────┤          │                │       │\n│ protocol │  │ username │ password │          host          │          │                │       │\n├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │\n│   origin    │                     │         origin         │ pathname │     search     │ hash  │\n├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤\n│                                              href                                              │\n└────────────────────────────────────────────────────────────────────────────────────────────────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
\n

Parsing the URL string using the WHATWG API:

\n
const myURL =\n  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
\n

Parsing the URL string using the Legacy API:

\n
import url from 'url';\nconst myURL =\n  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
\n
const url = require('url');\nconst myURL =\n  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
", "modules": [ { "textRaw": "Constructing a URL from component parts and getting the constructed string", "name": "constructing_a_url_from_component_parts_and_getting_the_constructed_string", "desc": "

It is possible to construct a WHATWG URL from component parts using either the\nproperty setters or a template literal string:

\n
const myURL = new URL('https://example.org');\nmyURL.pathname = '/a/b/c';\nmyURL.search = '?d=e';\nmyURL.hash = '#fgh';\n
\n
const pathname = '/a/b/c';\nconst search = '?d=e';\nconst hash = '#fgh';\nconst myURL = new URL(`https://example.org${pathname}${search}${hash}`);\n
\n

To get the constructed URL string, use the href property accessor:

\n
console.log(myURL.href);\n
", "type": "module", "displayName": "Constructing a URL from component parts and getting the constructed string" } ], "type": "module", "displayName": "URL strings and URL objects" }, { "textRaw": "The WHATWG URL API", "name": "the_whatwg_url_api", "classes": [ { "textRaw": "Class: `URL`", "type": "class", "name": "URL", "meta": { "added": [ "v7.0.0", "v6.13.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18281", "description": "The class is now available on the global object." } ] }, "desc": "

Browser-compatible URL class, implemented by following the WHATWG URL\nStandard. Examples of parsed URLs may be found in the Standard itself.\nThe URL class is also available on the global object.

\n

In accordance with browser conventions, all properties of URL objects\nare implemented as getters and setters on the class prototype, rather than as\ndata properties on the object itself. Thus, unlike legacy urlObjects,\nusing the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still\nreturn true.

", "properties": [ { "textRaw": "`hash` {string}", "type": "string", "name": "hash", "desc": "

Gets and sets the fragment portion of the URL.

\n
const myURL = new URL('https://example.org/foo#bar');\nconsole.log(myURL.hash);\n// Prints #bar\n\nmyURL.hash = 'baz';\nconsole.log(myURL.href);\n// Prints https://example.org/foo#baz\n
\n

Invalid URL characters included in the value assigned to the hash property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

" }, { "textRaw": "`host` {string}", "type": "string", "name": "host", "desc": "

Gets and sets the host portion of the URL.

\n
const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.host);\n// Prints example.org:81\n\nmyURL.host = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:82/foo\n
\n

Invalid host values assigned to the host property are ignored.

" }, { "textRaw": "`hostname` {string}", "type": "string", "name": "hostname", "desc": "

Gets and sets the host name portion of the URL. The key difference between\nurl.host and url.hostname is that url.hostname does not include the\nport.

\n
const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n// Prints example.org\n\n// Setting the hostname does not change the port\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:81/foo\n\n// Use myURL.host to change the hostname and port\nmyURL.host = 'example.org:82';\nconsole.log(myURL.href);\n// Prints https://example.org:82/foo\n
\n

Invalid host name values assigned to the hostname property are ignored.

" }, { "textRaw": "`href` {string}", "type": "string", "name": "href", "desc": "

Gets and sets the serialized URL.

\n
const myURL = new URL('https://example.org/foo');\nconsole.log(myURL.href);\n// Prints https://example.org/foo\n\nmyURL.href = 'https://example.com/bar';\nconsole.log(myURL.href);\n// Prints https://example.com/bar\n
\n

Getting the value of the href property is equivalent to calling\nurl.toString().

\n

Setting the value of this property to a new value is equivalent to creating a\nnew URL object using new URL(value). Each of the URL\nobject's properties will be modified.

\n

If the value assigned to the href property is not a valid URL, a TypeError\nwill be thrown.

" }, { "textRaw": "`origin` {string}", "type": "string", "name": "origin", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33325", "description": "The scheme \"gopher\" is no longer special and `url.origin` now returns `'null'` for it." } ] }, "desc": "

Gets the read-only serialization of the URL's origin.

\n
const myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n// Prints https://example.org\n
\n
const idnURL = new URL('https://測試');\nconsole.log(idnURL.origin);\n// Prints https://xn--g6w251d\n\nconsole.log(idnURL.hostname);\n// Prints xn--g6w251d\n
" }, { "textRaw": "`password` {string}", "type": "string", "name": "password", "desc": "

Gets and sets the password portion of the URL.

\n
const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.password);\n// Prints xyz\n\nmyURL.password = '123';\nconsole.log(myURL.href);\n// Prints https://abc:123@example.com\n
\n

Invalid URL characters included in the value assigned to the password property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

" }, { "textRaw": "`pathname` {string}", "type": "string", "name": "pathname", "desc": "

Gets and sets the path portion of the URL.

\n
const myURL = new URL('https://example.org/abc/xyz?123');\nconsole.log(myURL.pathname);\n// Prints /abc/xyz\n\nmyURL.pathname = '/abcdef';\nconsole.log(myURL.href);\n// Prints https://example.org/abcdef?123\n
\n

Invalid URL characters included in the value assigned to the pathname\nproperty are percent-encoded. The selection of which characters\nto percent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

" }, { "textRaw": "`port` {string}", "type": "string", "name": "port", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33325", "description": "The scheme \"gopher\" is no longer special." } ] }, "desc": "

Gets and sets the port portion of the URL.

\n

The port value may be a number or a string containing a number in the range\n0 to 65535 (inclusive). Setting the value to the default port of the\nURL objects given protocol will result in the port value becoming\nthe empty string ('').

\n

The port value can be an empty string in which case the port depends on\nthe protocol/scheme:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
protocolport
\"ftp\"21
\"file\"
\"http\"80
\"https\"443
\"ws\"80
\"wss\"443
\n

Upon assigning a value to the port, the value will first be converted to a\nstring using .toString().

\n

If that string is invalid but it begins with a number, the leading number is\nassigned to port.\nIf the number lies outside the range denoted above, it is ignored.

\n
const myURL = new URL('https://example.org:8888');\nconsole.log(myURL.port);\n// Prints 8888\n\n// Default ports are automatically transformed to the empty string\n// (HTTPS protocol's default port is 443)\nmyURL.port = '443';\nconsole.log(myURL.port);\n// Prints the empty string\nconsole.log(myURL.href);\n// Prints https://example.org/\n\nmyURL.port = 1234;\nconsole.log(myURL.port);\n// Prints 1234\nconsole.log(myURL.href);\n// Prints https://example.org:1234/\n\n// Completely invalid port strings are ignored\nmyURL.port = 'abcd';\nconsole.log(myURL.port);\n// Prints 1234\n\n// Leading numbers are treated as a port number\nmyURL.port = '5678abcd';\nconsole.log(myURL.port);\n// Prints 5678\n\n// Non-integers are truncated\nmyURL.port = 1234.5678;\nconsole.log(myURL.port);\n// Prints 1234\n\n// Out-of-range numbers which are not represented in scientific notation\n// will be ignored.\nmyURL.port = 1e10; // 10000000000, will be range-checked as described below\nconsole.log(myURL.port);\n// Prints 1234\n
\n

Numbers which contain a decimal point,\nsuch as floating-point numbers or numbers in scientific notation,\nare not an exception to this rule.\nLeading numbers up to the decimal point will be set as the URL's port,\nassuming they are valid:

\n
myURL.port = 4.567e21;\nconsole.log(myURL.port);\n// Prints 4 (because it is the leading number in the string '4.567e21')\n
" }, { "textRaw": "`protocol` {string}", "type": "string", "name": "protocol", "desc": "

Gets and sets the protocol portion of the URL.

\n
const myURL = new URL('https://example.org');\nconsole.log(myURL.protocol);\n// Prints https:\n\nmyURL.protocol = 'ftp';\nconsole.log(myURL.href);\n// Prints ftp://example.org/\n
\n

Invalid URL protocol values assigned to the protocol property are ignored.

", "modules": [ { "textRaw": "Special schemes", "name": "special_schemes", "meta": { "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33325", "description": "The scheme \"gopher\" is no longer special." } ] }, "desc": "

The WHATWG URL Standard considers a handful of URL protocol schemes to be\nspecial in terms of how they are parsed and serialized. When a URL is\nparsed using one of these special protocols, the url.protocol property\nmay be changed to another special protocol but cannot be changed to a\nnon-special protocol, and vice versa.

\n

For instance, changing from http to https works:

\n
const u = new URL('http://example.org');\nu.protocol = 'https';\nconsole.log(u.href);\n// https://example.org\n
\n

However, changing from http to a hypothetical fish protocol does not\nbecause the new protocol is not special.

\n
const u = new URL('http://example.org');\nu.protocol = 'fish';\nconsole.log(u.href);\n// http://example.org\n
\n

Likewise, changing from a non-special protocol to a special protocol is also\nnot permitted:

\n
const u = new URL('fish://example.org');\nu.protocol = 'http';\nconsole.log(u.href);\n// fish://example.org\n
\n

According to the WHATWG URL Standard, special protocol schemes are ftp,\nfile, http, https, ws, and wss.

", "type": "module", "displayName": "Special schemes" } ] }, { "textRaw": "`search` {string}", "type": "string", "name": "search", "desc": "

Gets and sets the serialized query portion of the URL.

\n
const myURL = new URL('https://example.org/abc?123');\nconsole.log(myURL.search);\n// Prints ?123\n\nmyURL.search = 'abc=xyz';\nconsole.log(myURL.href);\n// Prints https://example.org/abc?abc=xyz\n
\n

Any invalid URL characters appearing in the value assigned the search\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

" }, { "textRaw": "`searchParams` {URLSearchParams}", "type": "URLSearchParams", "name": "searchParams", "desc": "

Gets the URLSearchParams object representing the query parameters of the\nURL. This property is read-only but the URLSearchParams object it provides\ncan be used to mutate the URL instance; to replace the entirety of query\nparameters of the URL, use the url.search setter. See\nURLSearchParams documentation for details.

\n

Use care when using .searchParams to modify the URL because,\nper the WHATWG specification, the URLSearchParams object uses\ndifferent rules to determine which characters to percent-encode. For\ninstance, the URL object will not percent encode the ASCII tilde (~)\ncharacter, while URLSearchParams will always encode it:

\n
const myUrl = new URL('https://example.org/abc?foo=~bar');\n\nconsole.log(myUrl.search);  // prints ?foo=~bar\n\n// Modify the URL via searchParams...\nmyUrl.searchParams.sort();\n\nconsole.log(myUrl.search);  // prints ?foo=%7Ebar\n
" }, { "textRaw": "`username` {string}", "type": "string", "name": "username", "desc": "

Gets and sets the username portion of the URL.

\n
const myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.username);\n// Prints abc\n\nmyURL.username = '123';\nconsole.log(myURL.href);\n// Prints https://123:xyz@example.com/\n
\n

Any invalid URL characters appearing in the value assigned the username\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

" } ], "methods": [ { "textRaw": "`url.toString()`", "type": "method", "name": "toString", "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

The toString() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and url.toJSON().

" }, { "textRaw": "`url.toJSON()`", "type": "method", "name": "toJSON", "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

The toJSON() method on the URL object returns the serialized URL. The\nvalue returned is equivalent to that of url.href and\nurl.toString().

\n

This method is automatically called when an URL object is serialized\nwith JSON.stringify().

\n
const myURLs = [\n  new URL('https://www.example.com'),\n  new URL('https://test.example.org'),\n];\nconsole.log(JSON.stringify(myURLs));\n// Prints [\"https://www.example.com/\",\"https://test.example.org/\"]\n
" }, { "textRaw": "`URL.createObjectURL(blob)`", "type": "method", "name": "createObjectURL", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`blob` {Blob}", "name": "blob", "type": "Blob" } ] } ], "desc": "

Creates a 'blob:nodedata:...' URL string that represents the given <Blob>\nobject and can be used to retrieve the Blob later.

\n
const {\n  Blob,\n  resolveObjectURL,\n} = require('buffer');\n\nconst blob = new Blob(['hello']);\nconst id = URL.createObjectURL(blob);\n\n// later...\n\nconst otherBlob = resolveObjectURL(id);\nconsole.log(otherBlob.size);\n
\n

The data stored by the registered <Blob> will be retained in memory until\nURL.revokeObjectURL() is called to remove it.

\n

Blob objects are registered within the current thread. If using Worker\nThreads, Blob objects registered within one Worker will not be available\nto other workers or the main thread.

" }, { "textRaw": "`URL.revokeObjectURL(id)`", "type": "method", "name": "revokeObjectURL", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`id` {string} A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.", "name": "id", "type": "string", "desc": "A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`." } ] } ], "desc": "

Removes the stored <Blob> identified by the given ID.

" } ], "signatures": [ { "params": [ { "textRaw": "`input` {string} The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored.", "name": "input", "type": "string", "desc": "The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored." }, { "textRaw": "`base` {string|URL} The base URL to resolve against if the `input` is not absolute.", "name": "base", "type": "string|URL", "desc": "The base URL to resolve against if the `input` is not absolute." } ], "desc": "

Creates a new URL object by parsing the input relative to the base. If\nbase is passed as a string, it will be parsed equivalent to new URL(base).

\n
const myURL = new URL('/foo', 'https://example.org/');\n// https://example.org/foo\n
\n

The URL constructor is accessible as a property on the global object.\nIt can also be imported from the built-in url module:

\n
import { URL } from 'url';\nconsole.log(URL === globalThis.URL); // Prints 'true'.\n
\n
console.log(URL === require('url').URL); // Prints 'true'.\n
\n

A TypeError will be thrown if the input or base are not valid URLs. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:

\n
const myURL = new URL({ toString: () => 'https://example.org/' });\n// https://example.org/\n
\n

Unicode characters appearing within the host name of input will be\nautomatically converted to ASCII using the Punycode algorithm.

\n
const myURL = new URL('https://測試');\n// https://xn--g6w251d/\n
\n

This feature is only available if the node executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.

\n

In cases where it is not known in advance if input is an absolute URL\nand a base is provided, it is advised to validate that the origin of\nthe URL object is what is expected.

\n
let myURL = new URL('http://Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https://Example.com/', 'https://example.org/');\n// https://example.com/\n\nmyURL = new URL('foo://Example.com/', 'https://example.org/');\n// foo://Example.com/\n\nmyURL = new URL('http:Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https:Example.com/', 'https://example.org/');\n// https://example.org/Example.com/\n\nmyURL = new URL('foo:Example.com/', 'https://example.org/');\n// foo:Example.com/\n
" } ] }, { "textRaw": "Class: `URLSearchParams`", "type": "class", "name": "URLSearchParams", "meta": { "added": [ "v7.5.0", "v6.13.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18281", "description": "The class is now available on the global object." } ] }, "desc": "

The URLSearchParams API provides read and write access to the query of a\nURL. The URLSearchParams class can also be used standalone with one of the\nfour following constructors.\nThe URLSearchParams class is also available on the global object.

\n

The WHATWG URLSearchParams interface and the querystring module have\nsimilar purpose, but the purpose of the querystring module is more\ngeneral, as it allows the customization of delimiter characters (& and =).\nOn the other hand, this API is designed purely for URL query strings.

\n
const myURL = new URL('https://example.org/?abc=123');\nconsole.log(myURL.searchParams.get('abc'));\n// Prints 123\n\nmyURL.searchParams.append('abc', 'xyz');\nconsole.log(myURL.href);\n// Prints https://example.org/?abc=123&abc=xyz\n\nmyURL.searchParams.delete('abc');\nmyURL.searchParams.set('a', 'b');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\n\nconst newSearchParams = new URLSearchParams(myURL.searchParams);\n// The above is equivalent to\n// const newSearchParams = new URLSearchParams(myURL.search);\n\nnewSearchParams.append('a', 'c');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\nconsole.log(newSearchParams.toString());\n// Prints a=b&a=c\n\n// newSearchParams.toString() is implicitly called\nmyURL.search = newSearchParams;\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\nnewSearchParams.delete('a');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\n
", "methods": [ { "textRaw": "`urlSearchParams.append(name, value)`", "type": "method", "name": "append", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {string}", "name": "value", "type": "string" } ] } ], "desc": "

Append a new name-value pair to the query string.

" }, { "textRaw": "`urlSearchParams.delete(name)`", "type": "method", "name": "delete", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Remove all name-value pairs whose name is name.

" }, { "textRaw": "`urlSearchParams.entries()`", "type": "method", "name": "entries", "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Returns an ES6 Iterator over each of the name-value pairs in the query.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

\n

Alias for urlSearchParams[@@iterator]().

" }, { "textRaw": "`urlSearchParams.forEach(fn[, thisArg])`", "type": "method", "name": "forEach", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} Invoked for each name-value pair in the query", "name": "fn", "type": "Function", "desc": "Invoked for each name-value pair in the query" }, { "textRaw": "`thisArg` {Object} To be used as `this` value for when `fn` is called", "name": "thisArg", "type": "Object", "desc": "To be used as `this` value for when `fn` is called" } ] } ], "desc": "

Iterates over each name-value pair in the query and invokes the given function.

\n
const myURL = new URL('https://example.org/?a=b&c=d');\nmyURL.searchParams.forEach((value, name, searchParams) => {\n  console.log(name, value, myURL.searchParams === searchParams);\n});\n// Prints:\n//   a b true\n//   c d true\n
" }, { "textRaw": "`urlSearchParams.get(name)`", "type": "method", "name": "get", "signatures": [ { "return": { "textRaw": "Returns: {string} or `null` if there is no name-value pair with the given `name`.", "name": "return", "type": "string", "desc": "or `null` if there is no name-value pair with the given `name`." }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns the value of the first name-value pair whose name is name. If there\nare no such pairs, null is returned.

" }, { "textRaw": "`urlSearchParams.getAll(name)`", "type": "method", "name": "getAll", "signatures": [ { "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns the values of all name-value pairs whose name is name. If there are\nno such pairs, an empty array is returned.

" }, { "textRaw": "`urlSearchParams.has(name)`", "type": "method", "name": "has", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Returns true if there is at least one name-value pair whose name is name.

" }, { "textRaw": "`urlSearchParams.keys()`", "type": "method", "name": "keys", "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Returns an ES6 Iterator over the names of each name-value pair.

\n
const params = new URLSearchParams('foo=bar&foo=baz');\nfor (const name of params.keys()) {\n  console.log(name);\n}\n// Prints:\n//   foo\n//   foo\n
" }, { "textRaw": "`urlSearchParams.set(name, value)`", "type": "method", "name": "set", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {string}", "name": "value", "type": "string" } ] } ], "desc": "

Sets the value in the URLSearchParams object associated with name to\nvalue. If there are any pre-existing name-value pairs whose names are name,\nset the first such pair's value to value and remove all others. If not,\nappend the name-value pair to the query string.

\n
const params = new URLSearchParams();\nparams.append('foo', 'bar');\nparams.append('foo', 'baz');\nparams.append('abc', 'def');\nconsole.log(params.toString());\n// Prints foo=bar&foo=baz&abc=def\n\nparams.set('foo', 'def');\nparams.set('xyz', 'opq');\nconsole.log(params.toString());\n// Prints foo=def&abc=def&xyz=opq\n
" }, { "textRaw": "`urlSearchParams.sort()`", "type": "method", "name": "sort", "meta": { "added": [ "v7.7.0", "v6.13.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sort all existing name-value pairs in-place by their names. Sorting is done\nwith a stable sorting algorithm, so relative order between name-value pairs\nwith the same name is preserved.

\n

This method can be used, in particular, to increase cache hits.

\n
const params = new URLSearchParams('query[]=abc&type=search&query[]=123');\nparams.sort();\nconsole.log(params.toString());\n// Prints query%5B%5D=abc&query%5B%5D=123&type=search\n
" }, { "textRaw": "`urlSearchParams.toString()`", "type": "method", "name": "toString", "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Returns the search parameters serialized as a string, with characters\npercent-encoded where necessary.

" }, { "textRaw": "`urlSearchParams.values()`", "type": "method", "name": "values", "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Returns an ES6 Iterator over the values of each name-value pair.

" }, { "textRaw": "`urlSearchParams[Symbol.iterator]()`", "type": "method", "name": "[Symbol.iterator]", "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "

Returns an ES6 Iterator over each of the name-value pairs in the query string.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name, the second item of the Array is the value.

\n

Alias for urlSearchParams.entries().

\n
const params = new URLSearchParams('foo=bar&xyz=baz');\nfor (const [name, value] of params) {\n  console.log(name, value);\n}\n// Prints:\n//   foo bar\n//   xyz baz\n
" } ], "signatures": [ { "params": [], "desc": "

Instantiate a new empty URLSearchParams object.

" }, { "params": [ { "textRaw": "`string` {string} A query string", "name": "string", "type": "string", "desc": "A query string" } ], "desc": "

Parse the string as a query string, and use it to instantiate a new\nURLSearchParams object. A leading '?', if present, is ignored.

\n
let params;\n\nparams = new URLSearchParams('user=abc&query=xyz');\nconsole.log(params.get('user'));\n// Prints 'abc'\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\nparams = new URLSearchParams('?user=abc&query=xyz');\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n
" }, { "params": [ { "textRaw": "`obj` {Object} An object representing a collection of key-value pairs", "name": "obj", "type": "Object", "desc": "An object representing a collection of key-value pairs" } ], "desc": "

Instantiate a new URLSearchParams object with a query hash map. The key and\nvalue of each property of obj are always coerced to strings.

\n

Unlike querystring module, duplicate keys in the form of array values are\nnot allowed. Arrays are stringified using array.toString(), which simply\njoins all array elements with commas.

\n
const params = new URLSearchParams({\n  user: 'abc',\n  query: ['first', 'second']\n});\nconsole.log(params.getAll('query'));\n// Prints [ 'first,second' ]\nconsole.log(params.toString());\n// Prints 'user=abc&query=first%2Csecond'\n
" }, { "params": [ { "textRaw": "`iterable` {Iterable} An iterable object whose elements are key-value pairs", "name": "iterable", "type": "Iterable", "desc": "An iterable object whose elements are key-value pairs" } ], "desc": "

Instantiate a new URLSearchParams object with an iterable map in a way that\nis similar to Map's constructor. iterable can be an Array or any\niterable object. That means iterable can be another URLSearchParams, in\nwhich case the constructor will simply create a clone of the provided\nURLSearchParams. Elements of iterable are key-value pairs, and can\nthemselves be any iterable object.

\n

Duplicate keys are allowed.

\n
let params;\n\n// Using an array\nparams = new URLSearchParams([\n  ['user', 'abc'],\n  ['query', 'first'],\n  ['query', 'second'],\n]);\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Using a Map object\nconst map = new Map();\nmap.set('user', 'abc');\nmap.set('query', 'xyz');\nparams = new URLSearchParams(map);\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\n// Using a generator function\nfunction* getQueryPairs() {\n  yield ['user', 'abc'];\n  yield ['query', 'first'];\n  yield ['query', 'second'];\n}\nparams = new URLSearchParams(getQueryPairs());\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Each key-value pair must have exactly two elements\nnew URLSearchParams([\n  ['user', 'abc', 'error'],\n]);\n// Throws TypeError [ERR_INVALID_TUPLE]:\n//        Each query pair must be an iterable [name, value] tuple\n
" } ] } ], "methods": [ { "textRaw": "`url.domainToASCII(domain)`", "type": "method", "name": "domainToASCII", "meta": { "added": [ "v7.4.0", "v6.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`domain` {string}", "name": "domain", "type": "string" } ] } ], "desc": "

Returns the Punycode ASCII serialization of the domain. If domain is an\ninvalid domain, the empty string is returned.

\n

It performs the inverse operation to url.domainToUnicode().

\n

This feature is only available if the node executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.

\n
import url from 'url';\n\nconsole.log(url.domainToASCII('español.com'));\n// Prints xn--espaol-zwa.com\nconsole.log(url.domainToASCII('中文.com'));\n// Prints xn--fiq228c.com\nconsole.log(url.domainToASCII('xn--iñvalid.com'));\n// Prints an empty string\n
\n
const url = require('url');\n\nconsole.log(url.domainToASCII('español.com'));\n// Prints xn--espaol-zwa.com\nconsole.log(url.domainToASCII('中文.com'));\n// Prints xn--fiq228c.com\nconsole.log(url.domainToASCII('xn--iñvalid.com'));\n// Prints an empty string\n
" }, { "textRaw": "`url.domainToUnicode(domain)`", "type": "method", "name": "domainToUnicode", "meta": { "added": [ "v7.4.0", "v6.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`domain` {string}", "name": "domain", "type": "string" } ] } ], "desc": "

Returns the Unicode serialization of the domain. If domain is an invalid\ndomain, the empty string is returned.

\n

It performs the inverse operation to url.domainToASCII().

\n

This feature is only available if the node executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.

\n
import url from 'url';\n\nconsole.log(url.domainToUnicode('xn--espaol-zwa.com'));\n// Prints español.com\nconsole.log(url.domainToUnicode('xn--fiq228c.com'));\n// Prints 中文.com\nconsole.log(url.domainToUnicode('xn--iñvalid.com'));\n// Prints an empty string\n
\n
const url = require('url');\n\nconsole.log(url.domainToUnicode('xn--espaol-zwa.com'));\n// Prints español.com\nconsole.log(url.domainToUnicode('xn--fiq228c.com'));\n// Prints 中文.com\nconsole.log(url.domainToUnicode('xn--iñvalid.com'));\n// Prints an empty string\n
" }, { "textRaw": "`url.fileURLToPath(url)`", "type": "method", "name": "fileURLToPath", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string} The fully-resolved platform-specific Node.js file path.", "name": "return", "type": "string", "desc": "The fully-resolved platform-specific Node.js file path." }, "params": [ { "textRaw": "`url` {URL | string} The file URL string or URL object to convert to a path.", "name": "url", "type": "URL | string", "desc": "The file URL string or URL object to convert to a path." } ] } ], "desc": "

This function ensures the correct decodings of percent-encoded characters as\nwell as ensuring a cross-platform valid absolute path string.

\n
import { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\n\nnew URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/');         // Correct:   C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt');       // Correct:   \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname;   // Incorrect: /hello%20world\nfileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)\n
\n
const { fileURLToPath } = require('url');\nnew URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/');         // Correct:   C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt');       // Correct:   \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname;   // Incorrect: /hello%20world\nfileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)\n
" }, { "textRaw": "`url.format(URL[, options])`", "type": "method", "name": "format", "meta": { "added": [ "v7.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`URL` {URL} A [WHATWG URL][] object", "name": "URL", "type": "URL", "desc": "A [WHATWG URL][] object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`auth` {boolean} `true` if the serialized URL string should include the username and password, `false` otherwise. **Default:** `true`.", "name": "auth", "type": "boolean", "default": "`true`", "desc": "`true` if the serialized URL string should include the username and password, `false` otherwise." }, { "textRaw": "`fragment` {boolean} `true` if the serialized URL string should include the fragment, `false` otherwise. **Default:** `true`.", "name": "fragment", "type": "boolean", "default": "`true`", "desc": "`true` if the serialized URL string should include the fragment, `false` otherwise." }, { "textRaw": "`search` {boolean} `true` if the serialized URL string should include the search query, `false` otherwise. **Default:** `true`.", "name": "search", "type": "boolean", "default": "`true`", "desc": "`true` if the serialized URL string should include the search query, `false` otherwise." }, { "textRaw": "`unicode` {boolean} `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded. **Default:** `false`.", "name": "unicode", "type": "boolean", "default": "`false`", "desc": "`true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded." } ] } ] } ], "desc": "

Returns a customizable serialization of a URL String representation of a\nWHATWG URL object.

\n

The URL object has both a toString() method and href property that return\nstring serializations of the URL. These are not, however, customizable in\nany way. The url.format(URL[, options]) method allows for basic customization\nof the output.

\n
import url from 'url';\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
\n
const url = require('url');\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
" }, { "textRaw": "`url.pathToFileURL(path)`", "type": "method", "name": "pathToFileURL", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {URL} The file URL object.", "name": "return", "type": "URL", "desc": "The file URL object." }, "params": [ { "textRaw": "`path` {string} The path to convert to a File URL.", "name": "path", "type": "string", "desc": "The path to convert to a File URL." } ] } ], "desc": "

This function ensures that path is resolved absolutely, and that the URL\ncontrol characters are correctly encoded when converting into a File URL.

\n
import { pathToFileURL } from 'url';\n\nnew URL('/foo#1', 'file:');           // Incorrect: file:///foo#1\npathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)\n
\n
const { pathToFileURL } = require('url');\nnew URL(__filename);                  // Incorrect: throws (POSIX)\nnew URL(__filename);                  // Incorrect: C:\\... (Windows)\npathToFileURL(__filename);            // Correct:   file:///... (POSIX)\npathToFileURL(__filename);            // Correct:   file:///C:/... (Windows)\n\nnew URL('/foo#1', 'file:');           // Incorrect: file:///foo#1\npathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)\n
" }, { "textRaw": "`url.urlToHttpOptions(url)`", "type": "method", "name": "urlToHttpOptions", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} Options object", "name": "return", "type": "Object", "desc": "Options object", "options": [ { "textRaw": "`protocol` {string} Protocol to use.", "name": "protocol", "type": "string", "desc": "Protocol to use." }, { "textRaw": "`hostname` {string} A domain name or IP address of the server to issue the request to.", "name": "hostname", "type": "string", "desc": "A domain name or IP address of the server to issue the request to." }, { "textRaw": "`hash` {string} The fragment portion of the URL.", "name": "hash", "type": "string", "desc": "The fragment portion of the URL." }, { "textRaw": "`search` {string} The serialized query portion of the URL.", "name": "search", "type": "string", "desc": "The serialized query portion of the URL." }, { "textRaw": "`pathname` {string} The path portion of the URL.", "name": "pathname", "type": "string", "desc": "The path portion of the URL." }, { "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.", "name": "path", "type": "string", "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": "`href` {string} The serialized URL.", "name": "href", "type": "string", "desc": "The serialized URL." }, { "textRaw": "`port` {number} Port of remote server.", "name": "port", "type": "number", "desc": "Port of remote server." }, { "textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.", "name": "auth", "type": "string", "desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header." } ] }, "params": [ { "textRaw": "`url` {URL} The [WHATWG URL][] object to convert to an options object.", "name": "url", "type": "URL", "desc": "The [WHATWG URL][] object to convert to an options object." } ] } ], "desc": "

This utility function converts a URL object into an ordinary options object as\nexpected by the http.request() and https.request() APIs.

\n
import { urlToHttpOptions } from 'url';\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(urlToHttpOptions(myURL));\n/**\n{\n  protocol: 'https:',\n  hostname: 'xn--g6w251d',\n  hash: '#foo',\n  search: '?abc',\n  pathname: '/',\n  path: '/?abc',\n  href: 'https://a:b@xn--g6w251d/?abc#foo',\n  auth: 'a:b'\n}\n*/\n
\n
const { urlToHttpOptions } = require('url');\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(urlToHttpOptions(myUrl));\n/**\n{\n  protocol: 'https:',\n  hostname: 'xn--g6w251d',\n  hash: '#foo',\n  search: '?abc',\n  pathname: '/',\n  path: '/?abc',\n  href: 'https://a:b@xn--g6w251d/?abc#foo',\n  auth: 'a:b'\n}\n*/\n
" } ], "type": "module", "displayName": "The WHATWG URL API" }, { "textRaw": "Legacy URL API", "name": "legacy_url_api", "meta": { "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "This API is deprecated." } ] }, "stability": 3, "stabilityText": "Legacy: Use the WHATWG URL API instead.", "modules": [ { "textRaw": "Legacy `urlObject`", "name": "legacy_`urlobject`", "meta": { "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." } ] }, "stability": 3, "stabilityText": "Legacy: Use the WHATWG URL API instead.", "desc": "

The legacy urlObject (require('url').Url or import { Url } from 'url') is\ncreated and returned by the url.parse() function.

", "properties": [ { "textRaw": "`urlObject.auth`", "name": "auth", "desc": "

The auth property is the username and password portion of the URL, also\nreferred to as userinfo. This string subset follows the protocol and\ndouble slashes (if present) and precedes the host component, delimited by @.\nThe string is either the username, or it is the username and password separated\nby :.

\n

For example: 'user:pass'.

" }, { "textRaw": "`urlObject.hash`", "name": "hash", "desc": "

The hash property is the fragment identifier portion of the URL including the\nleading # character.

\n

For example: '#hash'.

" }, { "textRaw": "`urlObject.host`", "name": "host", "desc": "

The host property is the full lower-cased host portion of the URL, including\nthe port if specified.

\n

For example: 'sub.example.com:8080'.

" }, { "textRaw": "`urlObject.hostname`", "name": "hostname", "desc": "

The hostname property is the lower-cased host name portion of the host\ncomponent without the port included.

\n

For example: 'sub.example.com'.

" }, { "textRaw": "`urlObject.href`", "name": "href", "desc": "

The href property is the full URL string that was parsed with both the\nprotocol and host components converted to lower-case.

\n

For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

" }, { "textRaw": "`urlObject.path`", "name": "path", "desc": "

The path property is a concatenation of the pathname and search\ncomponents.

\n

For example: '/p/a/t/h?query=string'.

\n

No decoding of the path is performed.

" }, { "textRaw": "`urlObject.pathname`", "name": "pathname", "desc": "

The pathname property consists of the entire path section of the URL. This\nis everything following the host (including the port) and before the start\nof the query or hash components, delimited by either the ASCII question\nmark (?) or hash (#) characters.

\n

For example: '/p/a/t/h'.

\n

No decoding of the path string is performed.

" }, { "textRaw": "`urlObject.port`", "name": "port", "desc": "

The port property is the numeric port portion of the host component.

\n

For example: '8080'.

" }, { "textRaw": "`urlObject.protocol`", "name": "protocol", "desc": "

The protocol property identifies the URL's lower-cased protocol scheme.

\n

For example: 'http:'.

" }, { "textRaw": "`urlObject.query`", "name": "query", "desc": "

The query property is either the query string without the leading ASCII\nquestion mark (?), or an object returned by the querystring module's\nparse() method. Whether the query property is a string or object is\ndetermined by the parseQueryString argument passed to url.parse().

\n

For example: 'query=string' or {'query': 'string'}.

\n

If returned as a string, no decoding of the query string is performed. If\nreturned as an object, both keys and values are decoded.

" }, { "textRaw": "`urlObject.search`", "name": "search", "desc": "

The search property consists of the entire \"query string\" portion of the\nURL, including the leading ASCII question mark (?) character.

\n

For example: '?query=string'.

\n

No decoding of the query string is performed.

" }, { "textRaw": "`urlObject.slashes`", "name": "slashes", "desc": "

The slashes property is a boolean with a value of true if two ASCII\nforward-slash characters (/) are required following the colon in the\nprotocol.

" } ], "type": "module", "displayName": "Legacy `urlObject`" } ], "methods": [ { "textRaw": "`url.format(urlObject)`", "type": "method", "name": "format", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." }, { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/7234", "description": "URLs with a `file:` scheme will now always use the correct number of slashes regardless of `slashes` option. A falsy `slashes` option with no protocol is now also respected at all times." } ] }, "stability": 3, "stabilityText": "Legacy: Use the WHATWG URL API instead.", "signatures": [ { "params": [ { "textRaw": "`urlObject` {Object|string} A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`.", "name": "urlObject", "type": "Object|string", "desc": "A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`." } ] } ], "desc": "

The url.format() method returns a formatted URL string derived from\nurlObject.

\n
const url = require('url');\nurl.format({\n  protocol: 'https',\n  hostname: 'example.com',\n  pathname: '/some/path',\n  query: {\n    page: 1,\n    format: 'json'\n  }\n});\n\n// => 'https://example.com/some/path?page=1&format=json'\n
\n

If urlObject is not an object or a string, url.format() will throw a\nTypeError.

\n

The formatting process operates as follows:

\n
    \n
  • A new empty string result is created.
  • \n
  • If urlObject.protocol is a string, it is appended as-is to result.
  • \n
  • Otherwise, if urlObject.protocol is not undefined and is not a string, an\nError is thrown.
  • \n
  • For all string values of urlObject.protocol that do not end with an ASCII\ncolon (:) character, the literal string : will be appended to result.
  • \n
  • If either of the following conditions is true, then the literal string //\nwill be appended to result:\n
      \n
    • urlObject.slashes property is true;
    • \n
    • urlObject.protocol begins with http, https, ftp, gopher, or\nfile;
    • \n
    \n
  • \n
  • If the value of the urlObject.auth property is truthy, and either\nurlObject.host or urlObject.hostname are not undefined, the value of\nurlObject.auth will be coerced into a string and appended to result\nfollowed by the literal string @.
  • \n
  • If the urlObject.host property is undefined then:\n
      \n
    • If the urlObject.hostname is a string, it is appended to result.
    • \n
    • Otherwise, if urlObject.hostname is not undefined and is not a string,\nan Error is thrown.
    • \n
    • If the urlObject.port property value is truthy, and urlObject.hostname\nis not undefined:\n
        \n
      • The literal string : is appended to result, and
      • \n
      • The value of urlObject.port is coerced to a string and appended to\nresult.
      • \n
      \n
    • \n
    \n
  • \n
  • Otherwise, if the urlObject.host property value is truthy, the value of\nurlObject.host is coerced to a string and appended to result.
  • \n
  • If the urlObject.pathname property is a string that is not an empty string:\n
      \n
    • If the urlObject.pathname does not start with an ASCII forward slash\n(/), then the literal string '/' is appended to result.
    • \n
    • The value of urlObject.pathname is appended to result.
    • \n
    \n
  • \n
  • Otherwise, if urlObject.pathname is not undefined and is not a string, an\nError is thrown.
  • \n
  • If the urlObject.search property is undefined and if the urlObject.query\nproperty is an Object, the literal string ? is appended to result\nfollowed by the output of calling the querystring module's stringify()\nmethod passing the value of urlObject.query.
  • \n
  • Otherwise, if urlObject.search is a string:\n
      \n
    • If the value of urlObject.search does not start with the ASCII question\nmark (?) character, the literal string ? is appended to result.
    • \n
    • The value of urlObject.search is appended to result.
    • \n
    \n
  • \n
  • Otherwise, if urlObject.search is not undefined and is not a string, an\nError is thrown.
  • \n
  • If the urlObject.hash property is a string:\n
      \n
    • If the value of urlObject.hash does not start with the ASCII hash (#)\ncharacter, the literal string # is appended to result.
    • \n
    • The value of urlObject.hash is appended to result.
    • \n
    \n
  • \n
  • Otherwise, if the urlObject.hash property is not undefined and is not a\nstring, an Error is thrown.
  • \n
  • result is returned.
  • \n
" }, { "textRaw": "`url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`", "type": "method", "name": "parse", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.14.0", "pr-url": "https://github.com/nodejs/node/pull/26941", "description": "The `pathname` property on the returned URL object is now `/` when there is no path and the protocol scheme is `ws:` or `wss:`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." }, { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/13606", "description": "The `search` property on the returned URL object is now `null` when no query string is present." } ] }, "stability": 3, "stabilityText": "Legacy: Use the WHATWG URL API instead.", "signatures": [ { "params": [ { "textRaw": "`urlString` {string} The URL string to parse.", "name": "urlString", "type": "string", "desc": "The URL string to parse." }, { "textRaw": "`parseQueryString` {boolean} If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string. **Default:** `false`.", "name": "parseQueryString", "type": "boolean", "default": "`false`", "desc": "If `true`, the `query` property will always be set to an object returned by the [`querystring`][] module's `parse()` method. If `false`, the `query` property on the returned URL object will be an unparsed, undecoded string." }, { "textRaw": "`slashesDenoteHost` {boolean} If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. **Default:** `false`.", "name": "slashesDenoteHost", "type": "boolean", "default": "`false`", "desc": "If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`." } ] } ], "desc": "

The url.parse() method takes a URL string, parses it, and returns a URL\nobject.

\n

A TypeError is thrown if urlString is not a string.

\n

A URIError is thrown if the auth property is present but cannot be decoded.

\n

Use of the legacy url.parse() method is discouraged. Users should\nuse the WHATWG URL API. Because the url.parse() method uses a\nlenient, non-standard algorithm for parsing URL strings, security\nissues can be introduced. Specifically, issues with host name spoofing and\nincorrect handling of usernames and passwords have been identified.

" }, { "textRaw": "`url.resolve(from, to)`", "type": "method", "name": "resolve", "meta": { "added": [ "v0.1.25" ], "changes": [ { "version": "v15.13.0", "pr-url": "https://github.com/nodejs/node/pull/37784", "description": "Deprecation revoked. Status changed to \"Legacy\"." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22715", "description": "The Legacy URL API is deprecated. Use the WHATWG URL API." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8215", "description": "The `auth` fields are now kept intact when `from` and `to` refer to the same host." }, { "version": [ "v6.5.0", "v4.6.2" ], "pr-url": "https://github.com/nodejs/node/pull/8214", "description": "The `port` field is copied correctly now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/1480", "description": "The `auth` fields is cleared now the `to` parameter contains a hostname." } ] }, "stability": 3, "stabilityText": "Legacy: Use the WHATWG URL API instead.", "signatures": [ { "params": [ { "textRaw": "`from` {string} The Base URL being resolved against.", "name": "from", "type": "string", "desc": "The Base URL being resolved against." }, { "textRaw": "`to` {string} The HREF URL being resolved.", "name": "to", "type": "string", "desc": "The HREF URL being resolved." } ] } ], "desc": "

The url.resolve() method resolves a target URL relative to a base URL in a\nmanner similar to that of a Web browser resolving an anchor tag HREF.

\n
const url = require('url');\nurl.resolve('/one/two/three', 'four');         // '/one/two/four'\nurl.resolve('http://example.com/', '/one');    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
\n

You can achieve the same result using the WHATWG URL API:

\n
function resolve(from, to) {\n  const resolvedUrl = new URL(to, new URL(from, 'resolve://'));\n  if (resolvedUrl.protocol === 'resolve:') {\n    // `from` is a relative URL.\n    const { pathname, search, hash } = resolvedUrl;\n    return pathname + search + hash;\n  }\n  return resolvedUrl.toString();\n}\n\nresolve('/one/two/three', 'four');         // '/one/two/four'\nresolve('http://example.com/', '/one');    // 'http://example.com/one'\nresolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
\n

" } ], "type": "module", "displayName": "Legacy URL API" }, { "textRaw": "Percent-encoding in URLs", "name": "percent-encoding_in_urls", "desc": "

URLs are permitted to only contain a certain range of characters. Any character\nfalling outside of that range must be encoded. How such characters are encoded,\nand which characters to encode depends entirely on where the character is\nlocated within the structure of the URL.

", "modules": [ { "textRaw": "Legacy API", "name": "legacy_api", "desc": "

Within the Legacy API, spaces (' ') and the following characters will be\nautomatically escaped in the properties of URL objects:

\n
< > \" ` \\r \\n \\t { } | \\ ^ '\n
\n

For example, the ASCII space character (' ') is encoded as %20. The ASCII\nforward slash (/) character is encoded as %3C.

", "type": "module", "displayName": "Legacy API" }, { "textRaw": "WHATWG API", "name": "whatwg_api", "desc": "

The WHATWG URL Standard uses a more selective and fine grained approach to\nselecting encoded characters than that used by the Legacy API.

\n

The WHATWG algorithm defines four \"percent-encode sets\" that describe ranges\nof characters that must be percent-encoded:

\n
    \n
  • \n

    The C0 control percent-encode set includes code points in range U+0000 to\nU+001F (inclusive) and all code points greater than U+007E.

    \n
  • \n
  • \n

    The fragment percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+003C, U+003E, and U+0060.

    \n
  • \n
  • \n

    The path percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,\nU+007B, and U+007D.

    \n
  • \n
  • \n

    The userinfo encode set includes the path percent-encode set and code\npoints U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,\nU+005E, and U+007C.

    \n
  • \n
\n

The userinfo percent-encode set is used exclusively for username and\npasswords encoded within the URL. The path percent-encode set is used for the\npath of most URLs. The fragment percent-encode set is used for URL fragments.\nThe C0 control percent-encode set is used for host and path under certain\nspecific conditions, in addition to all other cases.

\n

When non-ASCII characters appear within a host name, the host name is encoded\nusing the Punycode algorithm. Note, however, that a host name may contain\nboth Punycode encoded and percent-encoded characters:

\n
const myURL = new URL('https://%CF%80.example.com/foo');\nconsole.log(myURL.href);\n// Prints https://xn--1xa.example.com/foo\nconsole.log(myURL.origin);\n// Prints https://xn--1xa.example.com\n
", "type": "module", "displayName": "WHATWG API" } ], "type": "module", "displayName": "Percent-encoding in URLs" } ], "type": "module", "displayName": "URL", "source": "doc/api/url.md" }, { "textRaw": "Util", "name": "util", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/util.js

\n

The util module supports the needs of Node.js internal APIs. Many of the\nutilities are useful for application and module developers as well. To access\nit:

\n
const util = require('util');\n
", "methods": [ { "textRaw": "`util.callbackify(original)`", "type": "method", "name": "callbackify", "meta": { "added": [ "v8.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function} a callback style function", "name": "return", "type": "Function", "desc": "a callback style function" }, "params": [ { "textRaw": "`original` {Function} An `async` function", "name": "original", "type": "Function", "desc": "An `async` function" } ] } ], "desc": "

Takes an async function (or a function that returns a Promise) and returns a\nfunction following the error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument. In the callback, the\nfirst argument will be the rejection reason (or null if the Promise\nresolved), and the second argument will be the resolved value.

\n
const util = require('util');\n\nasync function fn() {\n  return 'hello world';\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  if (err) throw err;\n  console.log(ret);\n});\n
\n

Will print:

\n
hello world\n
\n

The callback is executed asynchronously, and will have a limited stack trace.\nIf the callback throws, the process will emit an 'uncaughtException'\nevent, and if not handled will exit.

\n

Since null has a special meaning as the first argument to a callback, if a\nwrapped function rejects a Promise with a falsy value as a reason, the value\nis wrapped in an Error with the original value stored in a field named\nreason.

\n
function fn() {\n  return Promise.reject(null);\n}\nconst callbackFunction = util.callbackify(fn);\n\ncallbackFunction((err, ret) => {\n  // When the Promise was rejected with `null` it is wrapped with an Error and\n  // the original value is stored in `reason`.\n  err && err.hasOwnProperty('reason') && err.reason === null;  // true\n});\n
" }, { "textRaw": "`util.debuglog(section[, callback])`", "type": "method", "name": "debuglog", "meta": { "added": [ "v0.11.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function} The logging function", "name": "return", "type": "Function", "desc": "The logging function" }, "params": [ { "textRaw": "`section` {string} A string identifying the portion of the application for which the `debuglog` function is being created.", "name": "section", "type": "string", "desc": "A string identifying the portion of the application for which the `debuglog` function is being created." }, { "textRaw": "`callback` {Function} A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.", "name": "callback", "type": "Function", "desc": "A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function." } ] } ], "desc": "

The util.debuglog() method is used to create a function that conditionally\nwrites debug messages to stderr based on the existence of the NODE_DEBUG\nenvironment variable. If the section name appears within the value of that\nenvironment variable, then the returned function operates similar to\nconsole.error(). If not, then the returned function is a no-op.

\n
const util = require('util');\nconst debuglog = util.debuglog('foo');\n\ndebuglog('hello from foo [%d]', 123);\n
\n

If this program is run with NODE_DEBUG=foo in the environment, then\nit will output something like:

\n
FOO 3245: hello from foo [123]\n
\n

where 3245 is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.

\n

The section supports wildcard also:

\n
const util = require('util');\nconst debuglog = util.debuglog('foo-bar');\n\ndebuglog('hi there, it\\'s foo-bar [%d]', 2333);\n
\n

if it is run with NODE_DEBUG=foo* in the environment, then it will output\nsomething like:

\n
FOO-BAR 3257: hi there, it's foo-bar [2333]\n
\n

Multiple comma-separated section names may be specified in the NODE_DEBUG\nenvironment variable: NODE_DEBUG=fs,net,tls.

\n

The optional callback argument can be used to replace the logging function\nwith a different function that doesn't have any initialization or\nunnecessary wrapping.

\n
const util = require('util');\nlet debuglog = util.debuglog('internals', (debug) => {\n  // Replace with a logging function that optimizes out\n  // testing if the section is enabled\n  debuglog = debug;\n});\n
", "modules": [ { "textRaw": "`debuglog().enabled`", "name": "`debuglog().enabled`", "meta": { "added": [ "v14.9.0" ], "changes": [] }, "desc": "\n

The util.debuglog().enabled getter is used to create a test that can be used\nin conditionals based on the existence of the NODE_DEBUG environment variable.\nIf the section name appears within the value of that environment variable,\nthen the returned value will be true. If not, then the returned value will be\nfalse.

\n
const util = require('util');\nconst enabled = util.debuglog('foo').enabled;\nif (enabled) {\n  console.log('hello from foo [%d]', 123);\n}\n
\n

If this program is run with NODE_DEBUG=foo in the environment, then it will\noutput something like:

\n
hello from foo [123]\n
", "type": "module", "displayName": "`debuglog().enabled`" } ] }, { "textRaw": "`util.debug(section)`", "type": "method", "name": "debug", "meta": { "added": [ "v14.9.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Alias for util.debuglog. Usage allows for readability of that doesn't imply\nlogging when only using util.debuglog().enabled.

" }, { "textRaw": "`util.deprecate(fn, msg[, code])`", "type": "method", "name": "deprecate", "meta": { "added": [ "v0.8.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16393", "description": "Deprecation warnings are only emitted once for each code." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Function} The deprecated function wrapped to emit a warning.", "name": "return", "type": "Function", "desc": "The deprecated function wrapped to emit a warning." }, "params": [ { "textRaw": "`fn` {Function} The function that is being deprecated.", "name": "fn", "type": "Function", "desc": "The function that is being deprecated." }, { "textRaw": "`msg` {string} A warning message to display when the deprecated function is invoked.", "name": "msg", "type": "string", "desc": "A warning message to display when the deprecated function is invoked." }, { "textRaw": "`code` {string} A deprecation code. See the [list of deprecated APIs][] for a list of codes.", "name": "code", "type": "string", "desc": "A deprecation code. See the [list of deprecated APIs][] for a list of codes." } ] } ], "desc": "

The util.deprecate() method wraps fn (which may be a function or class) in\nsuch a way that it is marked as deprecated.

\n
const util = require('util');\n\nexports.obsoleteFunction = util.deprecate(() => {\n  // Do something here.\n}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');\n
\n

When called, util.deprecate() will return a function that will emit a\nDeprecationWarning using the 'warning' event. The warning will\nbe emitted and printed to stderr the first time the returned function is\ncalled. After the warning is emitted, the wrapped function is called without\nemitting a warning.

\n

If the same optional code is supplied in multiple calls to util.deprecate(),\nthe warning will be emitted only once for that code.

\n
const util = require('util');\n\nconst fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');\nconst fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');\nfn1(); // Emits a deprecation warning with code DEP0001\nfn2(); // Does not emit a deprecation warning because it has the same code\n
\n

If either the --no-deprecation or --no-warnings command-line flags are\nused, or if the process.noDeprecation property is set to true prior to\nthe first deprecation warning, the util.deprecate() method does nothing.

\n

If the --trace-deprecation or --trace-warnings command-line flags are set,\nor the process.traceDeprecation property is set to true, a warning and a\nstack trace are printed to stderr the first time the deprecated function is\ncalled.

\n

If the --throw-deprecation command-line flag is set, or the\nprocess.throwDeprecation property is set to true, then an exception will be\nthrown when the deprecated function is called.

\n

The --throw-deprecation command-line flag and process.throwDeprecation\nproperty take precedence over --trace-deprecation and\nprocess.traceDeprecation.

" }, { "textRaw": "`util.format(format[, ...args])`", "type": "method", "name": "format", "meta": { "added": [ "v0.5.3" ], "changes": [ { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29606", "description": "The `%c` specifier is ignored now." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23162", "description": "The `format` argument is now only taken as such if it actually contains format specifiers." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/23162", "description": "If the `format` argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/23708", "description": "The `%d`, `%f` and `%i` specifiers now support Symbols properly." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24806", "description": "The `%o` specifier's `depth` has default depth of 4 again." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/17907", "description": "The `%o` specifier's `depth` option will now fall back to the default depth." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22097", "description": "The `%d` and `%i` specifiers now support BigInt." }, { "version": "v8.4.0", "pr-url": "https://github.com/nodejs/node/pull/14558", "description": "The `%o` and `%O` specifiers are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`format` {string} A `printf`-like format string.", "name": "format", "type": "string", "desc": "A `printf`-like format string." } ] } ], "desc": "

The util.format() method returns a formatted string using the first argument\nas a printf-like format string which can contain zero or more format\nspecifiers. Each specifier is replaced with the converted value from the\ncorresponding argument. Supported specifiers are:

\n
    \n
  • %s: String will be used to convert all values except BigInt, Object\nand -0. BigInt values will be represented with an n and Objects that\nhave no user defined toString function are inspected using util.inspect()\nwith options { depth: 0, colors: false, compact: 3 }.
  • \n
  • %d: Number will be used to convert all values except BigInt and\nSymbol.
  • \n
  • %i: parseInt(value, 10) is used for all values except BigInt and\nSymbol.
  • \n
  • %f: parseFloat(value) is used for all values expect Symbol.
  • \n
  • %j: JSON. Replaced with the string '[Circular]' if the argument contains\ncircular references.
  • \n
  • %o: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() with options\n{ showHidden: true, showProxy: true }. This will show the full object\nincluding non-enumerable properties and proxies.
  • \n
  • %O: Object. A string representation of an object with generic JavaScript\nobject formatting. Similar to util.inspect() without options. This will show\nthe full object not including non-enumerable properties and proxies.
  • \n
  • %c: CSS. This specifier is ignored and will skip any CSS passed in.
  • \n
  • %%: single percent sign ('%'). This does not consume an argument.
  • \n
  • Returns: <string> The formatted string
  • \n
\n

If a specifier does not have a corresponding argument, it is not replaced:

\n
util.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n
\n

Values that are not part of the format string are formatted using\nutil.inspect() if their type is not string.

\n

If there are more arguments passed to the util.format() method than the\nnumber of specifiers, the extra arguments are concatenated to the returned\nstring, separated by spaces:

\n
util.format('%s:%s', 'foo', 'bar', 'baz');\n// Returns: 'foo:bar baz'\n
\n

If the first argument does not contain a valid format specifier, util.format()\nreturns a string that is the concatenation of all arguments separated by spaces:

\n
util.format(1, 2, 3);\n// Returns: '1 2 3'\n
\n

If only one argument is passed to util.format(), it is returned as it is\nwithout any formatting:

\n
util.format('%% %s');\n// Returns: '%% %s'\n
\n

util.format() is a synchronous method that is intended as a debugging tool.\nSome input values can have a significant performance overhead that can block the\nevent loop. Use this function with care and never in a hot code path.

" }, { "textRaw": "`util.formatWithOptions(inspectOptions, format[, ...args])`", "type": "method", "name": "formatWithOptions", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`inspectOptions` {Object}", "name": "inspectOptions", "type": "Object" }, { "textRaw": "`format` {string}", "name": "format", "type": "string" } ] } ], "desc": "

This function is identical to util.format(), except in that it takes\nan inspectOptions argument which specifies options that are passed along to\nutil.inspect().

\n
util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });\n// Returns 'See object { foo: 42 }', where `42` is colored as a number\n// when printed to a terminal.\n
" }, { "textRaw": "`util.getSystemErrorName(err)`", "type": "method", "name": "getSystemErrorName", "meta": { "added": [ "v9.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`err` {number}", "name": "err", "type": "number" } ] } ], "desc": "

Returns the string name for a numeric error code that comes from a Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.

\n
fs.access('file/that/does/not/exist', (err) => {\n  const name = util.getSystemErrorName(err.errno);\n  console.error(name);  // ENOENT\n});\n
" }, { "textRaw": "`util.getSystemErrorMap()`", "type": "method", "name": "getSystemErrorMap", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Map}", "name": "return", "type": "Map" }, "params": [] } ], "desc": "

Returns a Map of all system error codes available from the Node.js API.\nThe mapping between error codes and error names is platform-dependent.\nSee Common System Errors for the names of common errors.

\n
fs.access('file/that/does/not/exist', (err) => {\n  const errorMap = util.getSystemErrorMap();\n  const name = errorMap.get(err.errno);\n  console.error(name);  // ENOENT\n});\n
" }, { "textRaw": "`util.inherits(constructor, superConstructor)`", "type": "method", "name": "inherits", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/3455", "description": "The `constructor` parameter can refer to an ES6 class now." } ] }, "stability": 3, "stabilityText": "Legacy: Use ES2015 class syntax and `extends` keyword instead.", "signatures": [ { "params": [ { "textRaw": "`constructor` {Function}", "name": "constructor", "type": "Function" }, { "textRaw": "`superConstructor` {Function}", "name": "superConstructor", "type": "Function" } ] } ], "desc": "

Usage of util.inherits() is discouraged. Please use the ES6 class and\nextends keywords to get language level inheritance support. Also note\nthat the two styles are semantically incompatible.

\n

Inherit the prototype methods from one constructor into another. The\nprototype of constructor will be set to a new object created from\nsuperConstructor.

\n

This mainly adds some input validation on top of\nObject.setPrototypeOf(constructor.prototype, superConstructor.prototype).\nAs an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.

\n
const util = require('util');\nconst EventEmitter = require('events');\n\nfunction MyStream() {\n  EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, EventEmitter);\n\nMyStream.prototype.write = function(data) {\n  this.emit('data', data);\n};\n\nconst stream = new MyStream();\n\nconsole.log(stream instanceof EventEmitter); // true\nconsole.log(MyStream.super_ === EventEmitter); // true\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('It works!'); // Received data: \"It works!\"\n
\n

ES6 example using class and extends:

\n
const EventEmitter = require('events');\n\nclass MyStream extends EventEmitter {\n  write(data) {\n    this.emit('data', data);\n  }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n  console.log(`Received data: \"${data}\"`);\n});\nstream.write('With ES6');\n
" }, { "textRaw": "`util.inspect(object[, options])`", "type": "method", "name": "inspect", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33690", "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." }, { "version": [ "v13.13.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32392", "description": "The `maxStringLength` option is supported now." }, { "version": [ "v13.5.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30768", "description": "User defined prototype properties are inspected in case `showHidden` is `true`." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27685", "description": "Circular references now include a marker to the reference." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27109", "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/24971", "description": "Internal properties no longer appear in the context argument of a custom inspection function." }, { "version": "v11.11.0", "pr-url": "https://github.com/nodejs/node/pull/26269", "description": "The `compact` option accepts numbers for a new output mode." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25006", "description": "ArrayBuffers now also show their binary contents." }, { "version": "v11.5.0", "pr-url": "https://github.com/nodejs/node/pull/24852", "description": "The `getters` option is supported now." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24326", "description": "The `depth` default changed back to `2`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22846", "description": "The `depth` default changed to `20`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22756", "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22788", "description": "The `sorted` option is supported now." }, { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/20725", "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19259", "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17576", "description": "The `compact` option is supported now." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8174", "description": "Custom inspection functions can now return `this`." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/7499", "description": "The `breakLength` option is supported now." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6334", "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6465", "description": "The `showProxy` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} The representation of `object`.", "name": "return", "type": "string", "desc": "The representation of `object`." }, "params": [ { "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", "name": "object", "type": "any", "desc": "Any JavaScript primitive or `Object`." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", "name": "showHidden", "type": "boolean", "default": "`false`", "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." }, { "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", "name": "depth", "type": "number", "default": "`2`", "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." }, { "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", "name": "colors", "type": "boolean", "default": "`false`", "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." }, { "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", "name": "customInspect", "type": "boolean", "default": "`true`", "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." }, { "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", "name": "showProxy", "type": "boolean", "default": "`false`", "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." }, { "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", "name": "maxArrayLength", "type": "integer", "default": "`100`", "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." }, { "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `10000`.", "name": "maxStringLength", "type": "integer", "default": "`10000`", "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." }, { "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", "name": "breakLength", "type": "integer", "default": "`80`", "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." }, { "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will break on new lines in text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. For more information, see the example below. **Default:** `3`.", "name": "compact", "type": "boolean|integer", "default": "`3`", "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will break on new lines in text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. For more information, see the example below." }, { "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", "name": "sorted", "type": "boolean|Function", "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." }, { "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", "name": "getters", "type": "boolean|string", "default": "`false`", "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." } ] } ] } ], "desc": "

The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

\n
class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
\n

Circular references point to their anchor by using a reference index:

\n
const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// <ref *1> {\n//   a: [ [Circular *1] ],\n//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n// }\n
\n

The following example inspects all properties of the util object:

\n
const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
\n

The following example highlights the effect of the compact option:

\n
const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet,\\nconsectetur adipiscing elit, sed do ' +\n      'eiusmod \\ntempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet,\\nconsectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false or an integer creates more reader friendly output.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet,\\n' +\n//           'consectetur adipiscing elit, sed do eiusmod \\n' +\n//           'tempor incididunt ut labore et dolore magna aliqua.',\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map(2) {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n
\n

The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

\n
const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
\n

The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

\n
const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
\n

util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

" }, { "textRaw": "`util.inspect(object[, showHidden[, depth[, colors]]])`", "type": "method", "name": "inspect", "meta": { "added": [ "v0.3.0" ], "changes": [ { "version": [ "v14.6.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33690", "description": "If `object` is from a different `vm.Context` now, a custom inspection function on it will not receive context-specific arguments anymore." }, { "version": [ "v13.13.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32392", "description": "The `maxStringLength` option is supported now." }, { "version": [ "v13.5.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30768", "description": "User defined prototype properties are inspected in case `showHidden` is `true`." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27685", "description": "Circular references now include a marker to the reference." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/27109", "description": "The `compact` options default is changed to `3` and the `breakLength` options default is changed to `80`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/24971", "description": "Internal properties no longer appear in the context argument of a custom inspection function." }, { "version": "v11.11.0", "pr-url": "https://github.com/nodejs/node/pull/26269", "description": "The `compact` option accepts numbers for a new output mode." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25006", "description": "ArrayBuffers now also show their binary contents." }, { "version": "v11.5.0", "pr-url": "https://github.com/nodejs/node/pull/24852", "description": "The `getters` option is supported now." }, { "version": "v11.4.0", "pr-url": "https://github.com/nodejs/node/pull/24326", "description": "The `depth` default changed back to `2`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22846", "description": "The `depth` default changed to `20`." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22756", "description": "The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22788", "description": "The `sorted` option is supported now." }, { "version": "v10.6.0", "pr-url": "https://github.com/nodejs/node/pull/20725", "description": "Inspecting linked lists and similar objects is now possible up to the maximum call stack size." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19259", "description": "The `WeakMap` and `WeakSet` entries can now be inspected as well." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/17576", "description": "The `compact` option is supported now." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8174", "description": "Custom inspection functions can now return `this`." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/7499", "description": "The `breakLength` option is supported now." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6334", "description": "The `maxArrayLength` option is supported now; in particular, long arrays are truncated by default." }, { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/6465", "description": "The `showProxy` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} The representation of `object`.", "name": "return", "type": "string", "desc": "The representation of `object`." }, "params": [ { "textRaw": "`object` {any} Any JavaScript primitive or `Object`.", "name": "object", "type": "any", "desc": "Any JavaScript primitive or `Object`." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`showHidden` {boolean} If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties). **Default:** `false`.", "name": "showHidden", "type": "boolean", "default": "`false`", "desc": "If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result. [`WeakMap`][] and [`WeakSet`][] entries are also included as well as user defined prototype properties (excluding method properties)." }, { "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`. **Default:** `2`.", "name": "depth", "type": "number", "default": "`2`", "desc": "Specifies the number of times to recurse while formatting `object`. This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or `null`." }, { "textRaw": "`colors` {boolean} If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]. **Default:** `false`.", "name": "colors", "type": "boolean", "default": "`false`", "desc": "If `true`, the output is styled with ANSI color codes. Colors are customizable. See [Customizing `util.inspect` colors][]." }, { "textRaw": "`customInspect` {boolean} If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked. **Default:** `true`.", "name": "customInspect", "type": "boolean", "default": "`true`", "desc": "If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked." }, { "textRaw": "`showProxy` {boolean} If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects. **Default:** `false`.", "name": "showProxy", "type": "boolean", "default": "`false`", "desc": "If `true`, `Proxy` inspection includes the [`target` and `handler`][] objects." }, { "textRaw": "`maxArrayLength` {integer} Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements. **Default:** `100`.", "name": "maxArrayLength", "type": "integer", "default": "`100`", "desc": "Specifies the maximum number of `Array`, [`TypedArray`][], [`WeakMap`][] and [`WeakSet`][] elements to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no elements." }, { "textRaw": "`maxStringLength` {integer} Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters. **Default:** `10000`.", "name": "maxStringLength", "type": "integer", "default": "`10000`", "desc": "Specifies the maximum number of characters to include when formatting. Set to `null` or `Infinity` to show all elements. Set to `0` or negative to show no characters." }, { "textRaw": "`breakLength` {integer} The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`). **Default:** `80`.", "name": "breakLength", "type": "integer", "default": "`80`", "desc": "The length at which input values are split across multiple lines. Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any number >= `1`)." }, { "textRaw": "`compact` {boolean|integer} Setting this to `false` causes each object key to be displayed on a new line. It will break on new lines in text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. For more information, see the example below. **Default:** `3`.", "name": "compact", "type": "boolean|integer", "default": "`3`", "desc": "Setting this to `false` causes each object key to be displayed on a new line. It will break on new lines in text that is longer than `breakLength`. If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into `breakLength`. Short array elements are also grouped together. For more information, see the example below." }, { "textRaw": "`sorted` {boolean|Function} If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][].", "name": "sorted", "type": "boolean|Function", "desc": "If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the resulting string. If set to `true` the [default sort][] is used. If set to a function, it is used as a [compare function][]." }, { "textRaw": "`getters` {boolean|string} If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. **Default:** `false`.", "name": "getters", "type": "boolean|string", "default": "`false`", "desc": "If set to `true`, getters are inspected. If set to `'get'`, only getters without a corresponding setter are inspected. If set to `'set'`, only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function." } ] } ] } ], "desc": "

The util.inspect() method returns a string representation of object that is\nintended for debugging. The output of util.inspect may change at any time\nand should not be depended upon programmatically. Additional options may be\npassed that alter the result.\nutil.inspect() will use the constructor's name and/or @@toStringTag to make\nan identifiable tag for an inspected value.

\n
class Foo {\n  get [Symbol.toStringTag]() {\n    return 'bar';\n  }\n}\n\nclass Bar {}\n\nconst baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });\n\nutil.inspect(new Foo()); // 'Foo [bar] {}'\nutil.inspect(new Bar()); // 'Bar {}'\nutil.inspect(baz);       // '[foo] {}'\n
\n

Circular references point to their anchor by using a reference index:

\n
const { inspect } = require('util');\n\nconst obj = {};\nobj.a = [obj];\nobj.b = {};\nobj.b.inner = obj.b;\nobj.b.obj = obj;\n\nconsole.log(inspect(obj));\n// <ref *1> {\n//   a: [ [Circular *1] ],\n//   b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n// }\n
\n

The following example inspects all properties of the util object:

\n
const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
\n

The following example highlights the effect of the compact option:

\n
const util = require('util');\n\nconst o = {\n  a: [1, 2, [[\n    'Lorem ipsum dolor sit amet,\\nconsectetur adipiscing elit, sed do ' +\n      'eiusmod \\ntempor incididunt ut labore et dolore magna aliqua.',\n    'test',\n    'foo']], 4],\n  b: new Map([['za', 1], ['zb', 'test']])\n};\nconsole.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));\n\n// { a:\n//   [ 1,\n//     2,\n//     [ [ 'Lorem ipsum dolor sit amet,\\nconsectetur [...]', // A long line\n//           'test',\n//           'foo' ] ],\n//     4 ],\n//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }\n\n// Setting `compact` to false or an integer creates more reader friendly output.\nconsole.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 }));\n\n// {\n//   a: [\n//     1,\n//     2,\n//     [\n//       [\n//         'Lorem ipsum dolor sit amet,\\n' +\n//           'consectetur adipiscing elit, sed do eiusmod \\n' +\n//           'tempor incididunt ut labore et dolore magna aliqua.',\n//         'test',\n//         'foo'\n//       ]\n//     ],\n//     4\n//   ],\n//   b: Map(2) {\n//     'za' => 1,\n//     'zb' => 'test'\n//   }\n// }\n\n// Setting `breakLength` to e.g. 150 will print the \"Lorem ipsum\" text in a\n// single line.\n
\n

The showHidden option allows WeakMap and WeakSet entries to be\ninspected. If there are more entries than maxArrayLength, there is no\nguarantee which entries are displayed. That means retrieving the same\nWeakSet entries twice may result in different output. Furthermore, entries\nwith no remaining strong references may be garbage collected at any time.

\n
const { inspect } = require('util');\n\nconst obj = { a: 1 };\nconst obj2 = { b: 2 };\nconst weakSet = new WeakSet([obj, obj2]);\n\nconsole.log(inspect(weakSet, { showHidden: true }));\n// WeakSet { { a: 1 }, { b: 2 } }\n
\n

The sorted option ensures that an object's property insertion order does not\nimpact the result of util.inspect().

\n
const { inspect } = require('util');\nconst assert = require('assert');\n\nconst o1 = {\n  b: [2, 3, 1],\n  a: '`a` comes before `b`',\n  c: new Set([2, 3, 1])\n};\nconsole.log(inspect(o1, { sorted: true }));\n// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }\nconsole.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));\n// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }\n\nconst o2 = {\n  c: new Set([2, 1, 3]),\n  a: '`a` comes before `b`',\n  b: [2, 3, 1]\n};\nassert.strict.equal(\n  inspect(o1, { sorted: true }),\n  inspect(o2, { sorted: true })\n);\n
\n

util.inspect() is a synchronous method intended for debugging. Its maximum\noutput length is approximately 128 MB. Inputs that result in longer output will\nbe truncated.

", "miscs": [ { "textRaw": "Customizing `util.inspect` colors", "name": "Customizing `util.inspect` colors", "type": "misc", "desc": "

Color output (if enabled) of util.inspect is customizable globally\nvia the util.inspect.styles and util.inspect.colors properties.

\n

util.inspect.styles is a map associating a style name to a color from\nutil.inspect.colors.

\n

The default styles and associated colors are:

\n
    \n
  • bigint: yellow
  • \n
  • boolean: yellow
  • \n
  • date: magenta
  • \n
  • module: underline
  • \n
  • name: (no styling)
  • \n
  • null: bold
  • \n
  • number: yellow
  • \n
  • regexp: red
  • \n
  • special: cyan (e.g., Proxies)
  • \n
  • string: green
  • \n
  • symbol: green
  • \n
  • undefined: grey
  • \n
\n

Color styling uses ANSI control codes that may not be supported on all\nterminals. To verify color support use tty.hasColors().

\n

Predefined control codes are listed below (grouped as \"Modifiers\", \"Foreground\ncolors\", and \"Background colors\").

", "miscs": [ { "textRaw": "Modifiers", "name": "modifiers", "desc": "

Modifier support varies throughout different terminals. They will mostly be\nignored, if not supported.

\n
    \n
  • reset - Resets all (color) modifiers to their defaults
  • \n
  • bold - Make text bold
  • \n
  • italic - Make text italic
  • \n
  • underline - Make text underlined
  • \n
  • strikethrough - Puts a horizontal line through the center of the text\n(Alias: strikeThrough, crossedout, crossedOut)
  • \n
  • hidden - Prints the text, but makes it invisible (Alias: conceal)
  • \n
  • dim - Decreased color intensity (Alias:\nfaint)
  • \n
  • overlined - Make text overlined
  • \n
  • blink - Hides and shows the text in an interval
  • \n
  • inverse - Swap foreground and\nbackground colors (Alias: swapcolors, swapColors)
  • \n
  • doubleunderline - Make text\ndouble underlined (Alias: doubleUnderline)
  • \n
  • framed - Draw a frame around the text
  • \n
", "type": "misc", "displayName": "Modifiers" }, { "textRaw": "Foreground colors", "name": "foreground_colors", "desc": "
    \n
  • black
  • \n
  • red
  • \n
  • green
  • \n
  • yellow
  • \n
  • blue
  • \n
  • magenta
  • \n
  • cyan
  • \n
  • white
  • \n
  • gray (alias: grey, blackBright)
  • \n
  • redBright
  • \n
  • greenBright
  • \n
  • yellowBright
  • \n
  • blueBright
  • \n
  • magentaBright
  • \n
  • cyanBright
  • \n
  • whiteBright
  • \n
", "type": "misc", "displayName": "Foreground colors" }, { "textRaw": "Background colors", "name": "background_colors", "desc": "
    \n
  • bgBlack
  • \n
  • bgRed
  • \n
  • bgGreen
  • \n
  • bgYellow
  • \n
  • bgBlue
  • \n
  • bgMagenta
  • \n
  • bgCyan
  • \n
  • bgWhite
  • \n
  • bgGray (alias: bgGrey, bgBlackBright)
  • \n
  • bgRedBright
  • \n
  • bgGreenBright
  • \n
  • bgYellowBright
  • \n
  • bgBlueBright
  • \n
  • bgMagentaBright
  • \n
  • bgCyanBright
  • \n
  • bgWhiteBright
  • \n
", "type": "misc", "displayName": "Background colors" } ] }, { "textRaw": "Custom inspection functions on objects", "name": "Custom inspection functions on objects", "type": "misc", "desc": "

Objects may also define their own\n[util.inspect.custom](depth, opts) function,\nwhich util.inspect() will invoke and use the result of when inspecting\nthe object:

\n
const util = require('util');\n\nclass Box {\n  constructor(value) {\n    this.value = value;\n  }\n\n  [util.inspect.custom](depth, options) {\n    if (depth < 0) {\n      return options.stylize('[Box]', 'special');\n    }\n\n    const newOptions = Object.assign({}, options, {\n      depth: options.depth === null ? null : options.depth - 1\n    });\n\n    // Five space padding because that's the size of \"Box< \".\n    const padding = ' '.repeat(5);\n    const inner = util.inspect(this.value, newOptions)\n                      .replace(/\\n/g, `\\n${padding}`);\n    return `${options.stylize('Box', 'special')}< ${inner} >`;\n  }\n}\n\nconst box = new Box(true);\n\nutil.inspect(box);\n// Returns: \"Box< true >\"\n
\n

Custom [util.inspect.custom](depth, opts) functions typically return a string\nbut may return a value of any type that will be formatted accordingly by\nutil.inspect().

\n
const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[util.inspect.custom] = (depth) => {\n  return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: \"{ bar: 'baz' }\"\n
" } ], "properties": [ { "textRaw": "`custom` {symbol} that can be used to declare custom inspect functions.", "type": "symbol", "name": "custom", "meta": { "added": [ "v6.6.0" ], "changes": [ { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/20857", "description": "This is now defined as a shared symbol." } ] }, "desc": "

In addition to being accessible through util.inspect.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.inspect.custom').

\n
const inspect = Symbol.for('nodejs.util.inspect.custom');\n\nclass Password {\n  constructor(value) {\n    this.value = value;\n  }\n\n  toString() {\n    return 'xxxxxxxx';\n  }\n\n  [inspect]() {\n    return `Password <${this.toString()}>`;\n  }\n}\n\nconst password = new Password('r0sebud');\nconsole.log(password);\n// Prints Password <xxxxxxxx>\n
\n

See Custom inspection functions on Objects for more details.

", "shortDesc": "that can be used to declare custom inspect functions." }, { "textRaw": "`util.inspect.defaultOptions`", "name": "defaultOptions", "meta": { "added": [ "v6.4.0" ], "changes": [] }, "desc": "

The defaultOptions value allows customization of the default options used by\nutil.inspect. This is useful for functions like console.log or\nutil.format which implicitly call into util.inspect. It shall be set to an\nobject containing one or more valid util.inspect() options. Setting\noption properties directly is also supported.

\n
const util = require('util');\nconst arr = Array(101).fill(0);\n\nconsole.log(arr); // Logs the truncated array\nutil.inspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n
" } ] }, { "textRaw": "`util.isDeepStrictEqual(val1, val2)`", "type": "method", "name": "isDeepStrictEqual", "meta": { "added": [ "v9.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`val1` {any}", "name": "val1", "type": "any" }, { "textRaw": "`val2` {any}", "name": "val2", "type": "any" } ] } ], "desc": "

Returns true if there is deep strict equality between val1 and val2.\nOtherwise, returns false.

\n

See assert.deepStrictEqual() for more information about deep strict\nequality.

" }, { "textRaw": "`util.promisify(original)`", "type": "method", "name": "promisify", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Function}", "name": "return", "type": "Function" }, "params": [ { "textRaw": "`original` {Function}", "name": "original", "type": "Function" } ] } ], "desc": "

Takes a function following the common error-first callback style, i.e. taking\nan (err, value) => ... callback as the last argument, and returns a version\nthat returns promises.

\n
const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\nstat('.').then((stats) => {\n  // Do something with `stats`\n}).catch((error) => {\n  // Handle the error.\n});\n
\n

Or, equivalently using async functions:

\n
const util = require('util');\nconst fs = require('fs');\n\nconst stat = util.promisify(fs.stat);\n\nasync function callStat() {\n  const stats = await stat('.');\n  console.log(`This directory is owned by ${stats.uid}`);\n}\n
\n

If there is an original[util.promisify.custom] property present, promisify\nwill return its value, see Custom promisified functions.

\n

promisify() assumes that original is a function taking a callback as its\nfinal argument in all cases. If original is not a function, promisify()\nwill throw an error. If original is a function but its last argument is not\nan error-first callback, it will still be passed an error-first\ncallback as its last argument.

\n

Using promisify() on class methods or other methods that use this may not\nwork as expected unless handled specially:

\n
const util = require('util');\n\nclass Foo {\n  constructor() {\n    this.a = 42;\n  }\n\n  bar(callback) {\n    callback(null, this.a);\n  }\n}\n\nconst foo = new Foo();\n\nconst naiveBar = util.promisify(foo.bar);\n// TypeError: Cannot read property 'a' of undefined\n// naiveBar().then(a => console.log(a));\n\nnaiveBar.call(foo).then((a) => console.log(a)); // '42'\n\nconst bindBar = naiveBar.bind(foo);\nbindBar().then((a) => console.log(a)); // '42'\n
", "modules": [ { "textRaw": "Custom promisified functions", "name": "custom_promisified_functions", "desc": "

Using the util.promisify.custom symbol one can override the return value of\nutil.promisify():

\n
const util = require('util');\n\nfunction doSomething(foo, callback) {\n  // ...\n}\n\ndoSomething[util.promisify.custom] = (foo) => {\n  return getPromiseSomehow();\n};\n\nconst promisified = util.promisify(doSomething);\nconsole.log(promisified === doSomething[util.promisify.custom]);\n// prints 'true'\n
\n

This can be useful for cases where the original function does not follow the\nstandard format of taking an error-first callback as the last argument.

\n

For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

\n
doSomething[util.promisify.custom] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
\n

If promisify.custom is defined but is not a function, promisify() will\nthrow an error.

", "type": "module", "displayName": "Custom promisified functions" } ], "properties": [ { "textRaw": "`custom` {symbol} that can be used to declare custom promisified variants of functions, see [Custom promisified functions][].", "type": "symbol", "name": "custom", "meta": { "added": [ "v8.0.0" ], "changes": [ { "version": [ "v13.12.0", "v12.16.2" ], "pr-url": "https://github.com/nodejs/node/pull/31672", "description": "This is now defined as a shared symbol." } ] }, "desc": "

In addition to being accessible through util.promisify.custom, this\nsymbol is registered globally and can be\naccessed in any environment as Symbol.for('nodejs.util.promisify.custom').

\n

For example, with a function that takes in\n(foo, onSuccessCallback, onErrorCallback):

\n
const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');\n\ndoSomething[kCustomPromisifiedSymbol] = (foo) => {\n  return new Promise((resolve, reject) => {\n    doSomething(foo, resolve, reject);\n  });\n};\n
", "shortDesc": "that can be used to declare custom promisified variants of functions, see [Custom promisified functions][]." } ] } ], "classes": [ { "textRaw": "Class: `util.TextDecoder`", "type": "class", "name": "util.TextDecoder", "meta": { "added": [ "v8.3.0" ], "changes": [] }, "desc": "

An implementation of the WHATWG Encoding Standard TextDecoder API.

\n
const decoder = new TextDecoder('shift_jis');\nlet string = '';\nlet buffer;\nwhile (buffer = getNextChunkSomehow()) {\n  string += decoder.decode(buffer, { stream: true });\n}\nstring += decoder.decode(); // end-of-stream\n
", "modules": [ { "textRaw": "WHATWG supported encodings", "name": "whatwg_supported_encodings", "desc": "

Per the WHATWG Encoding Standard, the encodings supported by the\nTextDecoder API are outlined in the tables below. For each encoding,\none or more aliases may be used.

\n

Different Node.js build configurations support different sets of encodings.\n(see Internationalization)

", "modules": [ { "textRaw": "Encodings supported by default (with full ICU data)", "name": "encodings_supported_by_default_(with_full_icu_data)", "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\n\n\n\n\n\n\n\n\n\n\n\n\n\n
EncodingAliases
'ibm866''866', 'cp866', 'csibm866'
'iso-8859-2''csisolatin2', 'iso-ir-101', 'iso8859-2', 'iso88592', 'iso_8859-2', 'iso_8859-2:1987', 'l2', 'latin2'
'iso-8859-3''csisolatin3', 'iso-ir-109', 'iso8859-3', 'iso88593', 'iso_8859-3', 'iso_8859-3:1988', 'l3', 'latin3'
'iso-8859-4''csisolatin4', 'iso-ir-110', 'iso8859-4', 'iso88594', 'iso_8859-4', 'iso_8859-4:1988', 'l4', 'latin4'
'iso-8859-5''csisolatincyrillic', 'cyrillic', 'iso-ir-144', 'iso8859-5', 'iso88595', 'iso_8859-5', 'iso_8859-5:1988'
'iso-8859-6''arabic', 'asmo-708', 'csiso88596e', 'csiso88596i', 'csisolatinarabic', 'ecma-114', 'iso-8859-6-e', 'iso-8859-6-i', 'iso-ir-127', 'iso8859-6', 'iso88596', 'iso_8859-6', 'iso_8859-6:1987'
'iso-8859-7''csisolatingreek', 'ecma-118', 'elot_928', 'greek', 'greek8', 'iso-ir-126', 'iso8859-7', 'iso88597', 'iso_8859-7', 'iso_8859-7:1987', 'sun_eu_greek'
'iso-8859-8''csiso88598e', 'csisolatinhebrew', 'hebrew', 'iso-8859-8-e', 'iso-ir-138', 'iso8859-8', 'iso88598', 'iso_8859-8', 'iso_8859-8:1988', 'visual'
'iso-8859-8-i''csiso88598i', 'logical'
'iso-8859-10''csisolatin6', 'iso-ir-157', 'iso8859-10', 'iso885910', 'l6', 'latin6'
'iso-8859-13''iso8859-13', 'iso885913'
'iso-8859-14''iso8859-14', 'iso885914'
'iso-8859-15''csisolatin9', 'iso8859-15', 'iso885915', 'iso_8859-15', 'l9'
'koi8-r''cskoi8r', 'koi', 'koi8', 'koi8_r'
'koi8-u''koi8-ru'
'macintosh''csmacintosh', 'mac', 'x-mac-roman'
'windows-874''dos-874', 'iso-8859-11', 'iso8859-11', 'iso885911', 'tis-620'
'windows-1250''cp1250', 'x-cp1250'
'windows-1251''cp1251', 'x-cp1251'
'windows-1252''ansi_x3.4-1968', 'ascii', 'cp1252', 'cp819', 'csisolatin1', 'ibm819', 'iso-8859-1', 'iso-ir-100', 'iso8859-1', 'iso88591', 'iso_8859-1', 'iso_8859-1:1987', 'l1', 'latin1', 'us-ascii', 'x-cp1252'
'windows-1253''cp1253', 'x-cp1253'
'windows-1254''cp1254', 'csisolatin5', 'iso-8859-9', 'iso-ir-148', 'iso8859-9', 'iso88599', 'iso_8859-9', 'iso_8859-9:1989', 'l5', 'latin5', 'x-cp1254'
'windows-1255''cp1255', 'x-cp1255'
'windows-1256''cp1256', 'x-cp1256'
'windows-1257''cp1257', 'x-cp1257'
'windows-1258''cp1258', 'x-cp1258'
'x-mac-cyrillic''x-mac-ukrainian'
'gbk''chinese', 'csgb2312', 'csiso58gb231280', 'gb2312', 'gb_2312', 'gb_2312-80', 'iso-ir-58', 'x-gbk'
'gb18030'
'big5''big5-hkscs', 'cn-big5', 'csbig5', 'x-x-big5'
'euc-jp''cseucpkdfmtjapanese', 'x-euc-jp'
'iso-2022-jp''csiso2022jp'
'shift_jis''csshiftjis', 'ms932', 'ms_kanji', 'shift-jis', 'sjis', 'windows-31j', 'x-sjis'
'euc-kr''cseuckr', 'csksc56011987', 'iso-ir-149', 'korean', 'ks_c_5601-1987', 'ks_c_5601-1989', 'ksc5601', 'ksc_5601', 'windows-949'
", "type": "module", "displayName": "Encodings supported by default (with full ICU data)" }, { "textRaw": "Encodings supported when Node.js is built with the `small-icu` option", "name": "encodings_supported_when_node.js_is_built_with_the_`small-icu`_option", "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
EncodingAliases
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'
'utf-16be'
", "type": "module", "displayName": "Encodings supported when Node.js is built with the `small-icu` option" }, { "textRaw": "Encodings supported when ICU is disabled", "name": "encodings_supported_when_icu_is_disabled", "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
EncodingAliases
'utf-8''unicode-1-1-utf-8', 'utf8'
'utf-16le''utf-16'
\n

The 'iso-8859-16' encoding listed in the WHATWG Encoding Standard\nis not supported.

", "type": "module", "displayName": "Encodings supported when ICU is disabled" } ], "type": "module", "displayName": "WHATWG supported encodings" } ], "methods": [ { "textRaw": "`textDecoder.decode([input[, options]])`", "type": "method", "name": "decode", "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data.", "name": "input", "type": "ArrayBuffer|DataView|TypedArray", "desc": "An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`stream` {boolean} `true` if additional chunks of data are expected. **Default:** `false`.", "name": "stream", "type": "boolean", "default": "`false`", "desc": "`true` if additional chunks of data are expected." } ] } ] } ], "desc": "

Decodes the input and returns a string. If options.stream is true, any\nincomplete byte sequences occurring at the end of the input are buffered\ninternally and emitted after the next call to textDecoder.decode().

\n

If textDecoder.fatal is true, decoding errors that occur will result in a\nTypeError being thrown.

" } ], "properties": [ { "textRaw": "`encoding` {string}", "type": "string", "name": "encoding", "desc": "

The encoding supported by the TextDecoder instance.

" }, { "textRaw": "`fatal` {boolean}", "type": "boolean", "name": "fatal", "desc": "

The value will be true if decoding errors result in a TypeError being\nthrown.

" }, { "textRaw": "`ignoreBOM` {boolean}", "type": "boolean", "name": "ignoreBOM", "desc": "

The value will be true if the decoding result will include the byte order\nmark.

" } ], "signatures": [ { "params": [ { "textRaw": "`encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`.", "name": "encoding", "type": "string", "default": "`'utf-8'`", "desc": "Identifies the `encoding` that this `TextDecoder` instance supports." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`fatal` {boolean} `true` if decoding failures are fatal. This option is not supported when ICU is disabled (see [Internationalization][]). **Default:** `false`.", "name": "fatal", "type": "boolean", "default": "`false`", "desc": "`true` if decoding failures are fatal. This option is not supported when ICU is disabled (see [Internationalization][])." }, { "textRaw": "`ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.", "name": "ignoreBOM", "type": "boolean", "default": "`false`", "desc": "When `true`, the `TextDecoder` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`." } ] } ], "desc": "

Creates an new TextDecoder instance. The encoding may specify one of the\nsupported encodings or an alias.

\n

The TextDecoder class is also available on the global object.

" } ] }, { "textRaw": "Class: `util.TextEncoder`", "type": "class", "name": "util.TextEncoder", "meta": { "added": [ "v8.3.0" ], "changes": [ { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/22281", "description": "The class is now available on the global object." } ] }, "desc": "

An implementation of the WHATWG Encoding Standard TextEncoder API. All\ninstances of TextEncoder only support UTF-8 encoding.

\n
const encoder = new TextEncoder();\nconst uint8array = encoder.encode('this is some data');\n
\n

The TextEncoder class is also available on the global object.

", "methods": [ { "textRaw": "`textEncoder.encode([input])`", "type": "method", "name": "encode", "signatures": [ { "return": { "textRaw": "Returns: {Uint8Array}", "name": "return", "type": "Uint8Array" }, "params": [ { "textRaw": "`input` {string} The text to encode. **Default:** an empty string.", "name": "input", "type": "string", "default": "an empty string", "desc": "The text to encode." } ] } ], "desc": "

UTF-8 encodes the input string and returns a Uint8Array containing the\nencoded bytes.

" }, { "textRaw": "`textEncoder.encodeInto(src, dest)`", "type": "method", "name": "encodeInto", "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`read` {number} The read Unicode code units of src.", "name": "read", "type": "number", "desc": "The read Unicode code units of src." }, { "textRaw": "`written` {number} The written UTF-8 bytes of dest.", "name": "written", "type": "number", "desc": "The written UTF-8 bytes of dest." } ] }, "params": [ { "textRaw": "`src` {string} The text to encode.", "name": "src", "type": "string", "desc": "The text to encode." }, { "textRaw": "`dest` {Uint8Array} The array to hold the encode result.", "name": "dest", "type": "Uint8Array", "desc": "The array to hold the encode result." } ] } ], "desc": "

UTF-8 encodes the src string to the dest Uint8Array and returns an object\ncontaining the read Unicode code units and written UTF-8 bytes.

\n
const encoder = new TextEncoder();\nconst src = 'this is some data';\nconst dest = new Uint8Array(10);\nconst { read, written } = encoder.encodeInto(src, dest);\n
" } ], "properties": [ { "textRaw": "`encoding` {string}", "type": "string", "name": "encoding", "desc": "

The encoding supported by the TextEncoder instance. Always set to 'utf-8'.

" } ] } ], "properties": [ { "textRaw": "`util.types`", "name": "types", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v15.3.0", "pr-url": "https://github.com/nodejs/node/pull/34055", "description": "Exposed as `require('util/types')`." } ] }, "desc": "

util.types provides type checks for different kinds of built-in objects.\nUnlike instanceof or Object.prototype.toString.call(value), these checks do\nnot inspect properties of the object that are accessible from JavaScript (like\ntheir prototype), and usually have the overhead of calling into C++.

\n

The result generally does not make any guarantees about what kinds of\nproperties or behavior a value exposes in JavaScript. They are primarily\nuseful for addon developers who prefer to do type checking in JavaScript.

\n

The API is accessible via require('util').types or require('util/types').

", "methods": [ { "textRaw": "`util.types.isAnyArrayBuffer(value)`", "type": "method", "name": "isAnyArrayBuffer", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in ArrayBuffer or\nSharedArrayBuffer instance.

\n

See also util.types.isArrayBuffer() and\nutil.types.isSharedArrayBuffer().

\n
util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true\n
" }, { "textRaw": "`util.types.isArrayBufferView(value)`", "type": "method", "name": "isArrayBufferView", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an instance of one of the ArrayBuffer\nviews, such as typed array objects or DataView. Equivalent to\nArrayBuffer.isView().

\n
util.types.isArrayBufferView(new Int8Array());  // true\nutil.types.isArrayBufferView(Buffer.from('hello world')); // true\nutil.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true\nutil.types.isArrayBufferView(new ArrayBuffer());  // false\n
" }, { "textRaw": "`util.types.isArgumentsObject(value)`", "type": "method", "name": "isArgumentsObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an arguments object.

\n\n
function foo() {\n  util.types.isArgumentsObject(arguments);  // Returns true\n}\n
" }, { "textRaw": "`util.types.isArrayBuffer(value)`", "type": "method", "name": "isArrayBuffer", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in ArrayBuffer instance.\nThis does not include SharedArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

\n
util.types.isArrayBuffer(new ArrayBuffer());  // Returns true\nutil.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false\n
" }, { "textRaw": "`util.types.isAsyncFunction(value)`", "type": "method", "name": "isAsyncFunction", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an async function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

\n
util.types.isAsyncFunction(function foo() {});  // Returns false\nutil.types.isAsyncFunction(async function foo() {});  // Returns true\n
" }, { "textRaw": "`util.types.isBigInt64Array(value)`", "type": "method", "name": "isBigInt64Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a BigInt64Array instance.

\n
util.types.isBigInt64Array(new BigInt64Array());   // Returns true\nutil.types.isBigInt64Array(new BigUint64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isBigUint64Array(value)`", "type": "method", "name": "isBigUint64Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a BigUint64Array instance.

\n
util.types.isBigUint64Array(new BigInt64Array());   // Returns false\nutil.types.isBigUint64Array(new BigUint64Array());  // Returns true\n
" }, { "textRaw": "`util.types.isBooleanObject(value)`", "type": "method", "name": "isBooleanObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a boolean object, e.g. created\nby new Boolean().

\n
util.types.isBooleanObject(false);  // Returns false\nutil.types.isBooleanObject(true);   // Returns false\nutil.types.isBooleanObject(new Boolean(false)); // Returns true\nutil.types.isBooleanObject(new Boolean(true));  // Returns true\nutil.types.isBooleanObject(Boolean(false)); // Returns false\nutil.types.isBooleanObject(Boolean(true));  // Returns false\n
" }, { "textRaw": "`util.types.isBoxedPrimitive(value)`", "type": "method", "name": "isBoxedPrimitive", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is any boxed primitive object, e.g. created\nby new Boolean(), new String() or Object(Symbol()).

\n

For example:

\n
util.types.isBoxedPrimitive(false); // Returns false\nutil.types.isBoxedPrimitive(new Boolean(false)); // Returns true\nutil.types.isBoxedPrimitive(Symbol('foo')); // Returns false\nutil.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true\nutil.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true\n
" }, { "textRaw": "`util.types.isCryptoKey(value)`", "type": "method", "name": "isCryptoKey", "meta": { "added": [ "v16.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {Object}", "name": "value", "type": "Object" } ] } ], "desc": "

Returns true if value is a <CryptoKey>, false otherwise.

" }, { "textRaw": "`util.types.isDataView(value)`", "type": "method", "name": "isDataView", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in DataView instance.

\n
const ab = new ArrayBuffer(20);\nutil.types.isDataView(new DataView(ab));  // Returns true\nutil.types.isDataView(new Float64Array());  // Returns false\n
\n

See also ArrayBuffer.isView().

" }, { "textRaw": "`util.types.isDate(value)`", "type": "method", "name": "isDate", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Date instance.

\n
util.types.isDate(new Date());  // Returns true\n
" }, { "textRaw": "`util.types.isExternal(value)`", "type": "method", "name": "isExternal", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a native External value.

\n

A native External value is a special type of object that contains a\nraw C++ pointer (void*) for access from native code, and has no other\nproperties. Such objects are created either by Node.js internals or native\naddons. In JavaScript, they are frozen objects with a\nnull prototype.

\n
#include <js_native_api.h>\n#include <stdlib.h>\nnapi_value result;\nstatic napi_value MyNapi(napi_env env, napi_callback_info info) {\n  int* raw = (int*) malloc(1024);\n  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);\n  if (status != napi_ok) {\n    napi_throw_error(env, NULL, \"napi_create_external failed\");\n    return NULL;\n  }\n  return result;\n}\n...\nDECLARE_NAPI_PROPERTY(\"myNapi\", MyNapi)\n...\n
\n
const native = require('napi_addon.node');\nconst data = native.myNapi();\nutil.types.isExternal(data); // returns true\nutil.types.isExternal(0); // returns false\nutil.types.isExternal(new String('foo')); // returns false\n
\n

For further information on napi_create_external, refer to\nnapi_create_external().

" }, { "textRaw": "`util.types.isFloat32Array(value)`", "type": "method", "name": "isFloat32Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Float32Array instance.

\n
util.types.isFloat32Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat32Array(new Float32Array());  // Returns true\nutil.types.isFloat32Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isFloat64Array(value)`", "type": "method", "name": "isFloat64Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Float64Array instance.

\n
util.types.isFloat64Array(new ArrayBuffer());  // Returns false\nutil.types.isFloat64Array(new Uint8Array());  // Returns false\nutil.types.isFloat64Array(new Float64Array());  // Returns true\n
" }, { "textRaw": "`util.types.isGeneratorFunction(value)`", "type": "method", "name": "isGeneratorFunction", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

\n
util.types.isGeneratorFunction(function foo() {});  // Returns false\nutil.types.isGeneratorFunction(function* foo() {});  // Returns true\n
" }, { "textRaw": "`util.types.isGeneratorObject(value)`", "type": "method", "name": "isGeneratorObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a generator object as returned from a\nbuilt-in generator function.\nThis only reports back what the JavaScript engine is seeing;\nin particular, the return value may not match the original source code if\na transpilation tool was used.

\n
function* foo() {}\nconst generator = foo();\nutil.types.isGeneratorObject(generator);  // Returns true\n
" }, { "textRaw": "`util.types.isInt8Array(value)`", "type": "method", "name": "isInt8Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Int8Array instance.

\n
util.types.isInt8Array(new ArrayBuffer());  // Returns false\nutil.types.isInt8Array(new Int8Array());  // Returns true\nutil.types.isInt8Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isInt16Array(value)`", "type": "method", "name": "isInt16Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Int16Array instance.

\n
util.types.isInt16Array(new ArrayBuffer());  // Returns false\nutil.types.isInt16Array(new Int16Array());  // Returns true\nutil.types.isInt16Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isInt32Array(value)`", "type": "method", "name": "isInt32Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Int32Array instance.

\n
util.types.isInt32Array(new ArrayBuffer());  // Returns false\nutil.types.isInt32Array(new Int32Array());  // Returns true\nutil.types.isInt32Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isKeyObject(value)`", "type": "method", "name": "isKeyObject", "meta": { "added": [ "v16.2.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {Object}", "name": "value", "type": "Object" } ] } ], "desc": "

Returns true if value is a <KeyObject>, false otherwise.

" }, { "textRaw": "`util.types.isMap(value)`", "type": "method", "name": "isMap", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Map instance.

\n
util.types.isMap(new Map());  // Returns true\n
" }, { "textRaw": "`util.types.isMapIterator(value)`", "type": "method", "name": "isMapIterator", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an iterator returned for a built-in\nMap instance.

\n
const map = new Map();\nutil.types.isMapIterator(map.keys());  // Returns true\nutil.types.isMapIterator(map.values());  // Returns true\nutil.types.isMapIterator(map.entries());  // Returns true\nutil.types.isMapIterator(map[Symbol.iterator]());  // Returns true\n
" }, { "textRaw": "`util.types.isModuleNamespaceObject(value)`", "type": "method", "name": "isModuleNamespaceObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an instance of a Module Namespace Object.

\n\n
import * as ns from './a.js';\n\nutil.types.isModuleNamespaceObject(ns);  // Returns true\n
" }, { "textRaw": "`util.types.isNativeError(value)`", "type": "method", "name": "isNativeError", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an instance of a built-in Error type.

\n
util.types.isNativeError(new Error());  // Returns true\nutil.types.isNativeError(new TypeError());  // Returns true\nutil.types.isNativeError(new RangeError());  // Returns true\n
" }, { "textRaw": "`util.types.isNumberObject(value)`", "type": "method", "name": "isNumberObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a number object, e.g. created\nby new Number().

\n
util.types.isNumberObject(0);  // Returns false\nutil.types.isNumberObject(new Number(0));   // Returns true\n
" }, { "textRaw": "`util.types.isPromise(value)`", "type": "method", "name": "isPromise", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Promise.

\n
util.types.isPromise(Promise.resolve(42));  // Returns true\n
" }, { "textRaw": "`util.types.isProxy(value)`", "type": "method", "name": "isProxy", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a Proxy instance.

\n
const target = {};\nconst proxy = new Proxy(target, {});\nutil.types.isProxy(target);  // Returns false\nutil.types.isProxy(proxy);  // Returns true\n
" }, { "textRaw": "`util.types.isRegExp(value)`", "type": "method", "name": "isRegExp", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a regular expression object.

\n
util.types.isRegExp(/abc/);  // Returns true\nutil.types.isRegExp(new RegExp('abc'));  // Returns true\n
" }, { "textRaw": "`util.types.isSet(value)`", "type": "method", "name": "isSet", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Set instance.

\n
util.types.isSet(new Set());  // Returns true\n
" }, { "textRaw": "`util.types.isSetIterator(value)`", "type": "method", "name": "isSetIterator", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is an iterator returned for a built-in\nSet instance.

\n
const set = new Set();\nutil.types.isSetIterator(set.keys());  // Returns true\nutil.types.isSetIterator(set.values());  // Returns true\nutil.types.isSetIterator(set.entries());  // Returns true\nutil.types.isSetIterator(set[Symbol.iterator]());  // Returns true\n
" }, { "textRaw": "`util.types.isSharedArrayBuffer(value)`", "type": "method", "name": "isSharedArrayBuffer", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in SharedArrayBuffer instance.\nThis does not include ArrayBuffer instances. Usually, it is\ndesirable to test for both; See util.types.isAnyArrayBuffer() for that.

\n
util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false\nutil.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true\n
" }, { "textRaw": "`util.types.isStringObject(value)`", "type": "method", "name": "isStringObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a string object, e.g. created\nby new String().

\n
util.types.isStringObject('foo');  // Returns false\nutil.types.isStringObject(new String('foo'));   // Returns true\n
" }, { "textRaw": "`util.types.isSymbolObject(value)`", "type": "method", "name": "isSymbolObject", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a symbol object, created\nby calling Object() on a Symbol primitive.

\n
const symbol = Symbol('foo');\nutil.types.isSymbolObject(symbol);  // Returns false\nutil.types.isSymbolObject(Object(symbol));   // Returns true\n
" }, { "textRaw": "`util.types.isTypedArray(value)`", "type": "method", "name": "isTypedArray", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in TypedArray instance.

\n
util.types.isTypedArray(new ArrayBuffer());  // Returns false\nutil.types.isTypedArray(new Uint8Array());  // Returns true\nutil.types.isTypedArray(new Float64Array());  // Returns true\n
\n

See also ArrayBuffer.isView().

" }, { "textRaw": "`util.types.isUint8Array(value)`", "type": "method", "name": "isUint8Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Uint8Array instance.

\n
util.types.isUint8Array(new ArrayBuffer());  // Returns false\nutil.types.isUint8Array(new Uint8Array());  // Returns true\nutil.types.isUint8Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isUint8ClampedArray(value)`", "type": "method", "name": "isUint8ClampedArray", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Uint8ClampedArray instance.

\n
util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false\nutil.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true\nutil.types.isUint8ClampedArray(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isUint16Array(value)`", "type": "method", "name": "isUint16Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Uint16Array instance.

\n
util.types.isUint16Array(new ArrayBuffer());  // Returns false\nutil.types.isUint16Array(new Uint16Array());  // Returns true\nutil.types.isUint16Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isUint32Array(value)`", "type": "method", "name": "isUint32Array", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in Uint32Array instance.

\n
util.types.isUint32Array(new ArrayBuffer());  // Returns false\nutil.types.isUint32Array(new Uint32Array());  // Returns true\nutil.types.isUint32Array(new Float64Array());  // Returns false\n
" }, { "textRaw": "`util.types.isWeakMap(value)`", "type": "method", "name": "isWeakMap", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in WeakMap instance.

\n
util.types.isWeakMap(new WeakMap());  // Returns true\n
" }, { "textRaw": "`util.types.isWeakSet(value)`", "type": "method", "name": "isWeakSet", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in WeakSet instance.

\n
util.types.isWeakSet(new WeakSet());  // Returns true\n
" }, { "textRaw": "`util.types.isWebAssemblyCompiledModule(value)`", "type": "method", "name": "isWebAssemblyCompiledModule", "meta": { "added": [ "v10.0.0" ], "deprecated": [ "v14.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `value instanceof WebAssembly.Module` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Returns true if the value is a built-in WebAssembly.Module instance.

\n
const module = new WebAssembly.Module(wasmBuffer);\nutil.types.isWebAssemblyCompiledModule(module);  // Returns true\n
" } ] } ], "modules": [ { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "desc": "

The following APIs are deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.

", "methods": [ { "textRaw": "`util._extend(target, source)`", "type": "method", "name": "_extend", "meta": { "added": [ "v0.7.5" ], "deprecated": [ "v6.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`Object.assign()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`target` {Object}", "name": "target", "type": "Object" }, { "textRaw": "`source` {Object}", "name": "source", "type": "Object" } ] } ], "desc": "

The util._extend() method was never intended to be used outside of internal\nNode.js modules. The community found and used it anyway.

\n

It is deprecated and should not be used in new code. JavaScript comes with very\nsimilar built-in functionality through Object.assign().

" }, { "textRaw": "`util.isArray(object)`", "type": "method", "name": "isArray", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`Array.isArray()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Alias for Array.isArray().

\n

Returns true if the given object is an Array. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isArray([]);\n// Returns: true\nutil.isArray(new Array());\n// Returns: true\nutil.isArray({});\n// Returns: false\n
" }, { "textRaw": "`util.isBoolean(object)`", "type": "method", "name": "isBoolean", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `typeof value === 'boolean'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Boolean. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isBoolean(1);\n// Returns: false\nutil.isBoolean(0);\n// Returns: false\nutil.isBoolean(false);\n// Returns: true\n
" }, { "textRaw": "`util.isBuffer(object)`", "type": "method", "name": "isBuffer", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Buffer. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isBuffer({ length: 0 });\n// Returns: false\nutil.isBuffer([]);\n// Returns: false\nutil.isBuffer(Buffer.from('hello world'));\n// Returns: true\n
" }, { "textRaw": "`util.isDate(object)`", "type": "method", "name": "isDate", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`util.types.isDate()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Date. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isDate(new Date());\n// Returns: true\nutil.isDate(Date());\n// false (without 'new' returns a String)\nutil.isDate({});\n// Returns: false\n
" }, { "textRaw": "`util.isError(object)`", "type": "method", "name": "isError", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`util.types.isNativeError()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is an Error. Otherwise, returns\nfalse.

\n
const util = require('util');\n\nutil.isError(new Error());\n// Returns: true\nutil.isError(new TypeError());\n// Returns: true\nutil.isError({ name: 'Error', message: 'an error occurred' });\n// Returns: false\n
\n

This method relies on Object.prototype.toString() behavior. It is\npossible to obtain an incorrect result when the object argument manipulates\n@@toStringTag.

\n
const util = require('util');\nconst obj = { name: 'Error', message: 'an error occurred' };\n\nutil.isError(obj);\n// Returns: false\nobj[Symbol.toStringTag] = 'Error';\nutil.isError(obj);\n// Returns: true\n
" }, { "textRaw": "`util.isFunction(object)`", "type": "method", "name": "isFunction", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `typeof value === 'function'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Function. Otherwise, returns\nfalse.

\n
const util = require('util');\n\nfunction Foo() {}\nconst Bar = () => {};\n\nutil.isFunction({});\n// Returns: false\nutil.isFunction(Foo);\n// Returns: true\nutil.isFunction(Bar);\n// Returns: true\n
" }, { "textRaw": "`util.isNull(object)`", "type": "method", "name": "isNull", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `value === null` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is strictly null. Otherwise, returns\nfalse.

\n
const util = require('util');\n\nutil.isNull(0);\n// Returns: false\nutil.isNull(undefined);\n// Returns: false\nutil.isNull(null);\n// Returns: true\n
" }, { "textRaw": "`util.isNullOrUndefined(object)`", "type": "method", "name": "isNullOrUndefined", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use\n`value === undefined || value === null` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is null or undefined. Otherwise,\nreturns false.

\n
const util = require('util');\n\nutil.isNullOrUndefined(0);\n// Returns: false\nutil.isNullOrUndefined(undefined);\n// Returns: true\nutil.isNullOrUndefined(null);\n// Returns: true\n
" }, { "textRaw": "`util.isNumber(object)`", "type": "method", "name": "isNumber", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `typeof value === 'number'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Number. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isNumber(false);\n// Returns: false\nutil.isNumber(Infinity);\n// Returns: true\nutil.isNumber(0);\n// Returns: true\nutil.isNumber(NaN);\n// Returns: true\n
" }, { "textRaw": "`util.isObject(object)`", "type": "method", "name": "isObject", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated:\nUse `value !== null && typeof value === 'object'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is strictly an Object and not a\nFunction (even though functions are objects in JavaScript).\nOtherwise, returns false.

\n
const util = require('util');\n\nutil.isObject(5);\n// Returns: false\nutil.isObject(null);\n// Returns: false\nutil.isObject({});\n// Returns: true\nutil.isObject(() => {});\n// Returns: false\n
" }, { "textRaw": "`util.isPrimitive(object)`", "type": "method", "name": "isPrimitive", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use\n`(typeof value !== 'object' && typeof value !== 'function') || value === null`\ninstead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a primitive type. Otherwise, returns\nfalse.

\n
const util = require('util');\n\nutil.isPrimitive(5);\n// Returns: true\nutil.isPrimitive('foo');\n// Returns: true\nutil.isPrimitive(false);\n// Returns: true\nutil.isPrimitive(null);\n// Returns: true\nutil.isPrimitive(undefined);\n// Returns: true\nutil.isPrimitive({});\n// Returns: false\nutil.isPrimitive(() => {});\n// Returns: false\nutil.isPrimitive(/^$/);\n// Returns: false\nutil.isPrimitive(new Date());\n// Returns: false\n
" }, { "textRaw": "`util.isRegExp(object)`", "type": "method", "name": "isRegExp", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a RegExp. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isRegExp(/some regexp/);\n// Returns: true\nutil.isRegExp(new RegExp('another regexp'));\n// Returns: true\nutil.isRegExp({});\n// Returns: false\n
" }, { "textRaw": "`util.isString(object)`", "type": "method", "name": "isString", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `typeof value === 'string'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a string. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isString('');\n// Returns: true\nutil.isString('foo');\n// Returns: true\nutil.isString(String('foo'));\n// Returns: true\nutil.isString(5);\n// Returns: false\n
" }, { "textRaw": "`util.isSymbol(object)`", "type": "method", "name": "isSymbol", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `typeof value === 'symbol'` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is a Symbol. Otherwise, returns false.

\n
const util = require('util');\n\nutil.isSymbol(5);\n// Returns: false\nutil.isSymbol('foo');\n// Returns: false\nutil.isSymbol(Symbol('foo'));\n// Returns: true\n
" }, { "textRaw": "`util.isUndefined(object)`", "type": "method", "name": "isUndefined", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use `value === undefined` instead.", "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {any}", "name": "object", "type": "any" } ] } ], "desc": "

Returns true if the given object is undefined. Otherwise, returns false.

\n
const util = require('util');\n\nconst foo = undefined;\nutil.isUndefined(5);\n// Returns: false\nutil.isUndefined(foo);\n// Returns: true\nutil.isUndefined(null);\n// Returns: false\n
" }, { "textRaw": "`util.log(string)`", "type": "method", "name": "log", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v6.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use a third party module instead.", "signatures": [ { "params": [ { "textRaw": "`string` {string}", "name": "string", "type": "string" } ] } ], "desc": "

The util.log() method prints the given string to stdout with an included\ntimestamp.

\n
const util = require('util');\n\nutil.log('Timestamped message.');\n
" } ], "type": "module", "displayName": "Deprecated APIs" } ], "type": "module", "displayName": "Util", "source": "doc/api/util.md" }, { "textRaw": "V8", "name": "v8", "introduced_in": "v4.0.0", "desc": "

Source Code: lib/v8.js

\n

The v8 module exposes APIs that are specific to the version of V8\nbuilt into the Node.js binary. It can be accessed using:

\n
const v8 = require('v8');\n
", "methods": [ { "textRaw": "`v8.cachedDataVersionTag()`", "type": "method", "name": "cachedDataVersionTag", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Returns an integer representing a version tag derived from the V8 version,\ncommand-line flags, and detected CPU features. This is useful for determining\nwhether a vm.Script cachedData buffer is compatible with this instance\nof V8.

\n
console.log(v8.cachedDataVersionTag()); // 3947234607\n// The value returned by v8.cachedDataVersionTag() is derived from the V8\n// version, command-line flags, and detected CPU features. Test that the value\n// does indeed update when flags are toggled.\nv8.setFlagsFromString('--allow_natives_syntax');\nconsole.log(v8.cachedDataVersionTag()); // 183726201\n
" }, { "textRaw": "`v8.getHeapCodeStatistics()`", "type": "method", "name": "getHeapCodeStatistics", "meta": { "added": [ "v12.8.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object with the following properties:

\n\n\n
{\n  code_and_metadata_size: 212208,\n  bytecode_and_metadata_size: 161368,\n  external_script_source_size: 1410794\n}\n
" }, { "textRaw": "`v8.getHeapSnapshot()`", "type": "method", "name": "getHeapSnapshot", "meta": { "added": [ "v11.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Readable} A Readable Stream containing the V8 heap snapshot", "name": "return", "type": "stream.Readable", "desc": "A Readable Stream containing the V8 heap snapshot" }, "params": [] } ], "desc": "

Generates a snapshot of the current V8 heap and returns a Readable\nStream that may be used to read the JSON serialized representation.\nThis JSON stream format is intended to be used with tools such as\nChrome DevTools. The JSON schema is undocumented and specific to the\nV8 engine. Therefore, the schema may change from one version of V8 to the next.

\n
// Print heap snapshot to the console\nconst v8 = require('v8');\nconst stream = v8.getHeapSnapshot();\nstream.pipe(process.stdout);\n
" }, { "textRaw": "`v8.getHeapSpaceStatistics()`", "type": "method", "name": "getHeapSpaceStatistics", "meta": { "added": [ "v6.0.0" ], "changes": [ { "version": "v7.5.0", "pr-url": "https://github.com/nodejs/node/pull/10186", "description": "Support values exceeding the 32-bit unsigned integer range." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object[]}", "name": "return", "type": "Object[]" }, "params": [] } ], "desc": "

Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Neither the ordering of heap spaces, nor the availability of a\nheap space can be guaranteed as the statistics are provided via the V8\nGetHeapSpaceStatistics function and may change from one V8 version to the\nnext.

\n

The value returned is an array of objects containing the following properties:

\n\n
[\n  {\n    \"space_name\": \"new_space\",\n    \"space_size\": 2063872,\n    \"space_used_size\": 951112,\n    \"space_available_size\": 80824,\n    \"physical_space_size\": 2063872\n  },\n  {\n    \"space_name\": \"old_space\",\n    \"space_size\": 3090560,\n    \"space_used_size\": 2493792,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 3090560\n  },\n  {\n    \"space_name\": \"code_space\",\n    \"space_size\": 1260160,\n    \"space_used_size\": 644256,\n    \"space_available_size\": 960,\n    \"physical_space_size\": 1260160\n  },\n  {\n    \"space_name\": \"map_space\",\n    \"space_size\": 1094160,\n    \"space_used_size\": 201608,\n    \"space_available_size\": 0,\n    \"physical_space_size\": 1094160\n  },\n  {\n    \"space_name\": \"large_object_space\",\n    \"space_size\": 0,\n    \"space_used_size\": 0,\n    \"space_available_size\": 1490980608,\n    \"physical_space_size\": 0\n  }\n]\n
" }, { "textRaw": "`v8.getHeapStatistics()`", "type": "method", "name": "getHeapStatistics", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v7.5.0", "pr-url": "https://github.com/nodejs/node/pull/10186", "description": "Support values exceeding the 32-bit unsigned integer range." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/8610", "description": "Added `malloced_memory`, `peak_malloced_memory`, and `does_zap_garbage`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

Returns an object with the following properties:

\n\n

does_zap_garbage is a 0/1 boolean, which signifies whether the\n--zap_code_space option is enabled or not. This makes V8 overwrite heap\ngarbage with a bit pattern. The RSS footprint (resident set size) gets bigger\nbecause it continuously touches all heap pages and that makes them less likely\nto get swapped out by the operating system.

\n

number_of_native_contexts The value of native_context is the number of the\ntop-level contexts currently active. Increase of this number over time indicates\na memory leak.

\n

number_of_detached_contexts The value of detached_context is the number\nof contexts that were detached and not yet garbage collected. This number\nbeing non-zero indicates a potential memory leak.

\n\n
{\n  total_heap_size: 7326976,\n  total_heap_size_executable: 4194304,\n  total_physical_size: 7326976,\n  total_available_size: 1152656,\n  used_heap_size: 3476208,\n  heap_size_limit: 1535115264,\n  malloced_memory: 16384,\n  peak_malloced_memory: 1127496,\n  does_zap_garbage: 0,\n  number_of_native_contexts: 1,\n  number_of_detached_contexts: 0\n}\n
" }, { "textRaw": "`v8.setFlagsFromString(flags)`", "type": "method", "name": "setFlagsFromString", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`flags` {string}", "name": "flags", "type": "string" } ] } ], "desc": "

The v8.setFlagsFromString() method can be used to programmatically set\nV8 command-line flags. This method should be used with care. Changing settings\nafter the VM has started may result in unpredictable behavior, including\ncrashes and data loss; or it may simply do nothing.

\n

The V8 options available for a version of Node.js may be determined by running\nnode --v8-options.

\n

Usage:

\n
// Print GC events to stdout for one minute.\nconst v8 = require('v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
" }, { "textRaw": "`v8.stopCoverage()`", "type": "method", "name": "stopCoverage", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The v8.stopCoverage() method allows the user to stop the coverage collection\nstarted by NODE_V8_COVERAGE, so that V8 can release the execution count\nrecords and optimize code. This can be used in conjunction with\nv8.takeCoverage() if the user wants to collect the coverage on demand.

" }, { "textRaw": "`v8.takeCoverage()`", "type": "method", "name": "takeCoverage", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The v8.takeCoverage() method allows the user to write the coverage started by\nNODE_V8_COVERAGE to disk on demand. This method can be invoked multiple\ntimes during the lifetime of the process. Each time the execution counter will\nbe reset and a new coverage report will be written to the directory specified\nby NODE_V8_COVERAGE.

\n

When the process is about to exit, one last coverage will still be written to\ndisk unless v8.stopCoverage() is invoked before the process exits.

" }, { "textRaw": "`v8.writeHeapSnapshot([filename])`", "type": "method", "name": "writeHeapSnapshot", "meta": { "added": [ "v11.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string} The filename where the snapshot was saved.", "name": "return", "type": "string", "desc": "The filename where the snapshot was saved." }, "params": [ { "textRaw": "`filename` {string} The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread.", "name": "filename", "type": "string", "desc": "The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a worker thread." } ] } ], "desc": "

Generates a snapshot of the current V8 heap and writes it to a JSON\nfile. This file is intended to be used with tools such as Chrome\nDevTools. The JSON schema is undocumented and specific to the V8\nengine, and may change from one version of V8 to the next.

\n

A heap snapshot is specific to a single V8 isolate. When using\nworker threads, a heap snapshot generated from the main thread will\nnot contain any information about the workers, and vice versa.

\n
const { writeHeapSnapshot } = require('v8');\nconst {\n  Worker,\n  isMainThread,\n  parentPort\n} = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n\n  worker.once('message', (filename) => {\n    console.log(`worker heapdump: ${filename}`);\n    // Now get a heapdump for the main thread.\n    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);\n  });\n\n  // Tell the worker to create a heapdump.\n  worker.postMessage('heapdump');\n} else {\n  parentPort.once('message', (message) => {\n    if (message === 'heapdump') {\n      // Generate a heapdump for the worker\n      // and return the filename to the parent.\n      parentPort.postMessage(writeHeapSnapshot());\n    }\n  });\n}\n
" } ], "modules": [ { "textRaw": "Serialization API", "name": "serialization_api", "desc": "

The serialization API provides means of serializing JavaScript values in a way\nthat is compatible with the HTML structured clone algorithm.

\n

The format is backward-compatible (i.e. safe to store to disk).\nEqual JavaScript values may result in different serialized output.

", "methods": [ { "textRaw": "`v8.serialize(value)`", "type": "method", "name": "serialize", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Uses a DefaultSerializer to serialize value into a buffer.

" }, { "textRaw": "`v8.deserialize(buffer)`", "type": "method", "name": "deserialize", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serialize()`][].", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A buffer returned by [`serialize()`][]." } ] } ], "desc": "

Uses a DefaultDeserializer with default options to read a JS value\nfrom a buffer.

" } ], "classes": [ { "textRaw": "Class: `v8.Serializer`", "type": "class", "name": "v8.Serializer", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "methods": [ { "textRaw": "`serializer.writeHeader()`", "type": "method", "name": "writeHeader", "signatures": [ { "params": [] } ], "desc": "

Writes out a header, which includes the serialization format version.

" }, { "textRaw": "`serializer.writeValue(value)`", "type": "method", "name": "writeValue", "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" } ] } ], "desc": "

Serializes a JavaScript value and adds the serialized representation to the\ninternal buffer.

\n

This throws an error if value cannot be serialized.

" }, { "textRaw": "`serializer.releaseBuffer()`", "type": "method", "name": "releaseBuffer", "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [] } ], "desc": "

Returns the stored internal buffer. This serializer should not be used once\nthe buffer is released. Calling this method results in undefined behavior\nif a previous write has failed.

" }, { "textRaw": "`serializer.transferArrayBuffer(id, arrayBuffer)`", "type": "method", "name": "transferArrayBuffer", "signatures": [ { "params": [ { "textRaw": "`id` {integer} A 32-bit unsigned integer.", "name": "id", "type": "integer", "desc": "A 32-bit unsigned integer." }, { "textRaw": "`arrayBuffer` {ArrayBuffer} An `ArrayBuffer` instance.", "name": "arrayBuffer", "type": "ArrayBuffer", "desc": "An `ArrayBuffer` instance." } ] } ], "desc": "

Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the deserializing context to\ndeserializer.transferArrayBuffer().

" }, { "textRaw": "`serializer.writeUint32(value)`", "type": "method", "name": "writeUint32", "signatures": [ { "params": [ { "textRaw": "`value` {integer}", "name": "value", "type": "integer" } ] } ], "desc": "

Write a raw 32-bit unsigned integer.\nFor use inside of a custom serializer._writeHostObject().

" }, { "textRaw": "`serializer.writeUint64(hi, lo)`", "type": "method", "name": "writeUint64", "signatures": [ { "params": [ { "textRaw": "`hi` {integer}", "name": "hi", "type": "integer" }, { "textRaw": "`lo` {integer}", "name": "lo", "type": "integer" } ] } ], "desc": "

Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.\nFor use inside of a custom serializer._writeHostObject().

" }, { "textRaw": "`serializer.writeDouble(value)`", "type": "method", "name": "writeDouble", "signatures": [ { "params": [ { "textRaw": "`value` {number}", "name": "value", "type": "number" } ] } ], "desc": "

Write a JS number value.\nFor use inside of a custom serializer._writeHostObject().

" }, { "textRaw": "`serializer.writeRawBytes(buffer)`", "type": "method", "name": "writeRawBytes", "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView}", "name": "buffer", "type": "Buffer|TypedArray|DataView" } ] } ], "desc": "

Write raw bytes into the serializer’s internal buffer. The deserializer\nwill require a way to compute the length of the buffer.\nFor use inside of a custom serializer._writeHostObject().

" }, { "textRaw": "`serializer._writeHostObject(object)`", "type": "method", "name": "_writeHostObject", "signatures": [ { "params": [ { "textRaw": "`object` {Object}", "name": "object", "type": "Object" } ] } ], "desc": "

This method is called to write some kind of host object, i.e. an object created\nby native C++ bindings. If it is not possible to serialize object, a suitable\nexception should be thrown.

\n

This method is not present on the Serializer class itself but can be provided\nby subclasses.

" }, { "textRaw": "`serializer._getDataCloneError(message)`", "type": "method", "name": "_getDataCloneError", "signatures": [ { "params": [ { "textRaw": "`message` {string}", "name": "message", "type": "string" } ] } ], "desc": "

This method is called to generate error objects that will be thrown when an\nobject can not be cloned.

\n

This method defaults to the Error constructor and can be overridden on\nsubclasses.

" }, { "textRaw": "`serializer._getSharedArrayBufferId(sharedArrayBuffer)`", "type": "method", "name": "_getSharedArrayBufferId", "signatures": [ { "params": [ { "textRaw": "`sharedArrayBuffer` {SharedArrayBuffer}", "name": "sharedArrayBuffer", "type": "SharedArrayBuffer" } ] } ], "desc": "

This method is called when the serializer is going to serialize a\nSharedArrayBuffer object. It must return an unsigned 32-bit integer ID for\nthe object, using the same ID if this SharedArrayBuffer has already been\nserialized. When deserializing, this ID will be passed to\ndeserializer.transferArrayBuffer().

\n

If the object cannot be serialized, an exception should be thrown.

\n

This method is not present on the Serializer class itself but can be provided\nby subclasses.

" }, { "textRaw": "`serializer._setTreatArrayBufferViewsAsHostObjects(flag)`", "type": "method", "name": "_setTreatArrayBufferViewsAsHostObjects", "signatures": [ { "params": [ { "textRaw": "`flag` {boolean} **Default:** `false`", "name": "flag", "type": "boolean", "default": "`false`" } ] } ], "desc": "

Indicate whether to treat TypedArray and DataView objects as\nhost objects, i.e. pass them to serializer._writeHostObject().

" } ], "signatures": [ { "params": [], "desc": "

Creates a new Serializer object.

" } ] }, { "textRaw": "Class: `v8.Deserializer`", "type": "class", "name": "v8.Deserializer", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "methods": [ { "textRaw": "`deserializer.readHeader()`", "type": "method", "name": "readHeader", "signatures": [ { "params": [] } ], "desc": "

Reads and validates a header (including the format version).\nMay, for example, reject an invalid or unsupported wire format. In that case,\nan Error is thrown.

" }, { "textRaw": "`deserializer.readValue()`", "type": "method", "name": "readValue", "signatures": [ { "params": [] } ], "desc": "

Deserializes a JavaScript value from the buffer and returns it.

" }, { "textRaw": "`deserializer.transferArrayBuffer(id, arrayBuffer)`", "type": "method", "name": "transferArrayBuffer", "signatures": [ { "params": [ { "textRaw": "`id` {integer} A 32-bit unsigned integer.", "name": "id", "type": "integer", "desc": "A 32-bit unsigned integer." }, { "textRaw": "`arrayBuffer` {ArrayBuffer|SharedArrayBuffer} An `ArrayBuffer` instance.", "name": "arrayBuffer", "type": "ArrayBuffer|SharedArrayBuffer", "desc": "An `ArrayBuffer` instance." } ] } ], "desc": "

Marks an ArrayBuffer as having its contents transferred out of band.\nPass the corresponding ArrayBuffer in the serializing context to\nserializer.transferArrayBuffer() (or return the id from\nserializer._getSharedArrayBufferId() in the case of SharedArrayBuffers).

" }, { "textRaw": "`deserializer.getWireFormatVersion()`", "type": "method", "name": "getWireFormatVersion", "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Reads the underlying wire format version. Likely mostly to be useful to\nlegacy code reading old wire format versions. May not be called before\n.readHeader().

" }, { "textRaw": "`deserializer.readUint32()`", "type": "method", "name": "readUint32", "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

Read a raw 32-bit unsigned integer and return it.\nFor use inside of a custom deserializer._readHostObject().

" }, { "textRaw": "`deserializer.readUint64()`", "type": "method", "name": "readUint64", "signatures": [ { "return": { "textRaw": "Returns: {integer[]}", "name": "return", "type": "integer[]" }, "params": [] } ], "desc": "

Read a raw 64-bit unsigned integer and return it as an array [hi, lo]\nwith two 32-bit unsigned integer entries.\nFor use inside of a custom deserializer._readHostObject().

" }, { "textRaw": "`deserializer.readDouble()`", "type": "method", "name": "readDouble", "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [] } ], "desc": "

Read a JS number value.\nFor use inside of a custom deserializer._readHostObject().

" }, { "textRaw": "`deserializer.readRawBytes(length)`", "type": "method", "name": "readRawBytes", "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`length` {integer}", "name": "length", "type": "integer" } ] } ], "desc": "

Read raw bytes from the deserializer’s internal buffer. The length parameter\nmust correspond to the length of the buffer that was passed to\nserializer.writeRawBytes().\nFor use inside of a custom deserializer._readHostObject().

" }, { "textRaw": "`deserializer._readHostObject()`", "type": "method", "name": "_readHostObject", "signatures": [ { "params": [] } ], "desc": "

This method is called to read some kind of host object, i.e. an object that is\ncreated by native C++ bindings. If it is not possible to deserialize the data,\na suitable exception should be thrown.

\n

This method is not present on the Deserializer class itself but can be\nprovided by subclasses.

" } ], "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} A buffer returned by [`serializer.releaseBuffer()`][].", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "A buffer returned by [`serializer.releaseBuffer()`][]." } ], "desc": "

Creates a new Deserializer object.

" } ] }, { "textRaw": "Class: `v8.DefaultSerializer`", "type": "class", "name": "v8.DefaultSerializer", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

A subclass of Serializer that serializes TypedArray\n(in particular Buffer) and DataView objects as host objects, and only\nstores the part of their underlying ArrayBuffers that they are referring to.

" }, { "textRaw": "Class: `v8.DefaultDeserializer`", "type": "class", "name": "v8.DefaultDeserializer", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "desc": "

A subclass of Deserializer corresponding to the format written by\nDefaultSerializer.

" } ], "type": "module", "displayName": "Serialization API" } ], "type": "module", "displayName": "V8", "source": "doc/api/v8.md" }, { "textRaw": "VM (executing JavaScript)", "name": "vm", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/vm.js

\n

The vm module enables compiling and running code within V8 Virtual\nMachine contexts. The vm module is not a security mechanism. Do\nnot use it to run untrusted code.

\n

JavaScript code can be compiled and run immediately or\ncompiled, saved, and run later.

\n

A common use case is to run the code in a different V8 Context. This means\ninvoked code has a different global object than the invoking code.

\n

One can provide the context by contextifying an\nobject. The invoked code treats any property in the context like a\nglobal variable. Any changes to global variables caused by the invoked\ncode are reflected in the context object.

\n
const vm = require('vm');\n\nconst x = 1;\n\nconst context = { x: 2 };\nvm.createContext(context); // Contextify the object.\n\nconst code = 'x += 40; var y = 17;';\n// `x` and `y` are global variables in the context.\n// Initially, x has the value 2 because that is the value of context.x.\nvm.runInContext(code, context);\n\nconsole.log(context.x); // 42\nconsole.log(context.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
", "classes": [ { "textRaw": "Class: `vm.Script`", "type": "class", "name": "vm.Script", "meta": { "added": [ "v0.3.1" ], "changes": [] }, "desc": "

Instances of the vm.Script class contain precompiled scripts that can be\nexecuted in specific contexts.

", "methods": [ { "textRaw": "`script.createCachedData()`", "type": "method", "name": "createCachedData", "meta": { "added": [ "v10.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [] } ], "desc": "

Creates a code cache that can be used with the Script constructor's\ncachedData option. Returns a Buffer. This method may be called at any\ntime and any number of times.

\n
const script = new vm.Script(`\nfunction add(a, b) {\n  return a + b;\n}\n\nconst x = add(1, 2);\n`);\n\nconst cacheWithoutX = script.createCachedData();\n\nscript.runInThisContext();\n\nconst cacheWithX = script.createCachedData();\n
" }, { "textRaw": "`script.runInContext(contextifiedObject[, options])`", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`contextifiedObject` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", "name": "contextifiedObject", "type": "Object", "desc": "A [contextified][] object as returned by the `vm.createContext()` method." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." } ] } ] } ], "desc": "

Runs the compiled code contained by the vm.Script object within the given\ncontextifiedObject and returns the result. Running code does not have access\nto local scope.

\n

The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the context object.

\n
const vm = require('vm');\n\nconst context = {\n  animal: 'cat',\n  count: 2\n};\n\nconst script = new vm.Script('count += 1; name = \"kitty\";');\n\nvm.createContext(context);\nfor (let i = 0; i < 10; ++i) {\n  script.runInContext(context);\n}\n\nconsole.log(context);\n// Prints: { animal: 'cat', count: 12, name: 'kitty' }\n
\n

Using the timeout or breakOnSigint options will result in new event loops\nand corresponding threads being started, which have a non-zero performance\noverhead.

" }, { "textRaw": "`script.runInNewContext([contextObject[, options]])`", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34023", "description": "The `microtaskMode` option is supported now." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `contextCodeGeneration` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", "name": "contextObject", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." }, { "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "contextName", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "contextOrigin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`contextCodeGeneration` {Object}", "name": "contextCodeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] }, { "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case.", "name": "microtaskMode", "type": "string", "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case." } ] } ] } ], "desc": "

First contextifies the given contextObject, runs the compiled code contained\nby the vm.Script object within the created context, and returns the result.\nRunning code does not have access to local scope.

\n

The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual context.

\n
const vm = require('vm');\n\nconst script = new vm.Script('globalVar = \"set\"');\n\nconst contexts = [{}, {}, {}];\ncontexts.forEach((context) => {\n  script.runInNewContext(context);\n});\n\nconsole.log(contexts);\n// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
" }, { "textRaw": "`script.runInThisContext([options])`", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." } ] } ] } ], "desc": "

Runs the compiled code contained by the vm.Script within the context of the\ncurrent global object. Running code does not have access to local scope, but\ndoes have access to the current global object.

\n

The following example compiles code that increments a global variable then\nexecutes that code multiple times:

\n
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (let i = 0; i < 1000; ++i) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000\n
" } ], "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile.", "name": "code", "type": "string", "desc": "The JavaScript code to compile." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`script` {vm.Script}", "name": "script", "type": "vm.Script" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ] } ], "desc": "

If options is a string, then it specifies the filename.

\n

Creating a new vm.Script object compiles code but does not run it. The\ncompiled vm.Script can be run later multiple times. The code is not bound to\nany global object; rather, it is bound before each run, just for that run.

" } ] }, { "textRaw": "Class: `vm.Module`", "type": "class", "name": "vm.Module", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n

The vm.Module class provides a low-level interface for using\nECMAScript modules in VM contexts. It is the counterpart of the vm.Script\nclass that closely mirrors Module Records as defined in the ECMAScript\nspecification.

\n

Unlike vm.Script however, every vm.Module object is bound to a context from\nits creation. Operations on vm.Module objects are intrinsically asynchronous,\nin contrast with the synchronous nature of vm.Script objects. The use of\n'async' functions can help with manipulating vm.Module objects.

\n

Using a vm.Module object requires three distinct steps: creation/parsing,\nlinking, and evaluation. These three steps are illustrated in the following\nexample.

\n

This implementation lies at a lower level than the ECMAScript Module\nloader. There is also no way to interact with the Loader yet, though\nsupport is planned.

\n
import vm from 'vm';\n\nconst contextifiedObject = vm.createContext({\n  secret: 42,\n  print: console.log,\n});\n\n// Step 1\n//\n// Create a Module by constructing a new `vm.SourceTextModule` object. This\n// parses the provided source text, throwing a `SyntaxError` if anything goes\n// wrong. By default, a Module is created in the top context. But here, we\n// specify `contextifiedObject` as the context this Module belongs to.\n//\n// Here, we attempt to obtain the default export from the module \"foo\", and\n// put it into local binding \"secret\".\n\nconst bar = new vm.SourceTextModule(`\n  import s from 'foo';\n  s;\n  print(s);\n`, { context: contextifiedObject });\n\n// Step 2\n//\n// \"Link\" the imported dependencies of this Module to it.\n//\n// The provided linking callback (the \"linker\") accepts two arguments: the\n// parent module (`bar` in this case) and the string that is the specifier of\n// the imported module. The callback is expected to return a Module that\n// corresponds to the provided specifier, with certain requirements documented\n// in `module.link()`.\n//\n// If linking has not started for the returned Module, the same linker\n// callback will be called on the returned Module.\n//\n// Even top-level Modules without dependencies must be explicitly linked. The\n// callback provided would never be called, however.\n//\n// The link() method returns a Promise that will be resolved when all the\n// Promises returned by the linker resolve.\n//\n// Note: This is a contrived example in that the linker function creates a new\n// \"foo\" module every time it is called. In a full-fledged module system, a\n// cache would probably be used to avoid duplicated modules.\n\nasync function linker(specifier, referencingModule) {\n  if (specifier === 'foo') {\n    return new vm.SourceTextModule(`\n      // The \"secret\" variable refers to the global variable we added to\n      // \"contextifiedObject\" when creating the context.\n      export default secret;\n    `, { context: referencingModule.context });\n\n    // Using `contextifiedObject` instead of `referencingModule.context`\n    // here would work as well.\n  }\n  throw new Error(`Unable to resolve dependency: ${specifier}`);\n}\nawait bar.link(linker);\n\n// Step 3\n//\n// Evaluate the Module. The evaluate() method returns a promise which will\n// resolve after the module has finished evaluating.\n\n// Prints 42.\nawait bar.evaluate();\n
\n
const vm = require('vm');\n\nconst contextifiedObject = vm.createContext({\n  secret: 42,\n  print: console.log,\n});\n\n(async () => {\n  // Step 1\n  //\n  // Create a Module by constructing a new `vm.SourceTextModule` object. This\n  // parses the provided source text, throwing a `SyntaxError` if anything goes\n  // wrong. By default, a Module is created in the top context. But here, we\n  // specify `contextifiedObject` as the context this Module belongs to.\n  //\n  // Here, we attempt to obtain the default export from the module \"foo\", and\n  // put it into local binding \"secret\".\n\n  const bar = new vm.SourceTextModule(`\n    import s from 'foo';\n    s;\n    print(s);\n  `, { context: contextifiedObject });\n\n  // Step 2\n  //\n  // \"Link\" the imported dependencies of this Module to it.\n  //\n  // The provided linking callback (the \"linker\") accepts two arguments: the\n  // parent module (`bar` in this case) and the string that is the specifier of\n  // the imported module. The callback is expected to return a Module that\n  // corresponds to the provided specifier, with certain requirements documented\n  // in `module.link()`.\n  //\n  // If linking has not started for the returned Module, the same linker\n  // callback will be called on the returned Module.\n  //\n  // Even top-level Modules without dependencies must be explicitly linked. The\n  // callback provided would never be called, however.\n  //\n  // The link() method returns a Promise that will be resolved when all the\n  // Promises returned by the linker resolve.\n  //\n  // Note: This is a contrived example in that the linker function creates a new\n  // \"foo\" module every time it is called. In a full-fledged module system, a\n  // cache would probably be used to avoid duplicated modules.\n\n  async function linker(specifier, referencingModule) {\n    if (specifier === 'foo') {\n      return new vm.SourceTextModule(`\n        // The \"secret\" variable refers to the global variable we added to\n        // \"contextifiedObject\" when creating the context.\n        export default secret;\n      `, { context: referencingModule.context });\n\n      // Using `contextifiedObject` instead of `referencingModule.context`\n      // here would work as well.\n    }\n    throw new Error(`Unable to resolve dependency: ${specifier}`);\n  }\n  await bar.link(linker);\n\n  // Step 3\n  //\n  // Evaluate the Module. The evaluate() method returns a promise which will\n  // resolve after the module has finished evaluating.\n\n  // Prints 42.\n  await bar.evaluate();\n})();\n
", "properties": [ { "textRaw": "`dependencySpecifiers` {string[]}", "type": "string[]", "name": "dependencySpecifiers", "desc": "

The specifiers of all dependencies of this module. The returned array is frozen\nto disallow any changes to it.

\n

Corresponds to the [[RequestedModules]] field of Cyclic Module Records in\nthe ECMAScript specification.

" }, { "textRaw": "`error` {any}", "type": "any", "name": "error", "desc": "

If the module.status is 'errored', this property contains the exception\nthrown by the module during evaluation. If the status is anything else,\naccessing this property will result in a thrown exception.

\n

The value undefined cannot be used for cases where there is not a thrown\nexception due to possible ambiguity with throw undefined;.

\n

Corresponds to the [[EvaluationError]] field of Cyclic Module Records\nin the ECMAScript specification.

" }, { "textRaw": "`identifier` {string}", "type": "string", "name": "identifier", "desc": "

The identifier of the current module, as set in the constructor.

" }, { "textRaw": "`namespace` {Object}", "type": "Object", "name": "namespace", "desc": "

The namespace object of the module. This is only available after linking\n(module.link()) has completed.

\n

Corresponds to the GetModuleNamespace abstract operation in the ECMAScript\nspecification.

" }, { "textRaw": "`status` {string}", "type": "string", "name": "status", "desc": "

The current status of the module. Will be one of:

\n
    \n
  • \n

    'unlinked': module.link() has not yet been called.

    \n
  • \n
  • \n

    'linking': module.link() has been called, but not all Promises returned\nby the linker function have been resolved yet.

    \n
  • \n
  • \n

    'linked': The module has been linked successfully, and all of its\ndependencies are linked, but module.evaluate() has not yet been called.

    \n
  • \n
  • \n

    'evaluating': The module is being evaluated through a module.evaluate() on\nitself or a parent module.

    \n
  • \n
  • \n

    'evaluated': The module has been successfully evaluated.

    \n
  • \n
  • \n

    'errored': The module has been evaluated, but an exception was thrown.

    \n
  • \n
\n

Other than 'errored', this status string corresponds to the specification's\nCyclic Module Record's [[Status]] field. 'errored' corresponds to\n'evaluated' in the specification, but with [[EvaluationError]] set to a\nvalue that is not undefined.

" } ], "methods": [ { "textRaw": "`module.evaluate([options])`", "type": "method", "name": "evaluate", "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with `undefined` upon success.", "name": "return", "type": "Promise", "desc": "Fulfills with `undefined` upon success." }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." } ] } ] } ], "desc": "

Evaluate the module.

\n

This must be called after the module has been linked; otherwise it will reject.\nIt could be called also when the module has already been evaluated, in which\ncase it will either do nothing if the initial evaluation ended in success\n(module.status is 'evaluated') or it will re-throw the exception that the\ninitial evaluation resulted in (module.status is 'errored').

\n

This method cannot be called while the module is being evaluated\n(module.status is 'evaluating').

\n

Corresponds to the Evaluate() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

" }, { "textRaw": "`module.link(linker)`", "type": "method", "name": "link", "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [ { "textRaw": "`linker` {Function}", "name": "linker", "type": "Function", "options": [ { "textRaw": "`specifier` {string} The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```", "name": "specifier", "type": "string", "desc": "The specifier of the requested module:```mjs import foo from 'foo'; // ^^^^^ the module specifier ```" }, { "textRaw": "`extra` {Object}", "name": "extra", "type": "Object", "options": [ { "textRaw": "`assert` {Object} The data from the assertion:```js import foo from 'foo' assert { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the assertion ```Per ECMA-262, hosts are expected to ignore assertions that they do not support, as opposed to, for example, triggering an error if an unsupported assertion is present.", "name": "assert", "type": "Object", "desc": "The data from the assertion:```js import foo from 'foo' assert { name: 'value' }; // ^^^^^^^^^^^^^^^^^ the assertion ```Per ECMA-262, hosts are expected to ignore assertions that they do not support, as opposed to, for example, triggering an error if an unsupported assertion is present." } ] }, { "textRaw": "`referencingModule` {vm.Module} The `Module` object `link()` is called on.", "name": "referencingModule", "type": "vm.Module", "desc": "The `Module` object `link()` is called on." }, { "textRaw": "Returns: {vm.Module|Promise}", "name": "return", "type": "vm.Module|Promise" } ] } ] } ], "desc": "

Link module dependencies. This method must be called before evaluation, and\ncan only be called once per module.

\n

The function is expected to return a Module object or a Promise that\neventually resolves to a Module object. The returned Module must satisfy the\nfollowing two invariants:

\n
    \n
  • It must belong to the same context as the parent Module.
  • \n
  • Its status must not be 'errored'.
  • \n
\n

If the returned Module's status is 'unlinked', this method will be\nrecursively called on the returned Module with the same provided linker\nfunction.

\n

link() returns a Promise that will either get resolved when all linking\ninstances resolve to a valid Module, or rejected if the linker function either\nthrows an exception or returns an invalid Module.

\n

The linker function roughly corresponds to the implementation-defined\nHostResolveImportedModule abstract operation in the ECMAScript\nspecification, with a few key differences:

\n\n

The actual HostResolveImportedModule implementation used during module\nlinking is one that returns the modules linked during linking. Since at\nthat point all modules would have been fully linked already, the\nHostResolveImportedModule implementation is fully synchronous per\nspecification.

\n

Corresponds to the Link() concrete method field of Cyclic Module\nRecords in the ECMAScript specification.

" } ] }, { "textRaw": "Class: `vm.SourceTextModule`", "type": "class", "name": "vm.SourceTextModule", "meta": { "added": [ "v9.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n\n

The vm.SourceTextModule class provides the Source Text Module Record as\ndefined in the ECMAScript specification.

", "methods": [ { "textRaw": "`sourceTextModule.createCachedData()`", "type": "method", "name": "createCachedData", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [] } ], "desc": "

Creates a code cache that can be used with the SourceTextModule constructor's\ncachedData option. Returns a Buffer. This method may be called any number\nof times before the module has been evaluated.

\n
// Create an initial module\nconst module = new vm.SourceTextModule('const a = 1;');\n\n// Create cached data from this module\nconst cachedData = module.createCachedData();\n\n// Create a new module using the cached data. The code must be the same.\nconst module2 = new vm.SourceTextModule('const a = 1;', { cachedData });\n
" } ], "signatures": [ { "params": [ { "textRaw": "`code` {string} JavaScript Module code to parse", "name": "code", "type": "string", "desc": "JavaScript Module code to parse" }, { "textRaw": "`options`", "name": "options", "options": [ { "textRaw": "`identifier` {string} String used in stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", "name": "identifier", "type": "string", "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", "desc": "String used in stack traces." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. The `code` must be the same as the module from which this `cachedData` was created." }, { "textRaw": "`context` {Object} The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in.", "name": "context", "type": "Object", "desc": "The [contextified][] object as returned by the `vm.createContext()` method, to compile and evaluate this `Module` in." }, { "textRaw": "`lineOffset` {integer} Specifies the line number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", "name": "lineOffset", "type": "integer", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this `Module`." }, { "textRaw": "`columnOffset` {integer} Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`. **Default:** `0`.", "name": "columnOffset", "type": "integer", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this `Module`." }, { "textRaw": "`initializeImportMeta` {Function} Called during evaluation of this `Module` to initialize the `import.meta`.", "name": "initializeImportMeta", "type": "Function", "desc": "Called during evaluation of this `Module` to initialize the `import.meta`.", "options": [ { "textRaw": "`meta` {import.meta}", "name": "meta", "type": "import.meta" }, { "textRaw": "`module` {vm.SourceTextModule}", "name": "module", "type": "vm.SourceTextModule" } ] }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`module` {vm.Module}", "name": "module", "type": "vm.Module" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ] } ], "desc": "

Creates a new SourceTextModule instance.

\n

Properties assigned to the import.meta object that are objects may\nallow the module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

\n
import vm from 'vm';\n\nconst contextifiedObject = vm.createContext({ secret: 42 });\n\nconst module = new vm.SourceTextModule(\n  'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n  {\n    initializeImportMeta(meta) {\n      // Note: this object is created in the top context. As such,\n      // Object.getPrototypeOf(import.meta.prop) points to the\n      // Object.prototype in the top context rather than that in\n      // the contextified object.\n      meta.prop = {};\n    }\n  });\n// Since module has no dependencies, the linker function will never be called.\nawait module.link(() => {});\nawait module.evaluate();\n\n// Now, Object.prototype.secret will be equal to 42.\n//\n// To fix this problem, replace\n//     meta.prop = {};\n// above with\n//     meta.prop = vm.runInContext('{}', contextifiedObject);\n
\n
const vm = require('vm');\nconst contextifiedObject = vm.createContext({ secret: 42 });\n(async () => {\n  const module = new vm.SourceTextModule(\n    'Object.getPrototypeOf(import.meta.prop).secret = secret;',\n    {\n      initializeImportMeta(meta) {\n        // Note: this object is created in the top context. As such,\n        // Object.getPrototypeOf(import.meta.prop) points to the\n        // Object.prototype in the top context rather than that in\n        // the contextified object.\n        meta.prop = {};\n      }\n    });\n  // Since module has no dependencies, the linker function will never be called.\n  await module.link(() => {});\n  await module.evaluate();\n  // Now, Object.prototype.secret will be equal to 42.\n  //\n  // To fix this problem, replace\n  //     meta.prop = {};\n  // above with\n  //     meta.prop = vm.runInContext('{}', contextifiedObject);\n})();\n
" } ] }, { "textRaw": "Class: `vm.SyntheticModule`", "type": "class", "name": "vm.SyntheticModule", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

This feature is only available with the --experimental-vm-modules command\nflag enabled.

\n\n

The vm.SyntheticModule class provides the Synthetic Module Record as\ndefined in the WebIDL specification. The purpose of synthetic modules is to\nprovide a generic interface for exposing non-JavaScript sources to ECMAScript\nmodule graphs.

\n
const vm = require('vm');\n\nconst source = '{ \"a\": 1 }';\nconst module = new vm.SyntheticModule(['default'], function() {\n  const obj = JSON.parse(source);\n  this.setExport('default', obj);\n});\n\n// Use `module` in linking...\n
", "methods": [ { "textRaw": "`syntheticModule.setExport(name, value)`", "type": "method", "name": "setExport", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string} Name of the export to set.", "name": "name", "type": "string", "desc": "Name of the export to set." }, { "textRaw": "`value` {any} The value to set the export to.", "name": "value", "type": "any", "desc": "The value to set the export to." } ] } ], "desc": "

This method is used after the module is linked to set the values of exports. If\nit is called before the module is linked, an ERR_VM_MODULE_STATUS error\nwill be thrown.

\n
import vm from 'vm';\n\nconst m = new vm.SyntheticModule(['x'], () => {\n  m.setExport('x', 1);\n});\n\nawait m.link(() => {});\nawait m.evaluate();\n\nassert.strictEqual(m.namespace.x, 1);\n
\n
const vm = require('vm');\n(async () => {\n  const m = new vm.SyntheticModule(['x'], () => {\n    m.setExport('x', 1);\n  });\n  await m.link(() => {});\n  await m.evaluate();\n  assert.strictEqual(m.namespace.x, 1);\n})();\n
" } ], "signatures": [ { "params": [ { "textRaw": "`exportNames` {string[]} Array of names that will be exported from the module.", "name": "exportNames", "type": "string[]", "desc": "Array of names that will be exported from the module." }, { "textRaw": "`evaluateCallback` {Function} Called when the module is evaluated.", "name": "evaluateCallback", "type": "Function", "desc": "Called when the module is evaluated." }, { "textRaw": "`options`**Default:** `'vm:module(i)'` where `i` is a context-specific ascending index.", "name": "options", "default": "`'vm:module(i)'` where `i` is a context-specific ascending index", "options": [ { "textRaw": "`identifier` {string} String used in stack traces.", "name": "identifier", "type": "string", "desc": "String used in stack traces." } ] } ], "desc": "

Creates a new SyntheticModule instance.

\n

Objects assigned to the exports of this instance may allow importers of\nthe module to access information outside the specified context. Use\nvm.runInContext() to create objects in a specific context.

" } ] } ], "methods": [ { "textRaw": "`vm.compileFunction(code[, params[, options]])`", "type": "method", "name": "compileFunction", "meta": { "added": [ "v10.10.0" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/35431", "description": "Added `importModuleDynamically` option again." }, { "version": "v14.3.0", "pr-url": "https://github.com/nodejs/node/pull/33364", "description": "Removal of `importModuleDynamically` due to compatibility issues." }, { "version": [ "v14.1.0", "v13.14.0" ], "pr-url": "https://github.com/nodejs/node/pull/32985", "description": "The `importModuleDynamically` option is now supported." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Function}", "name": "return", "type": "Function" }, "params": [ { "textRaw": "`code` {string} The body of the function to compile.", "name": "code", "type": "string", "desc": "The body of the function to compile." }, { "textRaw": "`params` {string[]} An array of strings containing all parameters for the function.", "name": "params", "type": "string[]", "desc": "An array of strings containing all parameters for the function." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `''`.", "name": "filename", "type": "string", "default": "`''`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source." }, { "textRaw": "`produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "Specifies whether to produce new cache data." }, { "textRaw": "`parsingContext` {Object} The [contextified][] object in which the said function should be compiled in.", "name": "parsingContext", "type": "Object", "desc": "The [contextified][] object in which the said function should be compiled in." }, { "textRaw": "`contextExtensions` {Object[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`.", "name": "contextExtensions", "type": "Object[]", "default": "`[]`", "desc": "An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API, and should not be considered stable.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`function` {Function}", "name": "function", "type": "Function" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ] } ] } ], "desc": "

Compiles the given code into the provided context (if no context is\nsupplied, the current context is used), and returns it wrapped inside a\nfunction with the given params.

" }, { "textRaw": "`vm.createContext([contextObject[, options]])`", "type": "method", "name": "createContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34023", "description": "The `microtaskMode` option is supported now." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19398", "description": "The first argument can no longer be a function." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `codeGeneration` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} contextified object.", "name": "return", "type": "Object", "desc": "contextified object." }, "params": [ { "textRaw": "`contextObject` {Object}", "name": "contextObject", "type": "Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`name` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "name", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`origin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "origin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`codeGeneration` {Object}", "name": "codeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] }, { "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after a script has run through [`script.runInContext()`][]. They are included in the `timeout` and `breakOnSigint` scopes in that case.", "name": "microtaskMode", "type": "string", "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after a script has run through [`script.runInContext()`][]. They are included in the `timeout` and `breakOnSigint` scopes in that case." } ] } ] } ], "desc": "

If given a contextObject, the vm.createContext() method will prepare\nthat object so that it can be used in calls to\nvm.runInContext() or script.runInContext(). Inside such scripts,\nthe contextObject will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.

\n
const vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst context = { globalVar: 1 };\nvm.createContext(context);\n\nvm.runInContext('globalVar *= 2;', context);\n\nconsole.log(context);\n// Prints: { globalVar: 2 }\n\nconsole.log(global.globalVar);\n// Prints: 3\n
\n

If contextObject is omitted (or passed explicitly as undefined), a new,\nempty contextified object will be returned.

\n

The vm.createContext() method is primarily useful for creating a single\ncontext that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single context representing a\nwindow's global object, then run all <script> tags together within that\ncontext.

\n

The provided name and origin of the context are made visible through the\nInspector API.

" }, { "textRaw": "`vm.isContext(object)`", "type": "method", "name": "isContext", "meta": { "added": [ "v0.11.7" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`object` {Object}", "name": "object", "type": "Object" } ] } ], "desc": "

Returns true if the given object object has been contextified using\nvm.createContext().

" }, { "textRaw": "`vm.measureMemory([options])`", "type": "method", "name": "measureMemory", "meta": { "added": [ "v13.10.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [] } ], "desc": "

Measure the memory known to V8 and used by all contexts known to the\ncurrent V8 isolate, or the main context.

\n
    \n
  • options <Object> Optional.\n
      \n
    • mode <string> Either 'summary' or 'detailed'. In summary mode,\nonly the memory measured for the main context will be returned. In\ndetailed mode, the measure measured for all contexts known to the\ncurrent V8 isolate will be returned.\nDefault: 'summary'
    • \n
    • execution <string> Either 'default' or 'eager'. With default\nexecution, the promise will not resolve until after the next scheduled\ngarbage collection starts, which may take a while (or never if the program\nexits before the next GC). With eager execution, the GC will be started\nright away to measure the memory.\nDefault: 'default'
    • \n
    \n
  • \n
  • Returns: <Promise> If the memory is successfully measured the promise will\nresolve with an object containing information about the memory usage.
  • \n
\n

The format of the object that the returned Promise may resolve with is\nspecific to the V8 engine and may change from one version of V8 to the next.

\n

The returned result is different from the statistics returned by\nv8.getHeapSpaceStatistics() in that vm.measureMemory() measure the\nmemory reachable by each V8 specific contexts in the current instance of\nthe V8 engine, while the result of v8.getHeapSpaceStatistics() measure\nthe memory occupied by each heap space in the current V8 instance.

\n
const vm = require('vm');\n// Measure the memory used by the main context.\nvm.measureMemory({ mode: 'summary' })\n  // This is the same as vm.measureMemory()\n  .then((result) => {\n    // The current format is:\n    // {\n    //   total: {\n    //      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]\n    //    }\n    // }\n    console.log(result);\n  });\n\nconst context = vm.createContext({ a: 1 });\nvm.measureMemory({ mode: 'detailed', execution: 'eager' })\n  .then((result) => {\n    // Reference the context here so that it won't be GC'ed\n    // until the measurement is complete.\n    console.log(context.a);\n    // {\n    //   total: {\n    //     jsMemoryEstimate: 2574732,\n    //     jsMemoryRange: [ 2574732, 2904372 ]\n    //   },\n    //   current: {\n    //     jsMemoryEstimate: 2438996,\n    //     jsMemoryRange: [ 2438996, 2768636 ]\n    //   },\n    //   other: [\n    //     {\n    //       jsMemoryEstimate: 135736,\n    //       jsMemoryRange: [ 135736, 465376 ]\n    //     }\n    //   ]\n    // }\n    console.log(result);\n  });\n
" }, { "textRaw": "`vm.runInContext(code, contextifiedObject[, options])`", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`contextifiedObject` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run.", "name": "contextifiedObject", "type": "Object", "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`script` {vm.Script}", "name": "script", "type": "vm.Script" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ] } ] } ], "desc": "

The vm.runInContext() method compiles code, runs it within the context of\nthe contextifiedObject, then returns the result. Running code does not have\naccess to the local scope. The contextifiedObject object must have been\npreviously contextified using the vm.createContext() method.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes different scripts using a single\ncontextified object:

\n
const vm = require('vm');\n\nconst contextObject = { globalVar: 1 };\nvm.createContext(contextObject);\n\nfor (let i = 0; i < 10; ++i) {\n  vm.runInContext('globalVar *= 2;', contextObject);\n}\nconsole.log(contextObject);\n// Prints: { globalVar: 1024 }\n
" }, { "textRaw": "`vm.runInNewContext(code[, contextObject[, options]])`", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v14.6.0", "pr-url": "https://github.com/nodejs/node/pull/34023", "description": "The `microtaskMode` option is supported now." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19016", "description": "The `contextCodeGeneration` option is supported now." }, { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`contextObject` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created.", "name": "contextObject", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." }, { "textRaw": "`contextName` {string} Human-readable name of the newly created context. **Default:** `'VM Context i'`, where `i` is an ascending numerical index of the created context.", "name": "contextName", "type": "string", "default": "`'VM Context i'`, where `i` is an ascending numerical index of the created context", "desc": "Human-readable name of the newly created context." }, { "textRaw": "`contextOrigin` {string} [Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path. **Default:** `''`.", "name": "contextOrigin", "type": "string", "default": "`''`", "desc": "[Origin][origin] corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the [`url.origin`][] property of a [`URL`][] object. Most notably, this string should omit the trailing slash, as that denotes a path." }, { "textRaw": "`contextCodeGeneration` {Object}", "name": "contextCodeGeneration", "type": "Object", "options": [ { "textRaw": "`strings` {boolean} If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`. **Default:** `true`.", "name": "strings", "type": "boolean", "default": "`true`", "desc": "If set to false any calls to `eval` or function constructors (`Function`, `GeneratorFunction`, etc) will throw an `EvalError`." }, { "textRaw": "`wasm` {boolean} If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`. **Default:** `true`.", "name": "wasm", "type": "boolean", "default": "`true`", "desc": "If set to false any attempt to compile a WebAssembly module will throw a `WebAssembly.CompileError`." } ] }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`script` {vm.Script}", "name": "script", "type": "vm.Script" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] }, { "textRaw": "`microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case.", "name": "microtaskMode", "type": "string", "desc": "If set to `afterEvaluate`, microtasks (tasks scheduled through `Promise`s and `async function`s) will be run immediately after the script has run. They are included in the `timeout` and `breakOnSigint` scopes in that case." } ] } ] } ], "desc": "

The vm.runInNewContext() first contextifies the given contextObject (or\ncreates a new contextObject if passed as undefined), compiles the code,\nruns it within the created context, then returns the result. Running code\ndoes not have access to the local scope.

\n

If options is a string, then it specifies the filename.

\n

The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the contextObject.

\n
const vm = require('vm');\n\nconst contextObject = {\n  animal: 'cat',\n  count: 2\n};\n\nvm.runInNewContext('count += 1; name = \"kitty\"', contextObject);\nconsole.log(contextObject);\n// Prints: { animal: 'cat', count: 3, name: 'kitty' }\n
" }, { "textRaw": "`vm.runInThisContext(code[, options])`", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ], "changes": [ { "version": "v6.3.0", "pr-url": "https://github.com/nodejs/node/pull/6635", "description": "The `breakOnSigint` option is supported now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {any} the result of the very last statement executed in the script.", "name": "return", "type": "any", "desc": "the result of the very last statement executed in the script." }, "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run.", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`options` {Object|string}", "name": "options", "type": "Object|string", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. **Default:** `'evalmachine.'`.", "name": "filename", "type": "string", "default": "`'evalmachine.'`", "desc": "Specifies the filename used in stack traces produced by this script." }, { "textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "lineOffset", "type": "number", "default": "`0`", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the first-line column number offset that is displayed in stack traces produced by this script. **Default:** `0`.", "name": "columnOffset", "type": "number", "default": "`0`", "desc": "Specifies the first-line column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. **Default:** `true`.", "name": "displayErrors", "type": "boolean", "default": "`true`", "desc": "When `true`, if an [`Error`][] occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {integer} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer.", "name": "timeout", "type": "integer", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. This value must be a strictly positive integer." }, { "textRaw": "`breakOnSigint` {boolean} If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that. **Default:** `false`.", "name": "breakOnSigint", "type": "boolean", "default": "`false`", "desc": "If `true`, receiving `SIGINT` (Ctrl+C) will terminate execution and throw an [`Error`][]. Existing handlers for the event that have been attached via `process.on('SIGINT')` are disabled during script execution, but continue to work after that." }, { "textRaw": "`cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8.", "name": "cachedData", "type": "Buffer|TypedArray|DataView", "desc": "Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied source. When supplied, the `cachedDataRejected` value will be set to either `true` or `false` depending on acceptance of the data by V8." }, { "textRaw": "`produceCachedData` {boolean} When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`. **Default:** `false`.", "name": "produceCachedData", "type": "boolean", "default": "`false`", "desc": "When `true` and no `cachedData` is present, V8 will attempt to produce code cache data for `code`. Upon success, a `Buffer` with V8's code cache data will be produced and stored in the `cachedData` property of the returned `vm.Script` instance. The `cachedDataProduced` value will be set to either `true` or `false` depending on whether code cache data is produced successfully. This option is **deprecated** in favor of `script.createCachedData()`." }, { "textRaw": "`importModuleDynamically` {Function} Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "name": "importModuleDynamically", "type": "Function", "desc": "Called during evaluation of this module when `import()` is called. If this option is not specified, calls to `import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][]. This option is part of the experimental modules API. We do not recommend using it in a production environment.", "options": [ { "textRaw": "`specifier` {string} specifier passed to `import()`", "name": "specifier", "type": "string", "desc": "specifier passed to `import()`" }, { "textRaw": "`script` {vm.Script}", "name": "script", "type": "vm.Script" }, { "textRaw": "Returns: {Module Namespace Object|vm.Module} Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports.", "name": "return", "type": "Module Namespace Object|vm.Module", "desc": "Returning a `vm.Module` is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain `then` function exports." } ] } ] } ] } ], "desc": "

vm.runInThisContext() compiles code, runs it within the context of the\ncurrent global and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global object.

\n

If options is a string, then it specifies the filename.

\n

The following example illustrates using both vm.runInThisContext() and\nthe JavaScript eval() function to run the same code:

\n\n
const vm = require('vm');\nlet localVar = 'initial value';\n\nconst vmResult = vm.runInThisContext('localVar = \"vm\";');\nconsole.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);\n// Prints: vmResult: 'vm', localVar: 'initial value'\n\nconst evalResult = eval('localVar = \"eval\";');\nconsole.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);\n// Prints: evalResult: 'eval', localVar: 'eval'\n
\n

Because vm.runInThisContext() does not have access to the local scope,\nlocalVar is unchanged. In contrast, eval() does have access to the\nlocal scope, so the value localVar is changed. In this way\nvm.runInThisContext() is much like an indirect eval() call, e.g.\n(0,eval)('code').

\n

Example: Running an HTTP server within a VM

\n

When using either script.runInThisContext() or\nvm.runInThisContext(), the code is executed within the current V8 global\ncontext. The code passed to this VM context will have its own isolated scope.

\n

In order to run a simple web server using the http module the code passed to\nthe context must either call require('http') on its own, or have a reference\nto the http module passed to it. For instance:

\n
'use strict';\nconst vm = require('vm');\n\nconst code = `\n((require) => {\n  const http = require('http');\n\n  http.createServer((request, response) => {\n    response.writeHead(200, { 'Content-Type': 'text/plain' });\n    response.end('Hello World\\\\n');\n  }).listen(8124);\n\n  console.log('Server running at http://127.0.0.1:8124/');\n})`;\n\nvm.runInThisContext(code)(require);\n
\n

The require() in the above case shares the state with the context it is\npassed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.

" } ], "modules": [ { "textRaw": "What does it mean to \"contextify\" an object?", "name": "what_does_it_mean_to_\"contextify\"_an_object?", "desc": "

All JavaScript executed within Node.js runs within the scope of a \"context\".\nAccording to the V8 Embedder's Guide:

\n
\n

In V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.

\n
\n

When the method vm.createContext() is called, the contextObject argument\n(or a newly-created object if contextObject is undefined) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode run using the vm module's methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the contextObject is what this document refers to as\n\"contextifying\" the object.

", "type": "module", "displayName": "What does it mean to \"contextify\" an object?" }, { "textRaw": "Timeout interactions with asynchronous tasks and Promises", "name": "timeout_interactions_with_asynchronous_tasks_and_promises", "desc": "

Promises and async functions can schedule tasks run by the JavaScript\nengine asynchronously. By default, these tasks are run after all JavaScript\nfunctions on the current stack are done executing.\nThis allows escaping the functionality of the timeout and\nbreakOnSigint options.

\n

For example, the following code executed by vm.runInNewContext() with a\ntimeout of 5 milliseconds schedules an infinite loop to run after a promise\nresolves. The scheduled loop is never interrupted by the timeout:

\n
const vm = require('vm');\n\nfunction loop() {\n  console.log('entering loop');\n  while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5 }\n);\n// This is printed *before* 'entering loop' (!)\nconsole.log('done executing');\n
\n

This can be addressed by passing microtaskMode: 'afterEvaluate' to the code\nthat creates the Context:

\n
const vm = require('vm');\n\nfunction loop() {\n  while (1) console.log(Date.now());\n}\n\nvm.runInNewContext(\n  'Promise.resolve().then(() => loop());',\n  { loop, console },\n  { timeout: 5, microtaskMode: 'afterEvaluate' }\n);\n
\n

In this case, the microtask scheduled through promise.then() will be run\nbefore returning from vm.runInNewContext(), and will be interrupted\nby the timeout functionality. This applies only to code running in a\nvm.Context, so e.g. vm.runInThisContext() does not take this option.

\n

Promise callbacks are entered into the microtask queue of the context in which\nthey were created. For example, if () => loop() is replaced with just loop\nin the above example, then loop will be pushed into the global microtask\nqueue, because it is a function from the outer (main) context, and thus will\nalso be able to escape the timeout.

\n

If asynchronous scheduling functions such as process.nextTick(),\nqueueMicrotask(), setTimeout(), setImmediate(), etc. are made available\ninside a vm.Context, functions passed to them will be added to global queues,\nwhich are shared by all contexts. Therefore, callbacks passed to those functions\nare not controllable through the timeout either.

", "type": "module", "displayName": "Timeout interactions with asynchronous tasks and Promises" } ], "type": "module", "displayName": "vm", "source": "doc/api/vm.md" }, { "textRaw": "WebAssembly System Interface (WASI)", "name": "webassembly_system_interface_(wasi)", "introduced_in": "v12.16.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Source Code: lib/wasi.js

\n

The WASI API provides an implementation of the WebAssembly System Interface\nspecification. WASI gives sandboxed WebAssembly applications access to the\nunderlying operating system via a collection of POSIX-like functions.

\n
import fs from 'fs';\nimport { WASI } from 'wasi';\nimport { argv, env } from 'process';\n\nconst wasi = new WASI({\n  args: argv,\n  env,\n  preopens: {\n    '/sandbox': '/some/real/path/that/wasm/can/access'\n  }\n});\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\nconst wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));\nconst instance = await WebAssembly.instantiate(wasm, importObject);\n\nwasi.start(instance);\n
\n
'use strict';\nconst fs = require('fs');\nconst { WASI } = require('wasi');\nconst { argv, env } = require('process');\n\nconst wasi = new WASI({\n  args: argv,\n  env,\n  preopens: {\n    '/sandbox': '/some/real/path/that/wasm/can/access'\n  }\n});\nconst importObject = { wasi_snapshot_preview1: wasi.wasiImport };\n\n(async () => {\n  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));\n  const instance = await WebAssembly.instantiate(wasm, importObject);\n\n  wasi.start(instance);\n})();\n
\n

To run the above example, create a new WebAssembly text format file named\ndemo.wat:

\n
(module\n    ;; Import the required fd_write WASI function which will write the given io vectors to stdout\n    ;; The function signature for fd_write is:\n    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written\n    (import \"wasi_snapshot_preview1\" \"fd_write\" (func $fd_write (param i32 i32 i32 i32) (result i32)))\n\n    (memory 1)\n    (export \"memory\" (memory 0))\n\n    ;; Write 'hello world\\n' to memory at an offset of 8 bytes\n    ;; Note the trailing newline which is required for the text to appear\n    (data (i32.const 8) \"hello world\\n\")\n\n    (func $main (export \"_start\")\n        ;; Creating a new io vector within linear memory\n        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\\n' string\n        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\\n' string\n\n        (call $fd_write\n            (i32.const 1) ;; file_descriptor - 1 for stdout\n            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0\n            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.\n            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written\n        )\n        drop ;; Discard the number of bytes written from the top of the stack\n    )\n)\n
\n

Use wabt to compile .wat to .wasm

\n
$ wat2wasm demo.wat\n
\n

The --experimental-wasi-unstable-preview1 CLI argument is needed for this\nexample to run.

", "classes": [ { "textRaw": "Class: `WASI`", "type": "class", "name": "WASI", "meta": { "added": [ "v13.3.0", "v12.16.0" ], "changes": [] }, "desc": "

The WASI class provides the WASI system call API and additional convenience\nmethods for working with WASI-based applications. Each WASI instance\nrepresents a distinct sandbox environment. For security purposes, each WASI\ninstance must have its command-line arguments, environment variables, and\nsandbox directory structure configured explicitly.

", "methods": [ { "textRaw": "`wasi.start(instance)`", "type": "method", "name": "start", "meta": { "added": [ "v13.3.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`instance` {WebAssembly.Instance}", "name": "instance", "type": "WebAssembly.Instance" } ] } ], "desc": "

Attempt to begin execution of instance as a WASI command by invoking its\n_start() export. If instance does not contain a _start() export, or if\ninstance contains an _initialize() export, then an exception is thrown.

\n

start() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

\n

If start() is called more than once, an exception is thrown.

" }, { "textRaw": "`wasi.initialize(instance)`", "type": "method", "name": "initialize", "meta": { "added": [ "v14.6.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`instance` {WebAssembly.Instance}", "name": "instance", "type": "WebAssembly.Instance" } ] } ], "desc": "

Attempt to initialize instance as a WASI reactor by invoking its\n_initialize() export, if it is present. If instance contains a _start()\nexport, then an exception is thrown.

\n

initialize() requires that instance exports a WebAssembly.Memory named\nmemory. If instance does not have a memory export an exception is thrown.

\n

If initialize() is called more than once, an exception is thrown.

" } ], "properties": [ { "textRaw": "`wasiImport` {Object}", "type": "Object", "name": "wasiImport", "meta": { "added": [ "v13.3.0", "v12.16.0" ], "changes": [] }, "desc": "

wasiImport is an object that implements the WASI system call API. This object\nshould be passed as the wasi_snapshot_preview1 import during the instantiation\nof a WebAssembly.Instance.

" } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`args` {Array} An array of strings that the WebAssembly application will see as command-line arguments. The first argument is the virtual path to the WASI command itself. **Default:** `[]`.", "name": "args", "type": "Array", "default": "`[]`", "desc": "An array of strings that the WebAssembly application will see as command-line arguments. The first argument is the virtual path to the WASI command itself." }, { "textRaw": "`env` {Object} An object similar to `process.env` that the WebAssembly application will see as its environment. **Default:** `{}`.", "name": "env", "type": "Object", "default": "`{}`", "desc": "An object similar to `process.env` that the WebAssembly application will see as its environment." }, { "textRaw": "`preopens` {Object} This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine.", "name": "preopens", "type": "Object", "desc": "This object represents the WebAssembly application's sandbox directory structure. The string keys of `preopens` are treated as directories within the sandbox. The corresponding values in `preopens` are the real paths to those directories on the host machine." }, { "textRaw": "`returnOnExit` {boolean} By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process. **Default:** `false`.", "name": "returnOnExit", "type": "boolean", "default": "`false`", "desc": "By default, WASI applications terminate the Node.js process via the `__wasi_proc_exit()` function. Setting this option to `true` causes `wasi.start()` to return the exit code rather than terminate the process." }, { "textRaw": "`stdin` {integer} The file descriptor used as standard input in the WebAssembly application. **Default:** `0`.", "name": "stdin", "type": "integer", "default": "`0`", "desc": "The file descriptor used as standard input in the WebAssembly application." }, { "textRaw": "`stdout` {integer} The file descriptor used as standard output in the WebAssembly application. **Default:** `1`.", "name": "stdout", "type": "integer", "default": "`1`", "desc": "The file descriptor used as standard output in the WebAssembly application." }, { "textRaw": "`stderr` {integer} The file descriptor used as standard error in the WebAssembly application. **Default:** `2`.", "name": "stderr", "type": "integer", "default": "`2`", "desc": "The file descriptor used as standard error in the WebAssembly application." } ] } ] } ] } ], "type": "module", "displayName": "WebAssembly System Interface (WASI)", "source": "doc/api/wasi.md" }, { "textRaw": "Web Crypto API", "name": "web_crypto_api", "introduced_in": "v15.0.0", "stability": 1, "stabilityText": "Experimental", "desc": "

Node.js provides an implementation of the standard Web Crypto API.

\n

Use require('crypto').webcrypto to access this module.

\n
const { subtle } = require('crypto').webcrypto;\n\n(async function() {\n\n  const key = await subtle.generateKey({\n    name: 'HMAC',\n    hash: 'SHA-256',\n    length: 256\n  }, true, ['sign', 'verify']);\n\n  const digest = await subtle.sign({\n    name: 'HMAC'\n  }, key, 'I love cupcakes');\n\n})();\n
\n

Examples

", "modules": [ { "textRaw": "Generating keys", "name": "generating_keys", "desc": "

The <SubtleCrypto> class can be used to generate symmetric (secret) keys\nor asymmetric key pairs (public key and private key).

", "modules": [ { "textRaw": "AES keys", "name": "aes_keys", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateAesKey(length = 256) {\n  const key = await subtle.generateKey({\n    name: 'AES-CBC',\n    length\n  }, true, ['encrypt', 'decrypt']);\n\n  return key;\n}\n
", "type": "module", "displayName": "AES keys" }, { "textRaw": "Elliptic curve key pairs", "name": "elliptic_curve_key_pairs", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateEcKey(namedCurve = 'P-521') {\n  const {\n    publicKey,\n    privateKey\n  } = await subtle.generateKey({\n    name: 'ECDSA',\n    namedCurve,\n  }, true, ['sign', 'verify']);\n\n  return { publicKey, privateKey };\n}\n
", "type": "module", "displayName": "Elliptic curve key pairs" }, { "textRaw": "ED25519/ED448/X25519/X448 Elliptic curve key pairs", "name": "ed25519/ed448/x25519/x448_elliptic_curve_key_pairs", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateEd25519Key() {\n  return subtle.generateKey({\n    name: 'NODE-ED25519',\n    namedCurve: 'NODE-ED25519',\n  }, true, ['sign', 'verify']);\n}\n\nasync function generateX25519Key() {\n  return subtle.generateKey({\n    name: 'ECDH',\n    namedCurve: 'NODE-X25519',\n  }, true, ['deriveKey']);\n}\n
", "type": "module", "displayName": "ED25519/ED448/X25519/X448 Elliptic curve key pairs" }, { "textRaw": "HMAC keys", "name": "hmac_keys", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateHmacKey(hash = 'SHA-256') {\n  const key = await subtle.generateKey({\n    name: 'HMAC',\n    hash\n  }, true, ['sign', 'verify']);\n\n  return key;\n}\n
", "type": "module", "displayName": "HMAC keys" }, { "textRaw": "RSA key pairs", "name": "rsa_key_pairs", "desc": "
const { subtle } = require('crypto').webcrypto;\nconst publicExponent = new Uint8Array([1, 0, 1]);\n\nasync function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') {\n  const {\n    publicKey,\n    privateKey\n  } = await subtle.generateKey({\n    name: 'RSASSA-PKCS1-v1_5',\n    modulusLength,\n    publicExponent,\n    hash,\n  }, true, ['sign', 'verify']);\n\n  return { publicKey, privateKey };\n}\n
", "type": "module", "displayName": "RSA key pairs" } ], "type": "module", "displayName": "Generating keys" }, { "textRaw": "Encryption and decryption", "name": "encryption_and_decryption", "desc": "
const { subtle, getRandomValues } = require('crypto').webcrypto;\n\nasync function aesEncrypt(plaintext) {\n  const ec = new TextEncoder();\n  const key = await generateAesKey();\n  const iv = getRandomValues(new Uint8Array(16));\n\n  const ciphertext = await subtle.encrypt({\n    name: 'AES-CBC',\n    iv,\n  }, key, ec.encode(plaintext));\n\n  return {\n    key,\n    iv,\n    ciphertext\n  };\n}\n\nasync function aesDecrypt(ciphertext, key, iv) {\n  const dec = new TextDecoder();\n  const plaintext = await subtle.decrypt({\n    name: 'AES-CBC',\n    iv,\n  }, key, ciphertext);\n\n  return dec.decode(plaintext);\n}\n
", "type": "module", "displayName": "Encryption and decryption" }, { "textRaw": "Exporting and importing keys", "name": "exporting_and_importing_keys", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') {\n  const key = await subtle.generateKey({\n    name: 'HMAC',\n    hash\n  }, true, ['sign', 'verify']);\n\n  return subtle.exportKey(format, key);\n}\n\nasync function importHmacKey(keyData, format = 'jwk', hash = 'SHA-512') {\n  const key = await subtle.importKey(format, keyData, {\n    name: 'HMAC',\n    hash\n  }, true, ['sign', 'verify']);\n\n  return key;\n}\n
", "type": "module", "displayName": "Exporting and importing keys" }, { "textRaw": "Wrapping and unwrapping keys", "name": "wrapping_and_unwrapping_keys", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function generateAndWrapHmacKey(format = 'jwk', hash = 'SHA-512') {\n  const [\n    key,\n    wrappingKey,\n  ] = await Promise.all([\n    subtle.generateKey({\n      name: 'HMAC', hash\n    }, true, ['sign', 'verify']),\n    subtle.generateKey({\n      name: 'AES-KW',\n      length: 256\n    }, true, ['wrapKey', 'unwrapKey']),\n  ]);\n\n  const wrappedKey = await subtle.wrapKey(format, key, wrappingKey, 'AES-KW');\n\n  return wrappedKey;\n}\n\nasync function unwrapHmacKey(\n  wrappedKey,\n  wrappingKey,\n  format = 'jwk',\n  hash = 'SHA-512') {\n\n  const key = await subtle.unwrapKey(\n    format,\n    wrappedKey,\n    unwrappingKey,\n    'AES-KW',\n    { name: 'HMAC', hash },\n    true,\n    ['sign', 'verify']);\n\n  return key;\n}\n
", "type": "module", "displayName": "Wrapping and unwrapping keys" }, { "textRaw": "Sign and verify", "name": "sign_and_verify", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function sign(key, data) {\n  const ec = new TextEncoder();\n  const signature =\n    await subtle.sign('RSASSA-PKCS1-v1_5', key, ec.encode(data));\n  return signature;\n}\n\nasync function verify(key, signature, data) {\n  const ec = new TextEncoder();\n  const verified =\n    await subtle.verify(\n      'RSASSA-PKCS1-v1_5',\n      key,\n      signature,\n      ec.encode(data));\n  return verified;\n}\n
", "type": "module", "displayName": "Sign and verify" }, { "textRaw": "Deriving bits and keys", "name": "deriving_bits_and_keys", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function pbkdf2(pass, salt, iterations = 1000, length = 256) {\n  const ec = new TextEncoder();\n  const key = await subtle.importKey(\n    'raw',\n    ec.encode(pass),\n    'PBKDF2',\n    false,\n    ['deriveBits']);\n  const bits = await subtle.deriveBits({\n    name: 'PBKDF2',\n    hash: 'SHA-512',\n    salt: ec.encode(salt),\n    iterations\n  }, key, length);\n  return bits;\n}\n\nasync function pbkdf2Key(pass, salt, iterations = 1000, length = 256) {\n  const ec = new TextEncoder();\n  const keyMaterial = await subtle.importKey(\n    'raw',\n    ec.encode(pass),\n    'PBKDF2',\n    false,\n    ['deriveKey']);\n  const key = await subtle.deriveKey({\n    name: 'PBKDF2',\n    hash: 'SHA-512',\n    salt: ec.encode(salt),\n    iterations\n  }, keyMaterial, {\n    name: 'AES-GCM',\n    length: 256\n  }, true, ['encrypt', 'decrypt']);\n  return key;\n}\n
", "type": "module", "displayName": "Deriving bits and keys" }, { "textRaw": "Digest", "name": "digest", "desc": "
const { subtle } = require('crypto').webcrypto;\n\nasync function digest(data, algorithm = 'SHA-512') {\n  const ec = new TextEncoder();\n  const digest = await subtle.digest(algorithm, ec.encode(data));\n  return digest;\n}\n
", "type": "module", "displayName": "Digest" }, { "textRaw": "Algorithm Matrix", "name": "algorithm_matrix", "desc": "

The table details the algorithms supported by the Node.js Web Crypto API\nimplementation and the APIs supported for each:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
AlgorithmgenerateKeyexportKeyimportKeyencryptdecryptwrapKeyunwrapKeyderiveBitsderiveKeysignverifydigest
'RSASSA-PKCS1-v1_5'
'RSA-PSS'
'RSA-OAEP'
'ECDSA'
'ECDH'
'AES-CTR'
'AES-CBC'
'AES-GCM'
'AES-KW'
'HMAC'
'HKDF'
'PBKDF2'
'SHA-1'
'SHA-256'
'SHA-384'
'SHA-512'
'NODE-DSA'1
'NODE-DH'1
'NODE-ED25519'1
'NODE-ED448'1
\n

1 Node.js-specific extension

", "type": "module", "displayName": "Algorithm Matrix" }, { "textRaw": "Algorithm Parameters", "name": "algorithm_parameters", "desc": "

The algorithm parameter objects define the methods and parameters used by\nthe various <SubtleCrypto> methods. While described here as \"classes\", they\nare simple JavaScript dictionary objects.

", "classes": [ { "textRaw": "Class: `AesCbcParams`", "type": "class", "name": "AesCbcParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`iv` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Provides the initialization vector. It must be exactly 16-bytes in length\nand should be unpredictable and cryptographically random.

" }, { "textRaw": "`name` Type: {string} Must be `'AES-CBC'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'AES-CBC'`." } ] }, { "textRaw": "Class: `AesCtrParams`", "type": "class", "name": "AesCtrParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`counter` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The initial value of the counter block. This must be exactly 16 bytes long.

\n

The AES-CTR method uses the rightmost length bits of the block as the\ncounter and the remaining bits as the nonce.

" }, { "textRaw": "`length` Type: {number} The number of bits in the `aesCtrParams.counter` that are to be used as the counter.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The number of bits in the `aesCtrParams.counter` that are to be used as the counter." }, { "textRaw": "`name` Type: {string} Must be `'AES-CTR'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'AES-CTR'`." } ] }, { "textRaw": "Class: `AesGcmParams`", "type": "class", "name": "AesGcmParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`additionalData` Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined}", "type": "ArrayBuffer|TypedArray|DataView|Buffer|undefined", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

With the AES-GCM method, the additionalData is extra input that is not\nencrypted but is included in the authentication of the data. The use of\nadditionalData is optional.

" }, { "textRaw": "`iv` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The initialization vector must be unique for every encryption operation\nusing a given key. It is recommended by the AES-GCM specification that\nthis contain at least 12 random bytes.

" }, { "textRaw": "`name` Type: {string} Must be `'AES-GCM'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'AES-GCM'`." }, { "textRaw": "`tagLength` Type: {number} The size in bits of the generated authentication tag. This values must be one of `32`, `64`, `96`, `104`, `112`, `120`, or `128`. **Default:** `128`.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "default": "`128`", "desc": "The size in bits of the generated authentication tag. This values must be one of `32`, `64`, `96`, `104`, `112`, `120`, or `128`." } ] }, { "textRaw": "Class: `AesImportParams`", "type": "class", "name": "AesImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be one of `'AES-CTR'`, `'AES-CBC'`, `'AES-GCM'`, or `'AES-KW'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'AES-CTR'`, `'AES-CBC'`, `'AES-GCM'`, or `'AES-KW'`." } ] }, { "textRaw": "Class: `AesKeyGenParams`", "type": "class", "name": "AesKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`length` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The length of the AES key to be generated. This must be either 128, 192,\nor 256.

" }, { "textRaw": "`name` Type: {string} Must be one of `'AES-CBC'`, `'AES-CTR'`, `'AES-GCM'`, or `'AES-KW'`", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'AES-CBC'`, `'AES-CTR'`, `'AES-GCM'`, or `'AES-KW'`" } ] }, { "textRaw": "Class: `AesKwParams`", "type": "class", "name": "AesKwParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'AES-KW'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'AES-KW'`." } ] }, { "textRaw": "Class: `EcdhKeyDeriveParams`", "type": "class", "name": "EcdhKeyDeriveParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'ECDH'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'ECDH'`." }, { "textRaw": "`public` Type: {CryptoKey}", "type": "CryptoKey", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

ECDH key derivation operates by taking as input one parties private key and\nanother parties public key -- using both to generate a common shared secret.\nThe ecdhKeyDeriveParams.public property is set to the other parties public\nkey.

" } ] }, { "textRaw": "Class: `EcdsaParams`", "type": "class", "name": "EcdsaParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`name` Type: {string} Must be `'ECDSA'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'ECDSA'`." } ] }, { "textRaw": "Class: `EcKeyGenParams`", "type": "class", "name": "EcKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be one of `'ECDSA'` or `'ECDH'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'ECDSA'` or `'ECDH'`." }, { "textRaw": "`namedCurve` Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`, `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'P-256'`, `'P-384'`, `'P-521'`, `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`." } ] }, { "textRaw": "Class: `EcKeyImportParams`", "type": "class", "name": "EcKeyImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be one of `'ECDSA'` or `'ECDH'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'ECDSA'` or `'ECDH'`." }, { "textRaw": "`namedCurve` Type: {string} Must be one of `'P-256'`, `'P-384'`, `'P-521'`, `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'P-256'`, `'P-384'`, `'P-521'`, `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`." } ] }, { "textRaw": "Class: `HkdfParams`", "type": "class", "name": "HkdfParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`info` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Provides application-specific contextual input to the HKDF algorithm.\nThis can be zero-length but must be provided.

" }, { "textRaw": "`name` Type: {string} Must be `'HKDF'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'HKDF'`." }, { "textRaw": "`salt` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The salt value significantly improves the strength of the HKDF algorithm.\nIt should be random or pseudorandom and should be the same length as the\noutput of the digest function (for instance, if using 'SHA-256' as the\ndigest, the salt should be 256-bits of random data).

" } ] }, { "textRaw": "Class: `HmacImportParams`", "type": "class", "name": "HmacImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "modules": [ { "textRaw": "'hmacImportParams.hash`", "name": "'hmacimportparams.hash`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "\n

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

", "type": "module", "displayName": "'hmacImportParams.hash`" } ], "properties": [ { "textRaw": "`length` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The optional number of bits in the HMAC key. This is optional and should\nbe omitted for most cases.

" }, { "textRaw": "`name` Type: {string} Must be `'HMAC'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'HMAC'`." } ] }, { "textRaw": "Class: `HmacKeyGenParams`", "type": "class", "name": "HmacKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`length` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The number of bits to generate for the HMAC key. If omitted,\nthe length will be determined by the hash algorithm used.\nThis is optional and should be omitted for most cases.

" }, { "textRaw": "`name` Type: {string} Must be `'HMAC'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'HMAC'`." } ] }, { "textRaw": "Class: `HmacParams`", "type": "class", "name": "HmacParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'HMAC'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'HMAC'`." } ] }, { "textRaw": "Class: `Pbkdf2ImportParams`", "type": "class", "name": "Pbkdf2ImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'PBKDF2'`", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'PBKDF2'`" } ] }, { "textRaw": "Class: `Pbkdf2Params`", "type": "class", "name": "Pbkdf2Params", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`iterations` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The number of iterations the PBKDF2 algorithm should make when deriving bits.

" }, { "textRaw": "`name` Type: {string} Must be `'PBKDF2'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'PBKDF2'`." }, { "textRaw": "`salt` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Should be at least 16 random or pseudorandom bytes.

" } ] }, { "textRaw": "Class: `RsaHashedImportParams`", "type": "class", "name": "RsaHashedImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`name` Type: {string} Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`." } ] }, { "textRaw": "Class: `RsaHashedKeyGenParams`", "type": "class", "name": "RsaHashedKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`modulusLength` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The length in bits of the RSA modulus. As a best practice, this should be\nat least 2048.

" }, { "textRaw": "`name` Type: {string} Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or `'RSA-OAEP'`." }, { "textRaw": "`publicExponent` Type: {Uint8Array}", "type": "Uint8Array", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The RSA public exponent. This must be a <Uint8Array> containing a big-endian,\nunsigned integer that must fit within 32-bits. The <Uint8Array> may contain an\narbitrary number of leading zero-bits. The value must be a prime number. Unless\nthere is reason to use a different value, use new Uint8Array([1, 0, 1])\n(65537) as the public exponent.

" } ] }, { "textRaw": "Class: `RsaOaepParams`", "type": "class", "name": "RsaOaepParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`label` Type: {ArrayBuffer|TypedArray|DataView|Buffer}", "type": "ArrayBuffer|TypedArray|DataView|Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An additional collection of bytes that will not be encrypted, but will be bound\nto the generated ciphertext.

\n

The rsaOaepParams.label parameter is optional.

" }, { "textRaw": "`name` Type: {string} must be `'RSA-OAEP'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "must be `'RSA-OAEP'`." } ] }, { "textRaw": "Class: `RsaPssParams`", "type": "class", "name": "RsaPssParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'RSA-PSS'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'RSA-PSS'`." }, { "textRaw": "`saltLength` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The length (in bytes) of the random salt to use.

" } ] }, { "textRaw": "Class: `RsaSignParams`", "type": "class", "name": "RsaSignParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'RSASSA-PKCS1-v1_5'`", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'RSASSA-PKCS1-v1_5'`" } ] } ], "type": "module", "displayName": "Algorithm Parameters" }, { "textRaw": "Node.js-specific extensions", "name": "node.js-specific_extensions", "desc": "

The Node.js Web Crypto API extends various aspects of the Web Crypto API.\nThese extensions are consistently identified by prepending names with the\nnode. prefix. For instance, the 'node.keyObject' key format can be\nused with the subtle.exportKey() and subtle.importKey() methods to\nconvert between a WebCrypto <CryptoKey> object and a Node.js <KeyObject>.

\n

Care should be taken when using Node.js-specific extensions as they are\nnot supported by other WebCrypto implementations and reduce the portability\nof code to other environments.

", "modules": [ { "textRaw": "`NODE-DH` Algorithm", "name": "`node-dh`_algorithm", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The NODE-DH algorithm is the common implementation of Diffie-Hellman\nkey agreement.

", "classes": [ { "textRaw": "Class: `NodeDhImportParams`", "type": "class", "name": "NodeDhImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'NODE-DH'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'NODE-DH'`." } ] }, { "textRaw": "Class: NodeDhKeyGenParams`", "type": "class", "name": "NodeDhKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`generator` Type: {number} A custom generator.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "A custom generator." }, { "textRaw": "`group` Type: {string} The Diffie-Hellman group name.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The Diffie-Hellman group name." }, { "textRaw": "`prime` Type: {Buffer} The prime parameter.", "type": "Buffer", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The prime parameter." }, { "textRaw": "`primeLength` Type: {number} The length in bits of the prime.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The length in bits of the prime." } ] }, { "textRaw": "Class: NodeDhDeriveBitsParams", "type": "class", "name": "NodeDhDeriveBitsParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`public` Type: {CryptoKey} The other parties public key.", "type": "CryptoKey", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The other parties public key." } ] } ], "type": "module", "displayName": "`NODE-DH` Algorithm" }, { "textRaw": "`NODE-DSA` Algorithm", "name": "`node-dsa`_algorithm", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The NODE-DSA algorithm is the common implementation of the DSA digital\nsignature algorithm.

", "classes": [ { "textRaw": "Class: `NodeDsaImportParams`", "type": "class", "name": "NodeDsaImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`name` Type: {string} Must be `'NODE-DSA'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'NODE-DSA'`." } ] }, { "textRaw": "Class: `NodeDsaKeyGenParams`", "type": "class", "name": "NodeDsaKeyGenParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`divisorLength` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The optional length in bits of the DSA divisor.

" }, { "textRaw": "`hash` Type: {string|Object}", "type": "string|Object", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

If represented as a <string>, the value must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.

" }, { "textRaw": "`modulusLength` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The length in bits of the DSA modulus. As a best practice, this should be\nat least 2048.

" }, { "textRaw": "`name` Type: {string} Must be `'NODE-DSA'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'NODE-DSA'`." } ] }, { "textRaw": "Class: `NodeDsaSignParams`", "type": "class", "name": "NodeDsaSignParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'NODE-DSA'`", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'NODE-DSA'`" } ] } ], "type": "module", "displayName": "`NODE-DSA` Algorithm" }, { "textRaw": "`NODE-ED25519` and `NODE-ED448` Algorithms", "name": "`node-ed25519`_and_`node-ed448`_algorithms", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "classes": [ { "textRaw": "Class: `NodeEdKeyGenParams`", "type": "class", "name": "NodeEdKeyGenParams", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'` or `'ECDH'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "desc": "Must be one of `'NODE-ED25519'`, `'NODE-ED448'` or `'ECDH'`." }, { "textRaw": "`namedCurve` Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "desc": "Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`." } ] }, { "textRaw": "Class: `NodeEdKeyImportParams`", "type": "class", "name": "NodeEdKeyImportParams", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be one of `'NODE-ED25519'` or `'NODE-ED448'` if importing an `Ed25519` or `Ed448` key, or `'ECDH'` if importing an `X25519` or `X448` key.", "type": "string", "name": "Type", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "desc": "Must be one of `'NODE-ED25519'` or `'NODE-ED448'` if importing an `Ed25519` or `Ed448` key, or `'ECDH'` if importing an `X25519` or `X448` key." }, { "textRaw": "`namedCurve` Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "desc": "Must be one of `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`." }, { "textRaw": "`public` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "desc": "

The public parameter is used to specify that the 'raw' format key is to be\ninterpreted as a public key. Default: false.

" } ] } ], "type": "module", "displayName": "`NODE-ED25519` and `NODE-ED448` Algorithms" }, { "textRaw": "`NODE-SCRYPT` Algorithm", "name": "`node-scrypt`_algorithm", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The NODE-SCRYPT algorithm is the common implementation of the scrypt key\nderivation algorithm.

", "classes": [ { "textRaw": "Class: `NodeScryptImportParams`", "type": "class", "name": "NodeScryptImportParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`name` Type: {string} Must be `'NODE-SCRYPT'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "Must be `'NODE-SCRYPT'`." } ] }, { "textRaw": "Class: `NodeScryptParams`", "type": "class", "name": "NodeScryptParams", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`encoding` Type: {string} The string encoding when `salt` is a string.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "The string encoding when `salt` is a string." }, { "textRaw": "`maxmem` Type: {number} Memory upper bound. It is an error when (approximately) `127 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "default": "`32 * 1024 * 1024`", "desc": "Memory upper bound. It is an error when (approximately) `127 * N * r > maxmem`." }, { "textRaw": "`N` Type: {number} The CPU/memory cost parameter. Must e a power of two greater than 1. **Default:** `16384`.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "default": "`16384`", "desc": "The CPU/memory cost parameter. Must e a power of two greater than 1." }, { "textRaw": "`p` Type: {number} Parallelization parameter. **Default:** `1`.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "default": "`1`", "desc": "Parallelization parameter." }, { "textRaw": "`r` Type: {number} Block size parameter. **Default:** `8`.", "type": "number", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "default": "`8`", "desc": "Block size parameter." }, { "textRaw": "`salt` Type: {string|ArrayBuffer|Buffer|TypedArray|DataView}", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] } } ] } ], "type": "module", "displayName": "`NODE-SCRYPT` Algorithm" } ], "type": "module", "displayName": "Node.js-specific extensions" } ], "classes": [ { "textRaw": "Class: `Crypto`", "type": "class", "name": "Crypto", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Calling require('crypto').webcrypto returns an instance of the Crypto class.\nCrypto is a singleton that provides access to the remainder of the crypto API.

", "properties": [ { "textRaw": "`subtle` Type: {SubtleCrypto}", "type": "SubtleCrypto", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

Provides access to the SubtleCrypto API.

" } ], "methods": [ { "textRaw": "`crypto.getRandomValues(typedArray)`", "type": "method", "name": "getRandomValues", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|TypedArray|DataView|ArrayBuffer} Returns `typedArray`.", "name": "return", "type": "Buffer|TypedArray|DataView|ArrayBuffer", "desc": "Returns `typedArray`." }, "params": [ { "textRaw": "`typedArray` {Buffer|TypedArray|DataView|ArrayBuffer}", "name": "typedArray", "type": "Buffer|TypedArray|DataView|ArrayBuffer" } ] } ], "desc": "

Generates cryptographically strong random values. The given typedArray is\nfilled with random values, and a reference to typedArray is returned.

\n

An error will be thrown if the given typedArray is larger than 65,536 bytes.

" }, { "textRaw": "`crypto.randomUUID()`", "type": "method", "name": "randomUUID", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

Generates a random RFC 4122 version 4 UUID. The UUID is generated using a\ncryptographic pseudorandom number generator.

" } ] }, { "textRaw": "Class: `CryptoKey`", "type": "class", "name": "CryptoKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "properties": [ { "textRaw": "`cryptoKey.algorithm`", "name": "algorithm", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "\n\n\n

An object detailing the algorithm for which the key can be used along with\nadditional algorithm-specific parameters.

\n

Read-only.

" }, { "textRaw": "`extractable` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

When true, the <CryptoKey> can be extracted using either\nsubtleCrypto.exportKey() or subtleCrypto.wrapKey().

\n

Read-only.

" }, { "textRaw": "`type` Type: {string} One of `'secret'`, `'private'`, or `'public'`.", "type": "string", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

A string identifying whether the key is a symmetric ('secret') or\nasymmetric ('private' or 'public') key.

", "shortDesc": "One of `'secret'`, `'private'`, or `'public'`." }, { "textRaw": "`usages` Type: {string[]}", "type": "string[]", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An array of strings identifying the operations for which the\nkey may be used.

\n

The possible usages are:

\n
    \n
  • 'encrypt' - The key may be used to encrypt data.
  • \n
  • 'decrypt' - The key may be used to decrypt data.
  • \n
  • 'sign' - The key may be used to generate digital signatures.
  • \n
  • 'verify' - The key may be used to verify digital signatures.
  • \n
  • 'deriveKey' - The key may be used to derive a new key.
  • \n
  • 'deriveBits' - The key may be used to derive bits.
  • \n
  • 'wrapKey' - The key may be used to wrap another key.
  • \n
  • 'unwrapKey' - The key may be used to unwrap another key.
  • \n
\n

Valid key usages depend on the key algorithm (identified by\ncryptokey.algorithm.name).

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Key Type'encrypt''decrypt''sign''verify''deriveKey''deriveBits''wrapKey''unwrapKey'
'AES-CBC'
'AES-CTR'
'AES-GCM'
'AES-KW'
'ECDH'
'ECDSA'
'HDKF'
'HMAC'
'PBKDF2'
'RSA-OAEP'
'RSA-PSS'
'RSASSA-PKCS1-v1_5'
'NODE-DSA' 1
'NODE-DH' 1
'NODE-SCRYPT' 1
'NODE-ED25519' 1
'NODE-ED448' 1
\n

1 Node.js-specific extension.

" } ] }, { "textRaw": "Class: `CryptoKeyPair`", "type": "class", "name": "CryptoKeyPair", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

The CryptoKeyPair is a simple dictionary object with publicKey and\nprivateKey properties, representing an asymmetric key pair.

", "properties": [ { "textRaw": "`privateKey` Type: {CryptoKey} A {CryptoKey} whose `type` will be `'private'`.", "type": "CryptoKey", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "A {CryptoKey} whose `type` will be `'private'`." }, { "textRaw": "`publicKey` Type: {CryptoKey} A {CryptoKey} whose `type` will be `'public'`.", "type": "CryptoKey", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "A {CryptoKey} whose `type` will be `'public'`." } ] }, { "textRaw": "Class: `SubtleCrypto`", "type": "class", "name": "SubtleCrypto", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "methods": [ { "textRaw": "`subtle.decrypt(algorithm, key, data)`", "type": "method", "name": "decrypt", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {ArrayBuffer}", "name": "return", "type": "Promise", "desc": "containing {ArrayBuffer}" }, "params": [ { "textRaw": "`algorithm`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams}", "name": "algorithm", "type": "RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams" }, { "textRaw": "`key`: {CryptoKey}", "name": "key", "type": "CryptoKey" }, { "textRaw": "`data`: {ArrayBuffer|TypedArray|DataView|Buffer}", "name": "data", "type": "ArrayBuffer|TypedArray|DataView|Buffer" } ] } ], "desc": "

Using the method and parameters specified in algorithm and the keying\nmaterial provided by key, subtle.decrypt() attempts to decipher the\nprovided data. If successful, the returned promise will be resolved with\nan <ArrayBuffer> containing the plaintext result.

\n

The algorithms currently supported include:

\n
    \n
  • 'RSA-OAEP'
  • \n
  • 'AES-CTR'
  • \n
  • 'AES-CBC'
  • \n
  • 'AES-GCM'
  • \n
" }, { "textRaw": "`subtle.deriveBits(algorithm, baseKey, length)`", "type": "method", "name": "deriveBits", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Using the method and parameters specified in algorithm and the keying\nmaterial provided by baseKey, subtle.deriveBits() attempts to generate\nlength bits. The Node.js implementation requires that length is a\nmultiple of 8. If successful, the returned promise will be resolved with\nan <ArrayBuffer> containing the generated data.

\n

The algorithms currently supported include:

\n
    \n
  • 'ECDH'
  • \n
  • 'HKDF'
  • \n
  • 'PBKDF2'
  • \n
  • 'NODE-DH'1
  • \n
  • 'NODE-SCRYPT'1
  • \n
\n

1 Node.js-specific extension

" }, { "textRaw": "`subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)`", "type": "method", "name": "deriveKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Using the method and parameters specified in algorithm, and the keying\nmaterial provided by baseKey, subtle.deriveKey() attempts to generate\na new <CryptoKey> based on the method and parameters in derivedKeyAlgorithm.

\n

Calling subtle.deriveKey() is equivalent to calling subtle.deriveBits() to\ngenerate raw keying material, then passing the result into the\nsubtle.importKey() method using the deriveKeyAlgorithm, extractable, and\nkeyUsages parameters as input.

\n

The algorithms currently supported include:

\n
    \n
  • 'ECDH'
  • \n
  • 'HKDF'
  • \n
  • 'PBKDF2'
  • \n
  • 'NODE-DH'1
  • \n
  • 'NODE-SCRYPT'1
  • \n
\n

1 Node.js-specific extension

" }, { "textRaw": "`subtle.digest(algorithm, data)`", "type": "method", "name": "digest", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {ArrayBuffer}", "name": "return", "type": "Promise", "desc": "containing {ArrayBuffer}" }, "params": [ { "textRaw": "`algorithm`: {string|Object}", "name": "algorithm", "type": "string|Object" }, { "textRaw": "`data`: {ArrayBuffer|TypedArray|DataView|Buffer}", "name": "data", "type": "ArrayBuffer|TypedArray|DataView|Buffer" } ] } ], "desc": "

Using the method identified by algorithm, subtle.digest() attempts to\ngenerate a digest of data. If successful, the returned promise is resolved\nwith an <ArrayBuffer> containing the computed digest.

\n

If algorithm is provided as a <string>, it must be one of:

\n
    \n
  • 'SHA-1'
  • \n
  • 'SHA-256'
  • \n
  • 'SHA-384'
  • \n
  • 'SHA-512'
  • \n
\n

If algorithm is provided as an <Object>, it must have a name property\nwhose value is one of the above.

" }, { "textRaw": "`subtle.encrypt(algorithm, key, data)`", "type": "method", "name": "encrypt", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {ArrayBuffer}", "name": "return", "type": "Promise", "desc": "containing {ArrayBuffer}" }, "params": [ { "textRaw": "`algorithm`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams}", "name": "algorithm", "type": "RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams" }, { "textRaw": "`key`: {CryptoKey}", "name": "key", "type": "CryptoKey" } ] } ], "desc": "

Using the method and parameters specified by algorithm and the keying\nmaterial provided by key, subtle.encrypt() attempts to encipher data.\nIf successful, the returned promise is resolved with an <ArrayBuffer>\ncontaining the encrypted result.

\n

The algorithms currently supported include:

\n
    \n
  • 'RSA-OAEP'
  • \n
  • 'AES-CTR'
  • \n
  • 'AES-CBC'
  • \n
  • 'AES-GCM'
  • \n
" }, { "textRaw": "`subtle.exportKey(format, key)`", "type": "method", "name": "exportKey", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37203", "description": "Removed `'NODE-DSA'` JWK export." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {ArrayBuffer}, or, if `format` is `'node.keyObject'`, a {KeyObject}.", "name": "return", "type": "Promise", "desc": "containing {ArrayBuffer}, or, if `format` is `'node.keyObject'`, a {KeyObject}." }, "params": [ { "textRaw": "`format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or `'node.keyObject'`.", "name": "format", "type": "string", "desc": "Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or `'node.keyObject'`." }, { "textRaw": "`key`: {CryptoKey}", "name": "key", "type": "CryptoKey" } ] } ], "desc": "

Exports the given key into the specified format, if supported.

\n

If the <CryptoKey> is not extractable, the returned promise will reject.

\n

When format is either 'pkcs8' or 'spki' and the export is successful,\nthe returned promise will be resolved with an <ArrayBuffer> containing the\nexported key data.

\n

When format is 'jwk' and the export is successful, the returned promise\nwill be resolved with a JavaScript object conforming to the JSON Web Key\nspecification.

\n

The special 'node.keyObject' value for format is a Node.js-specific\nextension that allows converting a <CryptoKey> into a Node.js <KeyObject>.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Key Type'spki''pkcs8''jwk''raw'
'AES-CBC'
'AES-CTR'
'AES-GCM'
'AES-KW'
'ECDH'
'ECDSA'
'HDKF'
'HMAC'
'PBKDF2'
'RSA-OAEP'
'RSA-PSS'
'RSASSA-PKCS1-v1_5'
'NODE-DSA' 1
'NODE-DH' 1
'NODE-SCRYPT' 1
'NODE-ED25519' 1
'NODE-ED448' 1
\n

1 Node.js-specific extension

" }, { "textRaw": "`subtle.generateKey(algorithm, extractable, keyUsages)`", "type": "method", "name": "generateKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n\n

Using the method and parameters provided in algorithm, subtle.generateKey()\nattempts to generate new keying material. Depending the method used, the method\nmay generate either a single <CryptoKey> or a <CryptoKeyPair>.

\n

The <CryptoKeyPair> (public and private key) generating algorithms supported\ninclude:

\n
    \n
  • 'RSASSA-PKCS1-v1_5'
  • \n
  • 'RSA-PSS'
  • \n
  • 'RSA-OAEP'
  • \n
  • 'ECDSA'
  • \n
  • 'ECDH'
  • \n
  • 'NODE-DSA' 1
  • \n
  • 'NODE-DH' 1
  • \n
  • 'NODE-ED25519' 1
  • \n
  • 'NODE-ED448' 1
  • \n
\n

The <CryptoKey> (secret key) generating algorithms supported include:

\n
    \n
  • 'HMAC'
  • \n
  • 'AES-CTR'
  • \n
  • 'AES-CBC'
  • \n
  • 'AES-GCM'
  • \n
  • 'AES-KW'
  • \n
\n

1 Non-standard Node.js extension

" }, { "textRaw": "`subtle.importKey(format, keyData, algorithm, extractable, keyUsages)`", "type": "method", "name": "importKey", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37203", "description": "Removed `'NODE-DSA'` JWK import." } ] }, "signatures": [ { "params": [ { "textRaw": "`format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or `'node.keyObject'`.", "name": "format", "type": "string", "desc": "Must be one of `'raw'`, `'pkcs8'`, `'spki'`, `'jwk'`, or `'node.keyObject'`." }, { "textRaw": "`keyData`: {ArrayBuffer|TypedArray|DataView|Buffer|KeyObject}", "name": "keyData", "type": "ArrayBuffer|TypedArray|DataView|Buffer|KeyObject" } ] } ], "desc": "\n\n\n\n

The subtle.importKey() method attempts to interpret the provided keyData\nas the given format to create a <CryptoKey> instance using the provided\nalgorithm, extractable, and keyUsages arguments. If the import is\nsuccessful, the returned promise will be resolved with the created <CryptoKey>.

\n

The special 'node.keyObject' value for format is a Node.js-specific\nextension that allows converting a Node.js <KeyObject> into a <CryptoKey>.

\n

If importing a 'PBKDF2' key, extractable must be false.

\n

The algorithms currently supported include:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Key Type'spki''pkcs8''jwk''raw'
'AES-CBC'
'AES-CTR'
'AES-GCM'
'AES-KW'
'ECDH'
'ECDSA'
'HDKF'
'HMAC'
'PBKDF2'
'RSA-OAEP'
'RSA-PSS'
'RSASSA-PKCS1-v1_5'
'NODE-DSA' 1
'NODE-DH' 1
'NODE-SCRYPT' 1
'NODE-ED25519' 1
'NODE-ED448' 1
\n

1 Node.js-specific extension

" }, { "textRaw": "`subtle.sign(algorithm, key, data)`", "type": "method", "name": "sign", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Using the method and parameters given by algorithm and the keying material\nprovided by key, subtle.sign() attempts to generate a cryptographic\nsignature of data. If successful, the returned promise is resolved with\nan <ArrayBuffer> containing the generated signature.

\n

The algorithms currently supported include:

\n
    \n
  • 'RSASSA-PKCS1-v1_5'
  • \n
  • 'RSA-PSS'
  • \n
  • 'ECDSA'
  • \n
  • 'HMAC'
  • \n
  • 'NODE-DSA'1
  • \n
  • 'NODE-ED25519'1
  • \n
  • 'NODE-ED448'1
  • \n
\n

1 Non-standard Node.js extension

" }, { "textRaw": "`subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)`", "type": "method", "name": "unwrapKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.", "name": "format", "type": "string", "desc": "Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`." }, { "textRaw": "`wrappedKey`: {ArrayBuffer|TypedArray|DataView|Buffer}", "name": "wrappedKey", "type": "ArrayBuffer|TypedArray|DataView|Buffer" }, { "textRaw": "`unwrappingKey`: {CryptoKey}", "name": "unwrappingKey", "type": "CryptoKey" } ] } ], "desc": "\n\n\n\n

In cryptography, \"wrapping a key\" refers to exporting and then encrypting the\nkeying material. The subtle.unwrapKey() method attempts to decrypt a wrapped\nkey and create a <CryptoKey> instance. It is equivalent to calling\nsubtle.decrypt() first on the encrypted key data (using the wrappedKey,\nunwrapAlgo, and unwrappingKey arguments as input) then passing the results\nin to the subtle.importKey() method using the unwrappedKeyAlgo,\nextractable, and keyUsages arguments as inputs. If successful, the returned\npromise is resolved with a <CryptoKey> object.

\n

The wrapping algorithms currently supported include:

\n
    \n
  • 'RSA-OAEP'
  • \n
  • 'AES-CTR'1
  • \n
  • 'AES-CBC'1
  • \n
  • 'AES-GCM'1
  • \n
  • 'AES-KW'1
  • \n
\n

The unwrapped key algorithms supported include:

\n
    \n
  • 'RSASSA-PKCS1-v1_5'
  • \n
  • 'RSA-PSS'
  • \n
  • 'RSA-OAEP'
  • \n
  • 'ECDSA'
  • \n
  • 'ECDH'
  • \n
  • 'HMAC'
  • \n
  • 'AES-CTR'
  • \n
  • 'AES-CBC'
  • \n
  • 'AES-GCM'
  • \n
  • 'AES-KW'
  • \n
  • 'NODE-DSA'1
  • \n
  • 'NODE-DH'1
  • \n
\n

1 Non-standard Node.js extension

" }, { "textRaw": "`subtle.verify(algorithm, key, signature, data)`", "type": "method", "name": "verify", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Using the method and parameters given in algorithm and the keying material\nprovided by key, subtle.verify() attempts to verify that signature is\na valid cryptographic signature of data. The returned promise is resolved\nwith either true or false.

\n

The algorithms currently supported include:

\n
    \n
  • 'RSASSA-PKCS1-v1_5'
  • \n
  • 'RSA-PSS'
  • \n
  • 'ECDSA'
  • \n
  • 'HMAC'
  • \n
  • 'NODE-DSA'1
  • \n
  • 'NODE-ED25519'1
  • \n
  • 'NODE-ED448'1
  • \n
\n

1 Non-standard Node.js extension

" }, { "textRaw": "`subtle.wrapKey(format, key, wrappingKey, wrapAlgo)`", "type": "method", "name": "wrapKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} containing {ArrayBuffer}", "name": "return", "type": "Promise", "desc": "containing {ArrayBuffer}" }, "params": [ { "textRaw": "`format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.", "name": "format", "type": "string", "desc": "Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`." }, { "textRaw": "`key`: {CryptoKey}", "name": "key", "type": "CryptoKey" }, { "textRaw": "`wrappingKey`: {CryptoKey}", "name": "wrappingKey", "type": "CryptoKey" }, { "textRaw": "`wrapAlgo`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams}", "name": "wrapAlgo", "type": "RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams" } ] } ], "desc": "

In cryptography, \"wrapping a key\" refers to exporting and then encrypting the\nkeying material. The subtle.wrapKey() method exports the keying material into\nthe format identified by format, then encrypts it using the method and\nparameters specified by wrapAlgo and the keying material provided by\nwrappingKey. It is the equivalent to calling subtle.exportKey() using\nformat and key as the arguments, then passing the result to the\nsubtle.encrypt() method using wrappingKey and wrapAlgo as inputs. If\nsuccessful, the returned promise will be resolved with an <ArrayBuffer>\ncontaining the encrypted key data.

\n

The wrapping algorithms currently supported include:

\n
    \n
  • 'RSA-OAEP'
  • \n
  • 'AES-CTR'
  • \n
  • 'AES-CBC'
  • \n
  • 'AES-GCM'
  • \n
  • 'AES-KW'
  • \n
" } ] } ], "type": "module", "displayName": "Web Crypto API", "source": "doc/api/webcrypto.md" }, { "textRaw": "Web Streams API", "name": "web_streams_api", "introduced_in": "v16.5.0", "stability": 1, "stabilityText": "Experimental", "desc": "

An implementation of the WHATWG Streams Standard.

\n
import {\n  ReadableStream,\n  WritableStream,\n  TransformStream,\n} from 'node:stream/web';\n
\n
const {\n  ReadableStream,\n  WritableStream,\n  TransformStream,\n} = require('stream/web');\n
", "modules": [ { "textRaw": "Overview", "name": "overview", "desc": "

The WHATWG Streams Standard (or \"web streams\") defines an API for handling\nstreaming data. It is similar to the Node.js Streams API but emerged later\nand has become the \"standard\" API for streaming data across many JavaScript\nenvironments.

\n

There are three primary types of objects

\n
    \n
  • ReadableStream - Represents a source of streaming data.
  • \n
  • WritableStream - Represents a destination for streaming data.
  • \n
  • TransformStream - Represents an algorithm for transforming streaming data.
  • \n
\n

Example ReadableStream

\n

This example creates a simple ReadableStream that pushes the current\nperformance.now() timestamp once every second forever. An async iterable\nis used to read the data from the stream.

\n
import {\n  ReadableStream\n} from 'node:stream/web';\n\nimport {\n  setInterval as every\n} from 'node:timers/promises';\n\nimport {\n  performance\n} from 'node:perf_hooks';\n\nconst SECOND = 1000;\n\nconst stream = new ReadableStream({\n  async start(controller) {\n    for await (const _ of every(SECOND))\n      controller.enqueue(performance.now());\n  }\n});\n\nfor await (const value of stream)\n  console.log(value);\n
\n
const {\n  ReadableStream\n} = require('stream/web');\n\nconst {\n  setInterval: every\n} = require('timers/promises');\n\nconst {\n  performance\n} = require('perf_hooks');\n\nconst SECOND = 1000;\n\nconst stream = new ReadableStream({\n  async start(controller) {\n    for await (const _ of every(SECOND))\n      controller.enqueue(performance.now());\n  }\n});\n\n(async () => {\n  for await (const value of stream)\n    console.log(value);\n})();\n
", "type": "module", "displayName": "Overview" }, { "textRaw": "API", "name": "api", "classes": [ { "textRaw": "Class: `ReadableStream`", "type": "class", "name": "ReadableStream", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "properties": [ { "textRaw": "`locked` Type: {boolean} Set to `true` if there is an active reader for this {ReadableStream}.", "type": "boolean", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The readableStream.locked property is false by default, and is\nswitch to true while there is an active reader consuming the\nstream's data.

", "shortDesc": "Set to `true` if there is an active reader for this {ReadableStream}." } ], "methods": [ { "textRaw": "`readableStream.cancel([reason])`", "type": "method", "name": "cancel", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined` once cancelation has been completed.", "name": "return", "desc": "A promise fulfilled with `undefined` once cancelation has been completed." }, "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ] }, { "textRaw": "`readableStream.getReader([options])`", "type": "method", "name": "getReader", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ReadableStreamDefaultReader|ReadableStreamBYOBReader}", "name": "return", "type": "ReadableStreamDefaultReader|ReadableStreamBYOBReader" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`mode` {string} `'byob'` or `undefined`", "name": "mode", "type": "string", "desc": "`'byob'` or `undefined`" } ] } ] } ], "desc": "
import { ReadableStream } from 'node:stream/web';\n\nconst stream = new ReadableStream();\n\nconst reader = stream.getReader();\n\nconsole.log(await reader.read());\n
\n
const { ReadableStream } = require('stream/web');\n\nconst stream = new ReadableStream();\n\nconst reader = stream.getReader();\n\nreader.read().then(console.log);\n
\n

Causes the readableStream.locked to be true.

" }, { "textRaw": "`readableStream.pipeThrough(transform[, options])`", "type": "method", "name": "pipeThrough", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ReadableStream} From `transform.readable`.", "name": "return", "type": "ReadableStream", "desc": "From `transform.readable`." }, "params": [ { "textRaw": "`transform` {Object}", "name": "transform", "type": "Object", "options": [ { "textRaw": "`readable` {ReadableStream} The `ReadableStream` to which `transform.writable` will push the potentially modified data is receives from this `ReadableStream`.", "name": "readable", "type": "ReadableStream", "desc": "The `ReadableStream` to which `transform.writable` will push the potentially modified data is receives from this `ReadableStream`." }, { "textRaw": "`writable` {WritableStream} The `WritableStream` to which this `ReadableStream`'s data will be written.", "name": "writable", "type": "WritableStream", "desc": "The `WritableStream` to which this `ReadableStream`'s data will be written." } ] }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`preventAbort` {boolean} When `true`, errors in this `ReadableStream` will not cause `transform.writable` to be aborted.", "name": "preventAbort", "type": "boolean", "desc": "When `true`, errors in this `ReadableStream` will not cause `transform.writable` to be aborted." }, { "textRaw": "`preventCancel` {boolean} When `true`, errors in the destination `transform.writable` is not cause this `ReadableStream` to be canceled.", "name": "preventCancel", "type": "boolean", "desc": "When `true`, errors in the destination `transform.writable` is not cause this `ReadableStream` to be canceled." }, { "textRaw": "`preventClose` {boolean} When `true`, closing this `ReadableStream` will no cause `transform.writable` to be closed.", "name": "preventClose", "type": "boolean", "desc": "When `true`, closing this `ReadableStream` will no cause `transform.writable` to be closed." }, { "textRaw": "`signal` {AbortSignal} Allows the transfer of data to be canceled using an {AbortController}.", "name": "signal", "type": "AbortSignal", "desc": "Allows the transfer of data to be canceled using an {AbortController}." } ] } ] } ], "desc": "

Connects this <ReadableStream> to the pair of <ReadableStream> and\n<WritableStream> provided in the transform argument such that the\ndata from this <ReadableStream> is written in to transform.writable,\npossibly transformed, then pushed to transform.readable. Once the\npipeline is configured, transform.readable is returned.

\n

Causes the readableStream.locked to be true while the pipe operation\nis active.

\n
import {\n  ReadableStream,\n  TransformStream,\n} from 'node:stream/web';\n\nconst stream = new ReadableStream({\n  start(controller) {\n    controller.enqueue('a');\n  },\n});\n\nconst transform = new TransformStream({\n  transform(chunk, controller) {\n    controller.enqueue(chunk.toUpperCase());\n  }\n});\n\nconst transformedStream = stream.pipeThrough(transform);\n\nfor await (const chunk of transformedStream)\n  console.log(chunk);\n
\n
const {\n  ReadableStream,\n  TransformStream,\n} = require('stream/web');\n\nconst stream = new ReadableStream({\n  start(controller) {\n    controller.enqueue('a');\n  },\n});\n\nconst transform = new TransformStream({\n  transform(chunk, controller) {\n    controller.enqueue(chunk.toUpperCase());\n  }\n});\n\nconst transformedStream = stream.pipeThrough(transform);\n\n(async () => {\n  for await (const chunk of transformedStream)\n    console.log(chunk);\n})();\n
" }, { "textRaw": "`readableStream.pipeTo(destination, options)`", "type": "method", "name": "pipeTo", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`", "name": "return", "desc": "A promise fulfilled with `undefined`" }, "params": [ { "textRaw": "`destination` {WritableStream} A {WritableStream} to which this `ReadableStream`'s data will be written.", "name": "destination", "type": "WritableStream", "desc": "A {WritableStream} to which this `ReadableStream`'s data will be written." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`preventAbort` {boolean} When `true`, errors in this `ReadableStream` will not cause `transform.writable` to be aborted.", "name": "preventAbort", "type": "boolean", "desc": "When `true`, errors in this `ReadableStream` will not cause `transform.writable` to be aborted." }, { "textRaw": "`preventCancel` {boolean} When `true`, errors in the destination `transform.writable` is not cause this `ReadableStream` to be canceled.", "name": "preventCancel", "type": "boolean", "desc": "When `true`, errors in the destination `transform.writable` is not cause this `ReadableStream` to be canceled." }, { "textRaw": "`preventClose` {boolean} When `true`, closing this `ReadableStream` will no cause `transform.writable` to be closed.", "name": "preventClose", "type": "boolean", "desc": "When `true`, closing this `ReadableStream` will no cause `transform.writable` to be closed." }, { "textRaw": "`signal` {AbortSignal} Allows the transfer of data to be canceled using an {AbortController}.", "name": "signal", "type": "AbortSignal", "desc": "Allows the transfer of data to be canceled using an {AbortController}." } ] } ] } ], "desc": "

Causes the readableStream.locked to be true while the pipe operation\nis active.

" }, { "textRaw": "`readableStream.tee()`", "type": "method", "name": "tee", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ReadableStream[]}", "name": "return", "type": "ReadableStream[]" }, "params": [] } ], "desc": "

Returns a pair of new <ReadableStream> instances to which this\nReadableStream's data will be forwarded. Each will receive the\nsame data.

\n

Causes the readableStream.locked to be true.

" }, { "textRaw": "`readableStream.values([options])`", "type": "method", "name": "values", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`preventCancel` {boolean} When `true`, prevents the {ReadableStream} from being closed when the async iterator abruptly terminates. **Defaults**: `false`", "name": "preventCancel", "type": "boolean", "desc": "When `true`, prevents the {ReadableStream} from being closed when the async iterator abruptly terminates. **Defaults**: `false`" } ] } ] } ], "desc": "

Creates and returns an async iterator usable for consuming this\nReadableStream's data.

\n

Causes the readableStream.locked to be true while the async iterator\nis active.

\n
import { Buffer } from 'node:buffer';\n\nconst stream = new ReadableStream(getSomeSource());\n\nfor await (const chunk of stream.values({ preventCancel: true }))\n  console.log(Buffer.from(chunk).toString());\n
" } ], "modules": [ { "textRaw": "Async Iteration", "name": "async_iteration", "desc": "

The <ReadableStream> object supports the async iterator protocol using\nfor await syntax.

\n
import { Buffer } from 'buffer';\n\nconst stream = new ReadableStream(getSomeSource());\n\nfor await (const chunk of stream)\n  console.log(Buffer.from(chunk).toString());\n
\n

The async iterator will consume the <ReadableStream> until it terminates.

\n

By default, if the async iterator exits early (via either a break,\nreturn, or a throw), the <ReadableStream> will be closed. To prevent\nautomatic closing of the <ReadableStream>, use the readableStream.values()\nmethod to acquire the async iterator and set the preventCancel option to\ntrue.

\n

The <ReadableStream> must not be locked (that is, it must not have an existing\nactive reader). During the async iteration, the <ReadableStream> will be locked.

", "type": "module", "displayName": "Async Iteration" }, { "textRaw": "Transferring with `postMessage()`", "name": "transferring_with_`postmessage()`", "desc": "

A <ReadableStream> instance can be transferred using a <MessagePort>.

\n
const stream = new ReadableStream(getReadableSourceSomehow());\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => {\n  data.getReader().read().then((chunk) => {\n    console.log(chunk);\n  });\n};\n\nport2.postMessage(stream, [stream]);\n
", "type": "module", "displayName": "Transferring with `postMessage()`" } ], "signatures": [ { "params": [], "desc": "\n
    \n
  • underlyingSource <Object>\n
      \n
    • start <Function> A user-defined function that is invoked immediately when\nthe ReadableStream is created.\n\n
    • \n
    • pull <Function> A user-defined function that is called repeatedly when the\nReadableStream internal queue is not full. The operation may be sync or\nasync. If async, the function will not be called again until the previously\nreturned promise is fulfilled.\n\n
    • \n
    • cancel <Function> A user-defined function that is called when the\nReadableStream is canceled.\n
        \n
      • reason <any>
      • \n
      • Returns: A promise fulfilled with undefined.
      • \n
      \n
    • \n
    • type <string> Must be 'bytes' or undefined.
    • \n
    • autoAllocateChunkSize <number> Used only when type is equal to\n'bytes'.
    • \n
    \n
  • \n
  • strategy <Object>\n
      \n
    • highWaterMark <number> The maximum internal queue size before backpressure\nis applied.
    • \n
    • size <Function> A user-defined function used to identify the size of each\nchunk of data.\n\n
    • \n
    \n
  • \n
\n" } ] }, { "textRaw": "Class: `ReadableStreamDefaultReader`", "type": "class", "name": "ReadableStreamDefaultReader", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

By default, calling readableStream.getReader() with no arguments\nwill return an instance of ReadableStreamDefaultReader. The default\nreader treats the chunks of data passed through the stream as opaque\nvalues, which allows the <ReadableStream> to work with generally any\nJavaScript value.

", "methods": [ { "textRaw": "`readableStreamDefaultReader.cancel([reason])`", "type": "method", "name": "cancel", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ], "desc": "

Cancels the <ReadableStream> and returns a promise that is fulfilled\nwhen the underlying stream has been canceled.

" }, { "textRaw": "`readableStreamDefaultReader.read()`", "type": "method", "name": "read", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with an object:", "name": "return", "desc": "A promise fulfilled with an object:", "options": [ { "textRaw": "`value` {ArrayBuffer}", "name": "value", "type": "ArrayBuffer" }, { "textRaw": "`done` {boolean}", "name": "done", "type": "boolean" } ] }, "params": [] } ], "desc": "

Requests the next chunk of data from the underlying <ReadableStream>\nand returns a promise that is fulfilled with the data once it is\navailable.

" }, { "textRaw": "`readableStreamDefaultReader.releaseLock()`", "type": "method", "name": "releaseLock", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Releases this reader's lock on the underlying <ReadableStream>.

" } ], "properties": [ { "textRaw": "`closed` Type: {Promise} Fulfilled with `undefined` when the associated {ReadableStream} is closed or this reader's lock is released.", "type": "Promise", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "Fulfilled with `undefined` when the associated {ReadableStream} is closed or this reader's lock is released." } ], "signatures": [ { "params": [ { "textRaw": "`stream` {ReadableStream}", "name": "stream", "type": "ReadableStream" } ], "desc": "

Creates a new <ReadableStreamDefaultReader> that is locked to the\ngiven <ReadableStream>.

" } ] }, { "textRaw": "Class: `ReadableStreamBYOBReader`", "type": "class", "name": "ReadableStreamBYOBReader", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The ReadableStreamBYOBReader is an alternative consumer for\nbyte-oriented <ReadableStream>'s (those that are created with\nunderlyingSource.type set equal to 'bytes`` when the ReadableStream` was created).

\n

The BYOB is short for \"bring your own buffer\". This is a\npattern that allows for more efficient reading of byte-oriented\ndata that avoids extraneous copying.

\n
import {\n  open\n} from 'node:fs/promises';\n\nimport {\n  ReadableStream\n} from 'node:stream/web';\n\nimport { Buffer } from 'node:buffer';\n\nclass Source {\n  type = 'bytes';\n  autoAllocateChunkSize = 1024;\n\n  async start(controller) {\n    this.file = await open(new URL(import.meta.url));\n    this.controller = controller;\n  }\n\n  async pull(controller) {\n    const view = controller.byobRequest?.view;\n    const {\n      bytesRead,\n    } = await this.file.read({\n      buffer: view,\n      offset: view.byteOffset,\n      length: view.byteLength\n    });\n\n    if (bytesRead === 0) {\n      await this.file.close();\n      this.controller.close();\n    }\n    controller.byobRequest.respond(bytesRead);\n  }\n}\n\nconst stream = new ReadableStream(new Source());\n\nasync function read(stream) {\n  const reader = stream.getReader({ mode: 'byob' });\n\n  const chunks = [];\n  let result;\n  do {\n    result = await reader.read(Buffer.alloc(100));\n    if (result.value !== undefined)\n      chunks.push(Buffer.from(result.value));\n  } while (!result.done);\n\n  return Buffer.concat(chunks);\n}\n\nconst data = await read(stream);\nconsole.log(Buffer.from(data).toString());\n
", "methods": [ { "textRaw": "`readableStreamBYOBReader.cancel([reason])`", "type": "method", "name": "cancel", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ], "desc": "

Cancels the <ReadableStream> and returns a promise that is fulfilled\nwhen the underlying stream has been canceled.

" }, { "textRaw": "`readableStreamBYOBReader.read(view)`", "type": "method", "name": "read", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with an object:", "name": "return", "desc": "A promise fulfilled with an object:", "options": [ { "textRaw": "`value` {ArrayBuffer}", "name": "value", "type": "ArrayBuffer" }, { "textRaw": "`done` {boolean}", "name": "done", "type": "boolean" } ] }, "params": [ { "textRaw": "`view` {Buffer|TypedArray|DataView}", "name": "view", "type": "Buffer|TypedArray|DataView" } ] } ], "desc": "

Requests the next chunk of data from the underlying <ReadableStream>\nand returns a promise that is fulfilled with the data once it is\navailable.

\n

Do not pass a pooled <Buffer> object instance in to this method.\nPooled Buffer objects are created using Buffer.allocUnsafe(),\nor Buffer.from(), or are often returned by various fs module\ncallbacks. These types of Buffers use a shared underlying\n<ArrayBuffer> object that contains all of the data from all of\nthe pooled Buffer instances. When a Buffer, <TypedArray>,\nor <DataView> is passed in to readableStreamBYOBReader.read(),\nthe view's underlying ArrayBuffer is detached, invalidating\nall existing views that may exist on that ArrayBuffer. This\ncan have disastrous consequences for your application.

" }, { "textRaw": "`readableStreamBYOBReader.releaseLock()`", "type": "method", "name": "releaseLock", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Releases this reader's lock on the underlying <ReadableStream>.

" } ], "properties": [ { "textRaw": "`closed` Type: {Promise} Fulfilled with `undefined` when the associated {ReadableStream} is closed or this reader's lock is released.", "type": "Promise", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "Fulfilled with `undefined` when the associated {ReadableStream} is closed or this reader's lock is released." } ], "signatures": [ { "params": [ { "textRaw": "`stream` {ReadableStream}", "name": "stream", "type": "ReadableStream" } ], "desc": "

Creates a new ReadableStreamBYOBReader that is locked to the\ngiven <ReadableStream>.

" } ] }, { "textRaw": "Class: `ReadableStreamDefaultController`", "type": "class", "name": "ReadableStreamDefaultController", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

Every <ReadableStream> has a controller that is responsible for\nthe internal state and management of the stream's queue. The\nReadableStreamDefaultController is the default controller\nimplementation for ReadableStreams that are not byte-oriented.

", "methods": [ { "textRaw": "`readableStreamDefaultController.close()`", "type": "method", "name": "close", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the <ReadableStream> to which this controller is associated.

" }, { "textRaw": "`readableStreamDefaultController.enqueue(chunk)`", "type": "method", "name": "enqueue", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" } ] } ], "desc": "

Appends a new chunk of data to the <ReadableStream>'s queue.

" }, { "textRaw": "`readableStreamDefaultController.error(error)`", "type": "method", "name": "error", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {any}", "name": "error", "type": "any" } ] } ], "desc": "

Signals an error that causes the <ReadableStream> to error and close.

" } ], "properties": [ { "textRaw": "`desiredSize` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

Returns the amount of data remaining to fill the <ReadableStream>'s\nqueue.

" } ] }, { "textRaw": "Class: `ReadableByteStreamController`", "type": "class", "name": "ReadableByteStreamController", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

Every <ReadableStream> has a controller that is responsible for\nthe internal state and management of the stream's queue. The\nReadableByteStreamController is for byte-oriented ReadableStreams.

", "properties": [ { "textRaw": "`byobRequest` Type: {ReadableStreamBYOBRequest}", "type": "ReadableStreamBYOBRequest", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

Returns the amount of data remaining to fill the <ReadableStream>'s\nqueue.

" }, { "textRaw": "`desiredSize` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

Returns the amount of data remaining to fill the <ReadableStream>'s\nqueue.

" } ], "methods": [ { "textRaw": "`readableByteStreamController.close()`", "type": "method", "name": "close", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the <ReadableStream> to which this controller is associated.

" }, { "textRaw": "`readableByteStreamController.enqueue(chunk)`", "type": "method", "name": "enqueue", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`chunk`: {Buffer|TypedArray|DataView}", "name": "chunk", "type": "Buffer|TypedArray|DataView" } ] } ], "desc": "

Appends a new chunk of data to the <ReadableStream>'s queue.

" }, { "textRaw": "`readableByteStreamController.error(error)`", "type": "method", "name": "error", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {any}", "name": "error", "type": "any" } ] } ], "desc": "

Signals an error that causes the <ReadableStream> to error and close.

" } ] }, { "textRaw": "Class: `ReadableStreamBYOBRequest`", "type": "class", "name": "ReadableStreamBYOBRequest", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

When using ReadableByteStreamController in byte-oriented\nstreams, and when using the ReadableStreamBYOBReader,\nthe readableByteStreamController.byobRequest property\nprovides access to a ReadableStreamBYOBRequest instance\nthat represents the current read request. The object\nis used to gain access to the ArrayBuffer/TypedArray\nthat has been provided for the read request to fill,\nand provides methods for signaling that the data has\nbeen provided.

", "methods": [ { "textRaw": "`readableStreamBYOBRequest.respond(bytesWritten)`", "type": "method", "name": "respond", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`bytesWritten` {number}", "name": "bytesWritten", "type": "number" } ] } ], "desc": "

Signals that a bytesWritten number of bytes have been written\nto readableStreamBYOBRequest.view.

" }, { "textRaw": "`readableStreamBYOBRequest.respondWithNewView(view)`", "type": "method", "name": "respondWithNewView", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`view` {Buffer|TypedArray|DataView}", "name": "view", "type": "Buffer|TypedArray|DataView" } ] } ], "desc": "

Signals that the request has been fulfilled with bytes written\nto a new Buffer, TypedArray, or DataView.

" } ], "properties": [ { "textRaw": "`view` Type: {Buffer|TypedArray|DataView}", "type": "Buffer|TypedArray|DataView", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] } } ] }, { "textRaw": "Class: `WritableStream`", "type": "class", "name": "WritableStream", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The WritableStream is a destination to which stream data is sent.

\n
import {\n  WritableStream\n} from 'node:stream/web';\n\nconst stream = new WritableStream({\n  write(chunk) {\n    console.log(chunk);\n  }\n});\n\nawait stream.getWriter().write('Hello World');\n
", "methods": [ { "textRaw": "`writableStream.abort([reason])`", "type": "method", "name": "abort", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ], "desc": "

Abruptly terminates the WritableStream. All queued writes will be\ncanceled with their associated promises rejected.

" }, { "textRaw": "`writableStream.close()`", "type": "method", "name": "close", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [] } ], "desc": "

Closes the WritableStream when no additional writes are expected.

" }, { "textRaw": "`writableStream.getWriter()`", "type": "method", "name": "getWriter", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {WritableStreamDefaultWriter}", "name": "return", "type": "WritableStreamDefaultWriter" }, "params": [] } ], "desc": "

Creates and creates a new writer instance that can be used to write\ndata into the WritableStream.

" } ], "properties": [ { "textRaw": "`locked` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The writableStream.locked property is false by default, and is\nswitched to true while there is an active writer attached to this\nWritableStream.

" } ], "modules": [ { "textRaw": "Transferring with postMessage()", "name": "transferring_with_postmessage()", "desc": "

A <WritableStream> instance can be transferred using a <MessagePort>.

\n
const stream = new WritableStream(getWritableSinkSomehow());\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => {\n  data.getWriter().write('hello');\n};\n\nport2.postMessage(stream, [stream]);\n
", "type": "module", "displayName": "Transferring with postMessage()" } ], "signatures": [ { "params": [ { "textRaw": "`underlyingSink` {Object}", "name": "underlyingSink", "type": "Object", "options": [ { "textRaw": "`start` {Function} A user-defined function that is invoked immediately when the `WritableStream` is created.", "name": "start", "type": "Function", "desc": "A user-defined function that is invoked immediately when the `WritableStream` is created.", "options": [ { "textRaw": "`controller` {WritableStreamDefaultController}", "name": "controller", "type": "WritableStreamDefaultController" }, { "textRaw": "Returns: `undefined` or a promise fulfilled with `undefined`.", "name": "return", "desc": "`undefined` or a promise fulfilled with `undefined`." } ] }, { "textRaw": "`write` {Function} A user-defined function that is invoked when a chunk of data has been written to the `WritableStream`.", "name": "write", "type": "Function", "desc": "A user-defined function that is invoked when a chunk of data has been written to the `WritableStream`.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "`controller` {WritableStreamDefaultController}", "name": "controller", "type": "WritableStreamDefaultController" }, { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." } ] }, { "textRaw": "`close` {Function} A user-defined function that is called when the `WritableStream` is closed.", "name": "close", "type": "Function", "desc": "A user-defined function that is called when the `WritableStream` is closed.", "options": [ { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." } ] }, { "textRaw": "`abort` {Function} A user-defined function that is called to abruptly close the `WritableStream`.", "name": "abort", "type": "Function", "desc": "A user-defined function that is called to abruptly close the `WritableStream`.", "options": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" }, { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." } ] }, { "textRaw": "`type` {any} The `type` option is reserved for future use and *must* be undefined.", "name": "type", "type": "any", "desc": "The `type` option is reserved for future use and *must* be undefined." } ] }, { "textRaw": "`strategy` {Object}", "name": "strategy", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum internal queue size before backpressure is applied.", "name": "highWaterMark", "type": "number", "desc": "The maximum internal queue size before backpressure is applied." }, { "textRaw": "`size` {Function} A user-defined function used to identify the size of each chunk of data.", "name": "size", "type": "Function", "desc": "A user-defined function used to identify the size of each chunk of data.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ] } ] } ] }, { "textRaw": "Class: `WritableStreamDefaultWriter`", "type": "class", "name": "WritableStreamDefaultWriter", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "methods": [ { "textRaw": "`writableStreamDefaultWriter.abort([reason])`", "type": "method", "name": "abort", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ], "desc": "

Abruptly terminates the WritableStream. All queued writes will be\ncanceled with their associated promises rejected.

" }, { "textRaw": "`writableStreamDefaultWriter.close()`", "type": "method", "name": "close", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [] } ], "desc": "

Closes the WritableStream when no additional writes are expected.

" }, { "textRaw": "`writableStreamDefaultWriter.releaseLock()`", "type": "method", "name": "releaseLock", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Releases this writer's lock on the underlying <ReadableStream>.

" }, { "textRaw": "`writableStreamDefaultWriter.write([chunk])`", "type": "method", "name": "write", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." }, "params": [ { "textRaw": "`chunk`: {any}", "name": "chunk", "type": "any" } ] } ], "desc": "

Appends a new chunk of data to the <WritableStream>'s queue.

" } ], "properties": [ { "textRaw": "`closed` Type: A promise that is fulfilled with `undefined` when the associated {WritableStream} is closed or this writer's lock is released.", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "A promise that is fulfilled with `undefined` when the associated {WritableStream} is closed or this writer's lock is released." }, { "textRaw": "`desiredSize` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The amount of data required to fill the <WritableStream>'s queue.

" }, { "textRaw": "`ready` type: A promise that is fulfilled with `undefined` when the writer is ready to be used.", "name": "type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "A promise that is fulfilled with `undefined` when the writer is ready to be used." } ], "signatures": [ { "params": [ { "textRaw": "`stream` {WritableStream}", "name": "stream", "type": "WritableStream" } ], "desc": "

Creates a new WritableStreamDefaultWriter that is locked to the given\nWritableStream.

" } ] }, { "textRaw": "Class: `WritableStreamDefaultController`", "type": "class", "name": "WritableStreamDefaultController", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The WritableStreamDefaultController manage's the <WritableStream>'s\ninternal state.

", "properties": [ { "textRaw": "`abortReason` Type: {any} The `reason` value passed to `writableStream.abort()`.", "type": "any", "name": "Type", "desc": "The `reason` value passed to `writableStream.abort()`." }, { "textRaw": "`signal` Type: {AbortSignal} An `AbortSignal` that can be used to cancel pending write or close operations when a {WritableStream} is aborted.", "type": "AbortSignal", "name": "Type", "desc": "An `AbortSignal` that can be used to cancel pending write or close operations when a {WritableStream} is aborted." } ], "methods": [ { "textRaw": "`writableStreamDefaultController.error(error)`", "type": "method", "name": "error", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {any}", "name": "error", "type": "any" } ] } ], "desc": "

Called by user-code to signal that an error has occurred while processing\nthe WritableStream data. When called, the <WritableStream> will be aborted,\nwith currently pending writes canceled.

" } ] }, { "textRaw": "Class: `TransformStream`", "type": "class", "name": "TransformStream", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

A TransformStream consists of a <ReadableStream> and a <WritableStream> that\nare connected such that the data written to the WritableStream is received,\nand potentially transformed, before being pushed into the ReadableStream's\nqueue.

\n
import {\n  TransformStream\n} from 'node:stream/web';\n\nconst transform = new TransformStream({\n  transform(chunk, controller) {\n    controller.enqueue(chunk.toUpperCase());\n  }\n});\n\nawait Promise.all([\n  transform.writable.getWriter().write('A'),\n  transform.readable.getReader().read(),\n]);\n
", "properties": [ { "textRaw": "`readable` Type: {ReadableStream}", "type": "ReadableStream", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] } }, { "textRaw": "`writable` Type: {WritableStream}", "type": "WritableStream", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] } } ], "modules": [ { "textRaw": "Transferring with postMessage()", "name": "transferring_with_postmessage()", "desc": "

A <TransformStream> instance can be transferred using a <MessagePort>.

\n
const stream = new TransformStream();\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => {\n  const { writable, readable } = data;\n  // ...\n};\n\nport2.postMessage(stream, [stream]);\n
", "type": "module", "displayName": "Transferring with postMessage()" } ], "signatures": [ { "params": [ { "textRaw": "`transformer` {Object}", "name": "transformer", "type": "Object", "options": [ { "textRaw": "`start` {Function} A user-defined function that is invoked immediately when the `TransformStream` is created.", "name": "start", "type": "Function", "desc": "A user-defined function that is invoked immediately when the `TransformStream` is created.", "options": [ { "textRaw": "`controller` {TransformStreamDefaultController}", "name": "controller", "type": "TransformStreamDefaultController" }, { "textRaw": "Returns: `undefined` or a promise fulfilled with `undefined`", "name": "return", "desc": "`undefined` or a promise fulfilled with `undefined`" } ] }, { "textRaw": "`transform` {Function} A user-defined function that receives, and potentially modifies, a chunk of data written to `transformStream.writable`, before forwarding that on to `transformStream.readable`.", "name": "transform", "type": "Function", "desc": "A user-defined function that receives, and potentially modifies, a chunk of data written to `transformStream.writable`, before forwarding that on to `transformStream.readable`.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "`controller` {TransformStreamDefaultController}", "name": "controller", "type": "TransformStreamDefaultController" }, { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." } ] }, { "textRaw": "`flush` {Function} A user-defined function that is called immediately before the writable side of the `TransformStream` is closed, signaling the end of the transformation process.", "name": "flush", "type": "Function", "desc": "A user-defined function that is called immediately before the writable side of the `TransformStream` is closed, signaling the end of the transformation process.", "options": [ { "textRaw": "`controller` {TransformStreamDefaultController}", "name": "controller", "type": "TransformStreamDefaultController" }, { "textRaw": "Returns: A promise fulfilled with `undefined`.", "name": "return", "desc": "A promise fulfilled with `undefined`." } ] }, { "textRaw": "`readableType` {any} the `readableType` option is reserved for future use and *must* be `undefined.", "name": "readableType", "type": "any", "desc": "the `readableType` option is reserved for future use and *must* be `undefined." }, { "textRaw": "`writableType` {any} the `writableType` option is reserved for future use and *must* be `undefined.", "name": "writableType", "type": "any", "desc": "the `writableType` option is reserved for future use and *must* be `undefined." } ] }, { "textRaw": "`writableStrategy` {Object}", "name": "writableStrategy", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum internal queue size before backpressure is applied.", "name": "highWaterMark", "type": "number", "desc": "The maximum internal queue size before backpressure is applied." }, { "textRaw": "`size` {Function} A user-defined function used to identify the size of each chunk of data.", "name": "size", "type": "Function", "desc": "A user-defined function used to identify the size of each chunk of data.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ] }, { "textRaw": "`readableStrategy` {Object}", "name": "readableStrategy", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum internal queue size before backpressure is applied.", "name": "highWaterMark", "type": "number", "desc": "The maximum internal queue size before backpressure is applied." }, { "textRaw": "`size` {Function} A user-defined function used to identify the size of each chunk of data.", "name": "size", "type": "Function", "desc": "A user-defined function used to identify the size of each chunk of data.", "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ] } ] } ] }, { "textRaw": "Class: `TransformStreamDefaultController`", "type": "class", "name": "TransformStreamDefaultController", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The TransformStreamDefaultController manages the internal state\nof the TransformStream.

", "properties": [ { "textRaw": "`desiredSize` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "desc": "

The amount of data required to fill the readable side's queue.

" } ], "methods": [ { "textRaw": "`transformStreamDefaultController.enqueue([chunk])`", "type": "method", "name": "enqueue", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" } ] } ], "desc": "

Appends a chunk of data to the readable side's queue.

" }, { "textRaw": "`transformStreamDefaultController.error([reason])`", "type": "method", "name": "error", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`reason` {any}", "name": "reason", "type": "any" } ] } ], "desc": "

Signals to both the readable and writable side that an error has occurred\nwhile processing the transform data, causing both sides to be abruptly\nclosed.

" }, { "textRaw": "`transformStreamDefaultController.terminate()`", "type": "method", "name": "terminate", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the readable side of the transport and causes the writable side\nto be abruptly closed with an error.

" } ] }, { "textRaw": "Class: `ByteLengthQueuingStrategy`", "type": "class", "name": "ByteLengthQueuingStrategy", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "properties": [ { "textRaw": "`highWaterMark` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] } }, { "textRaw": "`size` Type: {Function}", "type": "Function", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number}", "name": "highWaterMark", "type": "number" } ] } ] } ] }, { "textRaw": "Class: `CountQueuingStrategy`", "type": "class", "name": "CountQueuingStrategy", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "properties": [ { "textRaw": "`highWaterMark` Type: {number}", "type": "number", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] } }, { "textRaw": "`size` Type: {Function}", "type": "Function", "name": "Type", "meta": { "added": [ "v16.5.0" ], "changes": [] }, "options": [ { "textRaw": "`chunk` {any}", "name": "chunk", "type": "any" }, { "textRaw": "Returns: {number}", "name": "return", "type": "number" } ] } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number}", "name": "highWaterMark", "type": "number" } ] } ] } ] }, { "textRaw": "Class: `TextEncoderStream`", "type": "class", "name": "TextEncoderStream", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "properties": [ { "textRaw": "`encoding` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "

The encoding supported by the TextEncoderStream instance.

" }, { "textRaw": "`readable` Type: {ReadableStream}", "type": "ReadableStream", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] } }, { "textRaw": "`writable` Type: {WritableStream}", "type": "WritableStream", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] } } ], "signatures": [ { "params": [], "desc": "

Creates a new TextEncoderStream instance.

" } ] }, { "textRaw": "Class: `TextDecoderStream`", "type": "class", "name": "TextDecoderStream", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "properties": [ { "textRaw": "`encoding` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "

The encoding supported by the TextDecoderStream instance.

" }, { "textRaw": "`fatal` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "

The value will be true if decoding errors result in a TypeError being\nthrown.

" }, { "textRaw": "`ignoreBOM` Type: {boolean}", "type": "boolean", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "desc": "

The value will be true if the decoding result will include the byte order\nmark.

" }, { "textRaw": "`readable` Type: {ReadableStream}", "type": "ReadableStream", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] } }, { "textRaw": "`writable` Type: {WritableStream}", "type": "WritableStream", "name": "Type", "meta": { "added": [ "v16.6.0" ], "changes": [] } } ], "signatures": [ { "params": [ { "textRaw": "`encoding` {string} Identifies the `encoding` that this `TextDecoder` instance supports. **Default:** `'utf-8'`.", "name": "encoding", "type": "string", "default": "`'utf-8'`", "desc": "Identifies the `encoding` that this `TextDecoder` instance supports." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`fatal` {boolean} `true` if decoding failures are fatal.", "name": "fatal", "type": "boolean", "desc": "`true` if decoding failures are fatal." }, { "textRaw": "`ignoreBOM` {boolean} When `true`, the `TextDecoderStream` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`. **Default:** `false`.", "name": "ignoreBOM", "type": "boolean", "default": "`false`", "desc": "When `true`, the `TextDecoderStream` will include the byte order mark in the decoded result. When `false`, the byte order mark will be removed from the output. This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`." } ] } ], "desc": "

Creates a new TextDecoderStream instance.

" } ] }, { "textRaw": "Class: `CompressionStream`", "type": "class", "name": "CompressionStream", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "properties": [ { "textRaw": "`readable` Type: {ReadableStream}", "type": "ReadableStream", "name": "Type", "meta": { "added": [ "v16.7.0" ], "changes": [] } }, { "textRaw": "`writable` Type: {WritableStream}", "type": "WritableStream", "name": "Type", "meta": { "added": [ "v16.7.0" ], "changes": [] } } ], "signatures": [ { "params": [ { "textRaw": "`format` {string} One of either `'deflate'` or `'gzip'`.", "name": "format", "type": "string", "desc": "One of either `'deflate'` or `'gzip'`." } ] } ] }, { "textRaw": "Class: `DecompressionStream`", "type": "class", "name": "DecompressionStream", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "properties": [ { "textRaw": "`readable` Type: {ReadableStream}", "type": "ReadableStream", "name": "Type", "meta": { "added": [ "v16.7.0" ], "changes": [] } }, { "textRaw": "`writable` Type: {WritableStream}", "type": "WritableStream", "name": "Type", "meta": { "added": [ "v16.7.0" ], "changes": [] } } ], "signatures": [ { "params": [ { "textRaw": "`format` {string} One of either `'deflate'` or `'gzip'`.", "name": "format", "type": "string", "desc": "One of either `'deflate'` or `'gzip'`." } ] } ] } ], "modules": [ { "textRaw": "Utility Consumers", "name": "utility_consumers", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "desc": "

The utility consumer functions provide common options for consuming\nstreams.

\n

They are accessed using:

\n
import {\n  arrayBuffer,\n  blob,\n  json,\n  text,\n} from 'node:stream/consumers';\n
\n
const {\n  arrayBuffer,\n  blob,\n  json,\n  text,\n} = require('stream/consumers');\n
", "methods": [ { "textRaw": "`streamConsumers.arrayBuffer(stream)`", "type": "method", "name": "arrayBuffer", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with an `ArrayBuffer` containing the full contents of the stream.", "name": "return", "type": "Promise", "desc": "Fulfills with an `ArrayBuffer` containing the full contents of the stream." }, "params": [ { "textRaw": "`stream` {ReadableStream|stream.Readable|AsyncIterator}", "name": "stream", "type": "ReadableStream|stream.Readable|AsyncIterator" } ] } ] }, { "textRaw": "`streamConsumers.blob(stream)`", "type": "method", "name": "blob", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with a {Blob} containing the full contents of the stream.", "name": "return", "type": "Promise", "desc": "Fulfills with a {Blob} containing the full contents of the stream." }, "params": [ { "textRaw": "`stream` {ReadableStream|stream.Readable|AsyncIterator}", "name": "stream", "type": "ReadableStream|stream.Readable|AsyncIterator" } ] } ] }, { "textRaw": "`streamConsumers.buffer(stream)`", "type": "method", "name": "buffer", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with a {Buffer} containing the full contents of the stream.", "name": "return", "type": "Promise", "desc": "Fulfills with a {Buffer} containing the full contents of the stream." }, "params": [ { "textRaw": "`stream` {ReadableStream|stream.Readable|AsyncIterator}", "name": "stream", "type": "ReadableStream|stream.Readable|AsyncIterator" } ] } ] }, { "textRaw": "`streamConsumers.json(stream)`", "type": "method", "name": "json", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the contents of the stream parsed as a UTF-8 encoded string that is then passed through `JSON.parse()`.", "name": "return", "type": "Promise", "desc": "Fulfills with the contents of the stream parsed as a UTF-8 encoded string that is then passed through `JSON.parse()`." }, "params": [ { "textRaw": "`stream` {ReadableStream|stream.Readable|AsyncIterator}", "name": "stream", "type": "ReadableStream|stream.Readable|AsyncIterator" } ] } ] }, { "textRaw": "`streamConsumers.text(stream)`", "type": "method", "name": "text", "meta": { "added": [ "v16.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} Fulfills with the contents of the stream parsed as a UTF-8 encoded string.", "name": "return", "type": "Promise", "desc": "Fulfills with the contents of the stream parsed as a UTF-8 encoded string." }, "params": [ { "textRaw": "`stream` {ReadableStream|stream.Readable|AsyncIterator}", "name": "stream", "type": "ReadableStream|stream.Readable|AsyncIterator" } ] } ] } ], "type": "module", "displayName": "Utility Consumers" } ], "type": "module", "displayName": "API" } ], "type": "module", "displayName": "Web Streams API", "source": "doc/api/webstreams.md" }, { "textRaw": "Worker threads", "name": "worker_threads", "introduced_in": "v10.5.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/worker_threads.js

\n

The worker_threads module enables the use of threads that execute JavaScript\nin parallel. To access it:

\n
const worker = require('worker_threads');\n
\n

Workers (threads) are useful for performing CPU-intensive JavaScript operations.\nThey do not help much with I/O-intensive work. The Node.js built-in\nasynchronous I/O operations are more efficient than Workers can be.

\n

Unlike child_process or cluster, worker_threads can share memory. They do\nso by transferring ArrayBuffer instances or sharing SharedArrayBuffer\ninstances.

\n
const {\n  Worker, isMainThread, parentPort, workerData\n} = require('worker_threads');\n\nif (isMainThread) {\n  module.exports = function parseJSAsync(script) {\n    return new Promise((resolve, reject) => {\n      const worker = new Worker(__filename, {\n        workerData: script\n      });\n      worker.on('message', resolve);\n      worker.on('error', reject);\n      worker.on('exit', (code) => {\n        if (code !== 0)\n          reject(new Error(`Worker stopped with exit code ${code}`));\n      });\n    });\n  };\n} else {\n  const { parse } = require('some-js-parsing-library');\n  const script = workerData;\n  parentPort.postMessage(parse(script));\n}\n
\n

The above example spawns a Worker thread for each parse() call. In actual\npractice, use a pool of Workers for these kinds of tasks. Otherwise, the\noverhead of creating Workers would likely exceed their benefit.

\n

When implementing a worker pool, use the AsyncResource API to inform\ndiagnostic tools (e.g. to provide asynchronous stack traces) about the\ncorrelation between tasks and their outcomes. See\n\"Using AsyncResource for a Worker thread pool\"\nin the async_hooks documentation for an example implementation.

\n

Worker threads inherit non-process-specific options by default. Refer to\nWorker constructor options to know how to customize worker thread options,\nspecifically argv and execArgv options.

", "methods": [ { "textRaw": "`worker.getEnvironmentData(key)`", "type": "method", "name": "getEnvironmentData", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "return": { "textRaw": "Returns: {any}", "name": "return", "type": "any" }, "params": [ { "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.", "name": "key", "type": "any", "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key." } ] } ], "desc": "

Within a worker thread, worker.getEnvironmentData() returns a clone\nof data passed to the spawning thread's worker.setEnvironmentData().\nEvery new Worker receives its own copy of the environment data\nautomatically.

\n
const {\n  Worker,\n  isMainThread,\n  setEnvironmentData,\n  getEnvironmentData,\n} = require('worker_threads');\n\nif (isMainThread) {\n  setEnvironmentData('Hello', 'World!');\n  const worker = new Worker(__filename);\n} else {\n  console.log(getEnvironmentData('Hello'));  // Prints 'World!'.\n}\n
" }, { "textRaw": "`worker.markAsUntransferable(object)`", "type": "method", "name": "markAsUntransferable", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Mark an object as not transferable. If object occurs in the transfer list of\na port.postMessage() call, it is ignored.

\n

In particular, this makes sense for objects that can be cloned, rather than\ntransferred, and which are used by other objects on the sending side.\nFor example, Node.js marks the ArrayBuffers it uses for its\nBuffer pool with this.

\n

This operation cannot be undone.

\n
const { MessageChannel, markAsUntransferable } = require('worker_threads');\n\nconst pooledBuffer = new ArrayBuffer(8);\nconst typedArray1 = new Uint8Array(pooledBuffer);\nconst typedArray2 = new Float64Array(pooledBuffer);\n\nmarkAsUntransferable(pooledBuffer);\n\nconst { port1 } = new MessageChannel();\nport1.postMessage(typedArray1, [ typedArray1.buffer ]);\n\n// The following line prints the contents of typedArray1 -- it still owns\n// its memory and has been cloned, not transferred. Without\n// `markAsUntransferable()`, this would print an empty Uint8Array.\n// typedArray2 is intact as well.\nconsole.log(typedArray1);\nconsole.log(typedArray2);\n
\n

There is no equivalent to this API in browsers.

" }, { "textRaw": "`worker.moveMessagePortToContext(port, contextifiedSandbox)`", "type": "method", "name": "moveMessagePortToContext", "meta": { "added": [ "v11.13.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {MessagePort}", "name": "return", "type": "MessagePort" }, "params": [ { "textRaw": "`port` {MessagePort} The message port to transfer.", "name": "port", "type": "MessagePort", "desc": "The message port to transfer." }, { "textRaw": "`contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method.", "name": "contextifiedSandbox", "type": "Object", "desc": "A [contextified][] object as returned by the `vm.createContext()` method." } ] } ], "desc": "

Transfer a MessagePort to a different vm Context. The original port\nobject is rendered unusable, and the returned MessagePort instance\ntakes its place.

\n

The returned MessagePort is an object in the target context and\ninherits from its global Object class. Objects passed to the\nport.onmessage() listener are also created in the target context\nand inherit from its global Object class.

\n

However, the created MessagePort no longer inherits from\nEventTarget, and only port.onmessage() can be used to receive\nevents using it.

" }, { "textRaw": "`worker.receiveMessageOnPort(port)`", "type": "method", "name": "receiveMessageOnPort", "meta": { "added": [ "v12.3.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37535", "description": "The port argument can also refer to a `BroadcastChannel` now." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object|undefined}", "name": "return", "type": "Object|undefined" }, "params": [ { "textRaw": "`port` {MessagePort|BroadcastChannel}", "name": "port", "type": "MessagePort|BroadcastChannel" } ] } ], "desc": "

Receive a single message from a given MessagePort. If no message is available,\nundefined is returned, otherwise an object with a single message property\nthat contains the message payload, corresponding to the oldest message in the\nMessagePort’s queue.

\n
const { MessageChannel, receiveMessageOnPort } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\nport1.postMessage({ hello: 'world' });\n\nconsole.log(receiveMessageOnPort(port2));\n// Prints: { message: { hello: 'world' } }\nconsole.log(receiveMessageOnPort(port2));\n// Prints: undefined\n
\n

When this function is used, no 'message' event is emitted and the\nonmessage listener is not invoked.

" }, { "textRaw": "`worker.setEnvironmentData(key[, value])`", "type": "method", "name": "setEnvironmentData", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`key` {any} Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.", "name": "key", "type": "any", "desc": "Any arbitrary, cloneable JavaScript value that can be used as a {Map} key." }, { "textRaw": "`value` {any} Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value for the `key` will be deleted.", "name": "value", "type": "any", "desc": "Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value for the `key` will be deleted." } ] } ], "desc": "

The worker.setEnvironmentData() API sets the content of\nworker.getEnvironmentData() in the current thread and all new Worker\ninstances spawned from the current context.

" } ], "properties": [ { "textRaw": "`isMainThread` {boolean}", "type": "boolean", "name": "isMainThread", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

Is true if this code is not running inside of a Worker thread.

\n
const { Worker, isMainThread } = require('worker_threads');\n\nif (isMainThread) {\n  // This re-loads the current file inside a Worker instance.\n  new Worker(__filename);\n} else {\n  console.log('Inside Worker!');\n  console.log(isMainThread);  // Prints 'false'.\n}\n
" }, { "textRaw": "`parentPort` {null|MessagePort}", "type": "null|MessagePort", "name": "parentPort", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

If this thread is a Worker, this is a MessagePort\nallowing communication with the parent thread. Messages sent using\nparentPort.postMessage() are available in the parent thread\nusing worker.on('message'), and messages sent from the parent thread\nusing worker.postMessage() are available in this thread using\nparentPort.on('message').

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  worker.once('message', (message) => {\n    console.log(message);  // Prints 'Hello, world!'.\n  });\n  worker.postMessage('Hello, world!');\n} else {\n  // When a message from the parent thread is received, send it back:\n  parentPort.once('message', (message) => {\n    parentPort.postMessage(message);\n  });\n}\n
" }, { "textRaw": "`resourceLimits` {Object}", "type": "Object", "name": "resourceLimits", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "options": [ { "textRaw": "`maxYoungGenerationSizeMb` {number}", "name": "maxYoungGenerationSizeMb", "type": "number" }, { "textRaw": "`maxOldGenerationSizeMb` {number}", "name": "maxOldGenerationSizeMb", "type": "number" }, { "textRaw": "`codeRangeSizeMb` {number}", "name": "codeRangeSizeMb", "type": "number" }, { "textRaw": "`stackSizeMb` {number}", "name": "stackSizeMb", "type": "number" } ], "desc": "

Provides the set of JS engine resource constraints inside this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

\n

If this is used in the main thread, its value is an empty object.

" }, { "textRaw": "`SHARE_ENV` {symbol}", "type": "symbol", "name": "SHARE_ENV", "meta": { "added": [ "v11.14.0" ], "changes": [] }, "desc": "

A special value that can be passed as the env option of the Worker\nconstructor, to indicate that the current thread and the Worker thread should\nshare read and write access to the same set of environment variables.

\n
const { Worker, SHARE_ENV } = require('worker_threads');\nnew Worker('process.env.SET_IN_WORKER = \"foo\"', { eval: true, env: SHARE_ENV })\n  .on('exit', () => {\n    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.\n  });\n
" }, { "textRaw": "`threadId` {integer}", "type": "integer", "name": "threadId", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

An integer identifier for the current thread. On the corresponding worker object\n(if there is any), it is available as worker.threadId.\nThis value is unique for each Worker instance inside a single process.

" }, { "textRaw": "`worker.workerData`", "name": "workerData", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

An arbitrary JavaScript value that contains a clone of the data passed\nto this thread’s Worker constructor.

\n

The data is cloned as if using postMessage(),\naccording to the HTML structured clone algorithm.

\n
const { Worker, isMainThread, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename, { workerData: 'Hello, world!' });\n} else {\n  console.log(workerData);  // Prints 'Hello, world!'.\n}\n
" } ], "classes": [ { "textRaw": "Class: `BroadcastChannel extends EventTarget`", "type": "class", "name": "BroadcastChannel", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Instances of BroadcastChannel allow asynchronous one-to-many communication\nwith all other BroadcastChannel instances bound to the same channel name.

\n
'use strict';\n\nconst {\n  isMainThread,\n  BroadcastChannel,\n  Worker\n} = require('worker_threads');\n\nconst bc = new BroadcastChannel('hello');\n\nif (isMainThread) {\n  let c = 0;\n  bc.onmessage = (event) => {\n    console.log(event.data);\n    if (++c === 10) bc.close();\n  };\n  for (let n = 0; n < 10; n++)\n    new Worker(__filename);\n} else {\n  bc.postMessage('hello from every worker');\n  bc.close();\n}\n
", "methods": [ { "textRaw": "`broadcastChannel.close()`", "type": "method", "name": "close", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Closes the BroadcastChannel connection.

" }, { "textRaw": "`broadcastChannel.postMessage(message)`", "type": "method", "name": "postMessage", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`message` {any} Any cloneable JavaScript value.", "name": "message", "type": "any", "desc": "Any cloneable JavaScript value." } ] } ] }, { "textRaw": "`broadcastChannel.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Opposite of unref(). Calling ref() on a previously unref()ed\nBroadcastChannel does not let the program exit if it's the only active handle\nleft (the default behavior). If the port is ref()ed, calling ref() again\nhas no effect.

" }, { "textRaw": "`broadcastChannel.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calling unref() on a BroadcastChannel allows the thread to exit if this\nis the only active handle in the event system. If the BroadcastChannel is\nalready unref()ed calling unref() again has no effect.

" } ], "properties": [ { "textRaw": "`onmessage` Type: {Function} Invoked with a single `MessageEvent` argument when a message is received.", "type": "Function", "name": "Type", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "desc": "Invoked with a single `MessageEvent` argument when a message is received." }, { "textRaw": "`onmessageerror` Type: {Function} Invoked with a received message cannot be deserialized.", "type": "Function", "name": "Type", "meta": { "added": [ "v15.4.0" ], "changes": [] }, "desc": "Invoked with a received message cannot be deserialized." } ], "signatures": [ { "params": [ { "textRaw": "`name` {any} The name of the channel to connect to. Any JavaScript value that can be converted to a string using ``${name}`` is permitted.", "name": "name", "type": "any", "desc": "The name of the channel to connect to. Any JavaScript value that can be converted to a string using ``${name}`` is permitted." } ] } ] }, { "textRaw": "Class: `MessageChannel`", "type": "class", "name": "MessageChannel", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

Instances of the worker.MessageChannel class represent an asynchronous,\ntwo-way communications channel.\nThe MessageChannel has no methods of its own. new MessageChannel()\nyields an object with port1 and port2 properties, which refer to linked\nMessagePort instances.

\n
const { MessageChannel } = require('worker_threads');\n\nconst { port1, port2 } = new MessageChannel();\nport1.on('message', (message) => console.log('received', message));\nport2.postMessage({ foo: 'bar' });\n// Prints: received { foo: 'bar' } from the `port1.on('message')` listener\n
" }, { "textRaw": "Class: `MessagePort`", "type": "class", "name": "MessagePort", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": [ "v14.7.0" ], "pr-url": "https://github.com/nodejs/node/pull/34057", "description": "This class now inherits from `EventTarget` rather than from `EventEmitter`." } ] }, "desc": "\n

Instances of the worker.MessagePort class represent one end of an\nasynchronous, two-way communications channel. It can be used to transfer\nstructured data, memory regions and other MessagePorts between different\nWorkers.

\n

This implementation matches browser MessagePorts.

", "events": [ { "textRaw": "Event: `'close'`", "type": "event", "name": "close", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted once either side of the channel has been\ndisconnected.

\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\n// Prints:\n//   foobar\n//   closed!\nport2.on('message', (message) => console.log(message));\nport2.on('close', () => console.log('closed!'));\n\nport1.postMessage('foobar');\nport1.close();\n
" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`value` {any} The transmitted value", "name": "value", "type": "any", "desc": "The transmitted value" } ], "desc": "

The 'message' event is emitted for any incoming message, containing the cloned\ninput of port.postMessage().

\n

Listeners on this event receive a clone of the value parameter as passed\nto postMessage() and no further arguments.

" }, { "textRaw": "Event: `'messageerror'`", "type": "event", "name": "messageerror", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error} An Error object", "name": "error", "type": "Error", "desc": "An Error object" } ], "desc": "

The 'messageerror' event is emitted when deserializing a message failed.

\n

Currently, this event is emitted when there is an error occurring while\ninstantiating the posted JS object on the receiving end. Such situations\nare rare, but can happen, for instance, when certain Node.js API objects\nare received in a vm.Context (where Node.js APIs are currently\nunavailable).

" } ], "methods": [ { "textRaw": "`port.close()`", "type": "method", "name": "close", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Disables further sending of messages on either side of the connection.\nThis method can be called when no further communication will happen over this\nMessagePort.

\n

The 'close' event is emitted on both MessagePort instances that\nare part of the channel.

" }, { "textRaw": "`port.postMessage(value[, transferList])`", "type": "method", "name": "postMessage", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v15.14.0", "pr-url": "https://github.com/nodejs/node/pull/37917", "description": "Add 'BlockList' to the list of cloneable types." }, { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37155", "description": "Add 'Histogram' types to the list of cloneable types." }, { "version": "v15.6.0", "pr-url": "https://github.com/nodejs/node/pull/36804", "description": "Added `X509Certificate` to the list of cloneable types." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "Added `CryptoKey` to the list of cloneable types." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33360", "description": "Added `KeyObject` to the list of cloneable types." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33772", "description": "Added `FileHandle` to the list of transferable types." } ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`transferList` {Object[]}", "name": "transferList", "type": "Object[]" } ] } ], "desc": "

Sends a JavaScript value to the receiving side of this channel.\nvalue is transferred in a way which is compatible with\nthe HTML structured clone algorithm.

\n

In particular, the significant differences to JSON are:

\n\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst circularData = {};\ncircularData.foo = circularData;\n// Prints: { foo: [Circular] }\nport2.postMessage(circularData);\n
\n

transferList may be a list of ArrayBuffer, MessagePort and\nFileHandle objects.\nAfter transferring, they are not usable on the sending side of the channel\nanymore (even if they are not contained in value). Unlike with\nchild processes, transferring handles such as network sockets is currently\nnot supported.

\n

If value contains SharedArrayBuffer instances, those are accessible\nfrom either thread. They cannot be listed in transferList.

\n

value may still contain ArrayBuffer instances that are not in\ntransferList; in that case, the underlying memory is copied rather than moved.

\n
const { MessageChannel } = require('worker_threads');\nconst { port1, port2 } = new MessageChannel();\n\nport1.on('message', (message) => console.log(message));\n\nconst uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);\n// This posts a copy of `uint8Array`:\nport2.postMessage(uint8Array);\n// This does not copy data, but renders `uint8Array` unusable:\nport2.postMessage(uint8Array, [ uint8Array.buffer ]);\n\n// The memory for the `sharedUint8Array` is accessible from both the\n// original and the copy received by `.on('message')`:\nconst sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));\nport2.postMessage(sharedUint8Array);\n\n// This transfers a freshly created message port to the receiver.\n// This can be used, for example, to create communication channels between\n// multiple `Worker` threads that are children of the same parent thread.\nconst otherChannel = new MessageChannel();\nport2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);\n
\n

The message object is cloned immediately, and can be modified after\nposting without having side effects.

\n

For more information on the serialization and deserialization mechanisms\nbehind this API, see the serialization API of the v8 module.

", "modules": [ { "textRaw": "Considerations when transferring TypedArrays and Buffers", "name": "considerations_when_transferring_typedarrays_and_buffers", "desc": "

All TypedArray and Buffer instances are views over an underlying\nArrayBuffer. That is, it is the ArrayBuffer that actually stores\nthe raw data while the TypedArray and Buffer objects provide a\nway of viewing and manipulating the data. It is possible and common\nfor multiple views to be created over the same ArrayBuffer instance.\nGreat care must be taken when using a transfer list to transfer an\nArrayBuffer as doing so causes all TypedArray and Buffer\ninstances that share that same ArrayBuffer to become unusable.

\n
const ab = new ArrayBuffer(10);\n\nconst u1 = new Uint8Array(ab);\nconst u2 = new Uint16Array(ab);\n\nconsole.log(u2.length);  // prints 5\n\nport.postMessage(u1, [u1.buffer]);\n\nconsole.log(u2.length);  // prints 0\n
\n

For Buffer instances, specifically, whether the underlying\nArrayBuffer can be transferred or cloned depends entirely on how\ninstances were created, which often cannot be reliably determined.

\n

An ArrayBuffer can be marked with markAsUntransferable() to indicate\nthat it should always be cloned and never transferred.

\n

Depending on how a Buffer instance was created, it may or may\nnot own its underlying ArrayBuffer. An ArrayBuffer must not\nbe transferred unless it is known that the Buffer instance\nowns it. In particular, for Buffers created from the internal\nBuffer pool (using, for instance Buffer.from() or Buffer.allocUnsafe()),\ntransferring them is not possible and they are always cloned,\nwhich sends a copy of the entire Buffer pool.\nThis behavior may come with unintended higher memory\nusage and possible security concerns.

\n

See Buffer.allocUnsafe() for more details on Buffer pooling.

\n

The ArrayBuffers for Buffer instances created using\nBuffer.alloc() or Buffer.allocUnsafeSlow() can always be\ntransferred but doing so renders all other existing views of\nthose ArrayBuffers unusable.

", "type": "module", "displayName": "Considerations when transferring TypedArrays and Buffers" }, { "textRaw": "Considerations when cloning objects with prototypes, classes, and accessors", "name": "considerations_when_cloning_objects_with_prototypes,_classes,_and_accessors", "desc": "

Because object cloning uses the HTML structured clone algorithm,\nnon-enumerable properties, property accessors, and object prototypes are\nnot preserved. In particular, Buffer objects will be read as\nplain Uint8Arrays on the receiving side, and instances of JavaScript\nclasses will be cloned as plain JavaScript objects.

\n
const b = Symbol('b');\n\nclass Foo {\n  #a = 1;\n  constructor() {\n    this[b] = 2;\n    this.c = 3;\n  }\n\n  get d() { return 4; }\n}\n\nconst { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new Foo());\n\n// Prints: { c: 3 }\n
\n

This limitation extends to many built-in objects, such as the global URL\nobject:

\n
const { port1, port2 } = new MessageChannel();\n\nport1.onmessage = ({ data }) => console.log(data);\n\nport2.postMessage(new URL('https://example.org'));\n\n// Prints: { }\n
", "type": "module", "displayName": "Considerations when cloning objects with prototypes, classes, and accessors" } ] }, { "textRaw": "`port.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Opposite of unref(). Calling ref() on a previously unref()ed port does\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the port is ref()ed, calling ref() again has no effect.

\n

If listeners are attached or removed using .on('message'), the port\nis ref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

" }, { "textRaw": "`port.start()`", "type": "method", "name": "start", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Starts receiving messages on this MessagePort. When using this port\nas an event emitter, this is called automatically once 'message'\nlisteners are attached.

\n

This method exists for parity with the Web MessagePort API. In Node.js,\nit is only useful for ignoring messages when no event listener is present.\nNode.js also diverges in its handling of .onmessage. Setting it\nautomatically calls .start(), but unsetting it lets messages queue up\nuntil a new handler is set or the port is discarded.

" }, { "textRaw": "`port.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calling unref() on a port allows the thread to exit if this is the only\nactive handle in the event system. If the port is already unref()ed calling\nunref() again has no effect.

\n

If listeners are attached or removed using .on('message'), the port is\nref()ed and unref()ed automatically depending on whether\nlisteners for the event exist.

" } ] }, { "textRaw": "Class: `Worker`", "type": "class", "name": "Worker", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "\n

The Worker class represents an independent JavaScript execution thread.\nMost Node.js APIs are available inside of it.

\n

Notable differences inside a Worker environment are:

\n\n

Creating Worker instances inside of other Workers is possible.

\n

Like Web Workers and the cluster module, two-way communication can be\nachieved through inter-thread message passing. Internally, a Worker has a\nbuilt-in pair of MessagePorts that are already associated with each other\nwhen the Worker is created. While the MessagePort object on the parent side\nis not directly exposed, its functionalities are exposed through\nworker.postMessage() and the worker.on('message') event\non the Worker object for the parent thread.

\n

To create custom messaging channels (which is encouraged over using the default\nglobal channel because it facilitates separation of concerns), users can create\na MessageChannel object on either thread and pass one of the\nMessagePorts on that MessageChannel to the other thread through a\npre-existing channel, such as the global one.

\n

See port.postMessage() for more information on how messages are passed,\nand what kind of JavaScript values can be successfully transported through\nthe thread barrier.

\n
const assert = require('assert');\nconst {\n  Worker, MessageChannel, MessagePort, isMainThread, parentPort\n} = require('worker_threads');\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  const subChannel = new MessageChannel();\n  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);\n  subChannel.port2.on('message', (value) => {\n    console.log('received:', value);\n  });\n} else {\n  parentPort.once('message', (value) => {\n    assert(value.hereIsYourPort instanceof MessagePort);\n    value.hereIsYourPort.postMessage('the worker is sending this');\n    value.hereIsYourPort.close();\n  });\n}\n
", "events": [ { "textRaw": "Event: `'error'`", "type": "event", "name": "error", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" } ], "desc": "

The 'error' event is emitted if the worker thread throws an uncaught\nexception. In that case, the worker is terminated.

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`exitCode` {integer}", "name": "exitCode", "type": "integer" } ], "desc": "

The 'exit' event is emitted once the worker has stopped. If the worker\nexited by calling process.exit(), the exitCode parameter is the\npassed exit code. If the worker was terminated, the exitCode parameter is\n1.

\n

This is the final event emitted by any Worker instance.

" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [ { "textRaw": "`value` {any} The transmitted value", "name": "value", "type": "any", "desc": "The transmitted value" } ], "desc": "

The 'message' event is emitted when the worker thread has invoked\nrequire('worker_threads').parentPort.postMessage().\nSee the port.on('message') event for more details.

\n

All messages sent from the worker thread are emitted before the\n'exit' event is emitted on the Worker object.

" }, { "textRaw": "Event: `'messageerror'`", "type": "event", "name": "messageerror", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error} An Error object", "name": "error", "type": "Error", "desc": "An Error object" } ], "desc": "

The 'messageerror' event is emitted when deserializing a message failed.

" }, { "textRaw": "Event: `'online'`", "type": "event", "name": "online", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "params": [], "desc": "

The 'online' event is emitted when the worker thread has started executing\nJavaScript code.

" } ], "methods": [ { "textRaw": "`worker.getHeapSnapshot()`", "type": "method", "name": "getHeapSnapshot", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise} A promise for a Readable Stream containing a V8 heap snapshot", "name": "return", "type": "Promise", "desc": "A promise for a Readable Stream containing a V8 heap snapshot" }, "params": [] } ], "desc": "

Returns a readable stream for a V8 snapshot of the current state of the Worker.\nSee v8.getHeapSnapshot() for more details.

\n

If the Worker thread is no longer running, which may occur before the\n'exit' event is emitted, the returned Promise is rejected\nimmediately with an ERR_WORKER_NOT_RUNNING error.

" }, { "textRaw": "`worker.postMessage(value[, transferList])`", "type": "method", "name": "postMessage", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`value` {any}", "name": "value", "type": "any" }, { "textRaw": "`transferList` {Object[]}", "name": "transferList", "type": "Object[]" } ] } ], "desc": "

Send a message to the worker that is received via\nrequire('worker_threads').parentPort.on('message').\nSee port.postMessage() for more details.

" }, { "textRaw": "`worker.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Opposite of unref(), calling ref() on a previously unref()ed worker does\nnot let the program exit if it's the only active handle left (the default\nbehavior). If the worker is ref()ed, calling ref() again has\nno effect.

" }, { "textRaw": "`worker.terminate()`", "type": "method", "name": "terminate", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v12.5.0", "pr-url": "https://github.com/nodejs/node/pull/28021", "description": "This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Promise}", "name": "return", "type": "Promise" }, "params": [] } ], "desc": "

Stop all JavaScript execution in the worker thread as soon as possible.\nReturns a Promise for the exit code that is fulfilled when the\n'exit' event is emitted.

" }, { "textRaw": "`worker.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calling unref() on a worker allows the thread to exit if this is the only\nactive handle in the event system. If the worker is already unref()ed calling\nunref() again has no effect.

" } ], "properties": [ { "textRaw": "`worker.performance`", "name": "performance", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "desc": "

An object that can be used to query performance information from a worker\ninstance. Similar to perf_hooks.performance.

", "methods": [ { "textRaw": "`performance.eventLoopUtilization([utilization1[, utilization2]])`", "type": "method", "name": "eventLoopUtilization", "meta": { "added": [ "v15.1.0", "v12.22.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`idle` {number}", "name": "idle", "type": "number" }, { "textRaw": "`active` {number}", "name": "active", "type": "number" }, { "textRaw": "`utilization` {number}", "name": "utilization", "type": "number" } ] }, "params": [ { "textRaw": "`utilization1` {Object} The result of a previous call to `eventLoopUtilization()`.", "name": "utilization1", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()`." }, { "textRaw": "`utilization2` {Object} The result of a previous call to `eventLoopUtilization()` prior to `utilization1`.", "name": "utilization2", "type": "Object", "desc": "The result of a previous call to `eventLoopUtilization()` prior to `utilization1`." } ] } ], "desc": "

The same call as perf_hooks eventLoopUtilization(), except the values\nof the worker instance are returned.

\n

One difference is that, unlike the main thread, bootstrapping within a worker\nis done within the event loop. So the event loop utilization is\nimmediately available once the worker's script begins execution.

\n

An idle time that does not increase does not indicate that the worker is\nstuck in bootstrap. The following examples shows how the worker's entire\nlifetime never accumulates any idle time, but is still be able to process\nmessages.

\n
const { Worker, isMainThread, parentPort } = require('worker_threads');\n\nif (isMainThread) {\n  const worker = new Worker(__filename);\n  setInterval(() => {\n    worker.postMessage('hi');\n    console.log(worker.performance.eventLoopUtilization());\n  }, 100).unref();\n  return;\n}\n\nparentPort.on('message', () => console.log('msg')).unref();\n(function r(n) {\n  if (--n < 0) return;\n  const t = Date.now();\n  while (Date.now() - t < 300);\n  setImmediate(r, n);\n})(10);\n
\n

The event loop utilization of a worker is available only after the 'online'\nevent emitted, and if called before this, or after the 'exit'\nevent, then all properties have the value of 0.

" } ] }, { "textRaw": "`resourceLimits` {Object}", "type": "Object", "name": "resourceLimits", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "options": [ { "textRaw": "`maxYoungGenerationSizeMb` {number}", "name": "maxYoungGenerationSizeMb", "type": "number" }, { "textRaw": "`maxOldGenerationSizeMb` {number}", "name": "maxOldGenerationSizeMb", "type": "number" }, { "textRaw": "`codeRangeSizeMb` {number}", "name": "codeRangeSizeMb", "type": "number" }, { "textRaw": "`stackSizeMb` {number}", "name": "stackSizeMb", "type": "number" } ], "desc": "

Provides the set of JS engine resource constraints for this Worker thread.\nIf the resourceLimits option was passed to the Worker constructor,\nthis matches its values.

\n

If the worker has stopped, the return value is an empty object.

" }, { "textRaw": "`stderr` {stream.Readable}", "type": "stream.Readable", "name": "stderr", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

This is a readable stream which contains data written to process.stderr\ninside the worker thread. If stderr: true was not passed to the\nWorker constructor, then data is piped to the parent thread's\nprocess.stderr stream.

" }, { "textRaw": "`stdin` {null|stream.Writable}", "type": "null|stream.Writable", "name": "stdin", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

If stdin: true was passed to the Worker constructor, this is a\nwritable stream. The data written to this stream will be made available in\nthe worker thread as process.stdin.

" }, { "textRaw": "`stdout` {stream.Readable}", "type": "stream.Readable", "name": "stdout", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

This is a readable stream which contains data written to process.stdout\ninside the worker thread. If stdout: true was not passed to the\nWorker constructor, then data is piped to the parent thread's\nprocess.stdout stream.

" }, { "textRaw": "`threadId` {integer}", "type": "integer", "name": "threadId", "meta": { "added": [ "v10.5.0" ], "changes": [] }, "desc": "

An integer identifier for the referenced thread. Inside the worker thread,\nit is available as require('worker_threads').threadId.\nThis value is unique for each Worker instance inside a single process.

" } ], "signatures": [ { "params": [ { "textRaw": "`filename` {string|URL} The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path.", "name": "filename", "type": "string|URL", "desc": "The path to the Worker’s main script or module. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with `./` or `../`, or a WHATWG `URL` object using `file:` or `data:` protocol. When using a [`data:` URL][], the data is interpreted based on MIME type using the [ECMAScript module loader][]. If `options.eval` is `true`, this is a string containing JavaScript code rather than a path." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`argv` {any[]} List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values are available on the global `process.argv` as if they were passed as CLI options to the script.", "name": "argv", "type": "any[]", "desc": "List of arguments which would be stringified and appended to `process.argv` in the worker. This is mostly similar to the `workerData` but the values are available on the global `process.argv` as if they were passed as CLI options to the script." }, { "textRaw": "`env` {Object} If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object affect the other thread as well. **Default:** `process.env`.", "name": "env", "type": "Object", "default": "`process.env`", "desc": "If set, specifies the initial value of `process.env` inside the Worker thread. As a special value, [`worker.SHARE_ENV`][] may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread’s `process.env` object affect the other thread as well." }, { "textRaw": "`eval` {boolean} If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online.", "name": "eval", "type": "boolean", "desc": "If `true` and the first argument is a `string`, interpret the first argument to the constructor as a script that is executed once the worker is online." }, { "textRaw": "`execArgv` {string[]} List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this is provided as [`process.execArgv`][] inside the worker. By default, options are inherited from the parent thread.", "name": "execArgv", "type": "string[]", "desc": "List of node CLI options passed to the worker. V8 options (such as `--max-old-space-size`) and options that affect the process (such as `--title`) are not supported. If set, this is provided as [`process.execArgv`][] inside the worker. By default, options are inherited from the parent thread." }, { "textRaw": "`stdin` {boolean} If this is set to `true`, then `worker.stdin` provides a writable stream whose contents appear as `process.stdin` inside the Worker. By default, no data is provided.", "name": "stdin", "type": "boolean", "desc": "If this is set to `true`, then `worker.stdin` provides a writable stream whose contents appear as `process.stdin` inside the Worker. By default, no data is provided." }, { "textRaw": "`stdout` {boolean} If this is set to `true`, then `worker.stdout` is not automatically piped through to `process.stdout` in the parent.", "name": "stdout", "type": "boolean", "desc": "If this is set to `true`, then `worker.stdout` is not automatically piped through to `process.stdout` in the parent." }, { "textRaw": "`stderr` {boolean} If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent.", "name": "stderr", "type": "boolean", "desc": "If this is set to `true`, then `worker.stderr` is not automatically piped through to `process.stderr` in the parent." }, { "textRaw": "`workerData` {any} Any JavaScript value that is cloned and made available as [`require('worker_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s).", "name": "workerData", "type": "any", "desc": "Any JavaScript value that is cloned and made available as [`require('worker_threads').workerData`][]. The cloning occurs as described in the [HTML structured clone algorithm][], and an error is thrown if the object cannot be cloned (e.g. because it contains `function`s)." }, { "textRaw": "`trackUnmanagedFds` {boolean} If this is set to `true`, then the Worker tracks raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and closes them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s. **Default:** `true`.", "name": "trackUnmanagedFds", "type": "boolean", "default": "`true`", "desc": "If this is set to `true`, then the Worker tracks raw file descriptors managed through [`fs.open()`][] and [`fs.close()`][], and closes them when the Worker exits, similar to other resources like network sockets or file descriptors managed through the [`FileHandle`][] API. This option is automatically inherited by all nested `Worker`s." }, { "textRaw": "`transferList` {Object[]} If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown. See [`port.postMessage()`][] for more information.", "name": "transferList", "type": "Object[]", "desc": "If one or more `MessagePort`-like objects are passed in `workerData`, a `transferList` is required for those items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown. See [`port.postMessage()`][] for more information." }, { "textRaw": "`resourceLimits` {Object} An optional set of resource limits for the new JS engine instance. Reaching these limits leads to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", "name": "resourceLimits", "type": "Object", "desc": "An optional set of resource limits for the new JS engine instance. Reaching these limits leads to termination of the `Worker` instance. These limits only affect the JS engine, and no external data, including no `ArrayBuffer`s. Even if these limits are set, the process may still abort if it encounters a global out-of-memory situation.", "options": [ { "textRaw": "`maxOldGenerationSizeMb` {number} The maximum size of the main heap in MB.", "name": "maxOldGenerationSizeMb", "type": "number", "desc": "The maximum size of the main heap in MB." }, { "textRaw": "`maxYoungGenerationSizeMb` {number} The maximum size of a heap space for recently created objects.", "name": "maxYoungGenerationSizeMb", "type": "number", "desc": "The maximum size of a heap space for recently created objects." }, { "textRaw": "`codeRangeSizeMb` {number} The size of a pre-allocated memory range used for generated code.", "name": "codeRangeSizeMb", "type": "number", "desc": "The size of a pre-allocated memory range used for generated code." }, { "textRaw": "`stackSizeMb` {number} The default maximum stack size for the thread. Small values may lead to unusable Worker instances. **Default:** `4`.", "name": "stackSizeMb", "type": "number", "default": "`4`", "desc": "The default maximum stack size for the thread. Small values may lead to unusable Worker instances." } ] } ] } ] } ] } ], "modules": [ { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Synchronous blocking of stdio", "name": "synchronous_blocking_of_stdio", "desc": "

Workers utilize message passing via <MessagePort> to implement interactions\nwith stdio. This means that stdio output originating from a Worker can\nget blocked by synchronous code on the receiving end that is blocking the\nNode.js event loop.

\n
import {\n  Worker,\n  isMainThread,\n} from 'worker_threads';\n\nif (isMainThread) {\n  new Worker(new URL(import.meta.url));\n  for (let n = 0; n < 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n
\n
'use strict';\n\nconst {\n  Worker,\n  isMainThread,\n} = require('worker_threads');\n\nif (isMainThread) {\n  new Worker(__filename);\n  for (let n = 0; n < 1e10; n++) {}\n} else {\n  // This output will be blocked by the for loop in the main thread.\n  console.log('foo');\n}\n
", "type": "module", "displayName": "Synchronous blocking of stdio" }, { "textRaw": "Launching worker threads from preload scripts", "name": "launching_worker_threads_from_preload_scripts", "desc": "

Take care when launching worker threads from preload scripts (scripts loaded\nand run using the -r command line flag). Unless the execArgv option is\nexplicitly set, new Worker threads automatically inherit the command line flags\nfrom the running process and will preload the same preload scripts as the main\nthread. If the preload script unconditionally launches a worker thread, every\nthread spawned will spawn another until the application crashes.

", "type": "module", "displayName": "Launching worker threads from preload scripts" } ], "type": "module", "displayName": "Notes" } ], "type": "module", "displayName": "Worker threads", "source": "doc/api/worker_threads.md" }, { "textRaw": "Zlib", "name": "zlib", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/zlib.js

\n

The zlib module provides compression functionality implemented using Gzip,\nDeflate/Inflate, and Brotli.

\n

To access it:

\n
const zlib = require('zlib');\n
\n

Compression and decompression are built around the Node.js Streams API.

\n

Compressing or decompressing a stream (such as a file) can be accomplished by\npiping the source stream through a zlib Transform stream into a destination\nstream:

\n
const { createGzip } = require('zlib');\nconst { pipeline } = require('stream');\nconst {\n  createReadStream,\n  createWriteStream\n} = require('fs');\n\nconst gzip = createGzip();\nconst source = createReadStream('input.txt');\nconst destination = createWriteStream('input.txt.gz');\n\npipeline(source, gzip, destination, (err) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst pipe = promisify(pipeline);\n\nasync function do_gzip(input, output) {\n  const gzip = createGzip();\n  const source = createReadStream(input);\n  const destination = createWriteStream(output);\n  await pipe(source, gzip, destination);\n}\n\ndo_gzip('input.txt', 'input.txt.gz')\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
\n

It is also possible to compress or decompress data in a single step:

\n
const { deflate, unzip } = require('zlib');\n\nconst input = '.................................';\ndeflate(input, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString('base64'));\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nunzip(buffer, (err, buffer) => {\n  if (err) {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  }\n  console.log(buffer.toString());\n});\n\n// Or, Promisified\n\nconst { promisify } = require('util');\nconst do_unzip = promisify(unzip);\n\ndo_unzip(buffer)\n  .then((buf) => console.log(buf.toString()))\n  .catch((err) => {\n    console.error('An error occurred:', err);\n    process.exitCode = 1;\n  });\n
", "modules": [ { "textRaw": "Threadpool usage and performance considerations", "name": "threadpool_usage_and_performance_considerations", "desc": "

All zlib APIs, except those that are explicitly synchronous, use the Node.js\ninternal threadpool. This can lead to surprising effects and performance\nlimitations in some applications.

\n

Creating and using a large number of zlib objects simultaneously can cause\nsignificant memory fragmentation.

\n
const zlib = require('zlib');\n\nconst payload = Buffer.from('This is some data');\n\n// WARNING: DO NOT DO THIS!\nfor (let i = 0; i < 30000; ++i) {\n  zlib.deflate(payload, (err, buffer) => {});\n}\n
\n

In the preceding example, 30,000 deflate instances are created concurrently.\nBecause of how some operating systems handle memory allocation and\ndeallocation, this may lead to to significant memory fragmentation.

\n

It is strongly recommended that the results of compression\noperations be cached to avoid duplication of effort.

", "type": "module", "displayName": "Threadpool usage and performance considerations" }, { "textRaw": "Compressing HTTP requests and responses", "name": "compressing_http_requests_and_responses", "desc": "

The zlib module can be used to implement support for the gzip, deflate\nand br content-encoding mechanisms defined by\nHTTP.

\n

The HTTP Accept-Encoding header is used within an http request to identify\nthe compression encodings accepted by the client. The Content-Encoding\nheader is used to identify the compression encodings actually applied to a\nmessage.

\n

The examples given below are drastically simplified to show the basic concept.\nUsing zlib encoding can be expensive, and the results ought to be cached.\nSee Memory usage tuning for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.

\n
// Client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nconst request = http.get({ host: 'example.com',\n                           path: '/',\n                           port: 80,\n                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });\nrequest.on('response', (response) => {\n  const output = fs.createWriteStream('example.com_index.html');\n\n  const onError = (err) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n  };\n\n  switch (response.headers['content-encoding']) {\n    case 'br':\n      pipeline(response, zlib.createBrotliDecompress(), output, onError);\n      break;\n    // Or, just use zlib.createUnzip() to handle both of the following cases:\n    case 'gzip':\n      pipeline(response, zlib.createGunzip(), output, onError);\n      break;\n    case 'deflate':\n      pipeline(response, zlib.createInflate(), output, onError);\n      break;\n    default:\n      pipeline(response, output, onError);\n      break;\n  }\n});\n
\n
// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  const raw = fs.createReadStream('index.html');\n  // Store both a compressed and an uncompressed version of the resource.\n  response.setHeader('Vary', 'Accept-Encoding');\n  let acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  const onError = (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  };\n\n  // Note: This is not a conformant accept-encoding parser.\n  // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (/\\bdeflate\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'deflate' });\n    pipeline(raw, zlib.createDeflate(), response, onError);\n  } else if (/\\bgzip\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'gzip' });\n    pipeline(raw, zlib.createGzip(), response, onError);\n  } else if (/\\bbr\\b/.test(acceptEncoding)) {\n    response.writeHead(200, { 'Content-Encoding': 'br' });\n    pipeline(raw, zlib.createBrotliCompress(), response, onError);\n  } else {\n    response.writeHead(200, {});\n    pipeline(raw, response, onError);\n  }\n}).listen(1337);\n
\n

By default, the zlib methods will throw an error when decompressing\ntruncated data. However, if it is known that the data is incomplete, or\nthe desire is to inspect only the beginning of a compressed file, it is\npossible to suppress the default error handling by changing the flushing\nmethod that is used to decompress the last chunk of input data:

\n
// This is a truncated version of the buffer from the above examples\nconst buffer = Buffer.from('eJzT0yMA', 'base64');\n\nzlib.unzip(\n  buffer,\n  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.\n  { finishFlush: zlib.constants.Z_SYNC_FLUSH },\n  (err, buffer) => {\n    if (err) {\n      console.error('An error occurred:', err);\n      process.exitCode = 1;\n    }\n    console.log(buffer.toString());\n  });\n
\n

This will not change the behavior in other error-throwing situations, e.g.\nwhen the input data has an invalid format. Using this method, it will not be\npossible to determine whether the input ended prematurely or lacks the\nintegrity checks, making it necessary to manually check that the\ndecompressed result is valid.

", "type": "module", "displayName": "Compressing HTTP requests and responses" }, { "textRaw": "Flushing", "name": "flushing", "desc": "

Calling .flush() on a compression stream will make zlib return as much\noutput as currently possible. This may come at the cost of degraded compression\nquality, but can be useful when data needs to be available as soon as possible.

\n

In the following example, flush() is used to write a compressed partial\nHTTP response to the client:

\n
const zlib = require('zlib');\nconst http = require('http');\nconst { pipeline } = require('stream');\n\nhttp.createServer((request, response) => {\n  // For the sake of simplicity, the Accept-Encoding checks are omitted.\n  response.writeHead(200, { 'content-encoding': 'gzip' });\n  const output = zlib.createGzip();\n  let i;\n\n  pipeline(output, response, (err) => {\n    if (err) {\n      // If an error occurs, there's not much we can do because\n      // the server has already sent the 200 response code and\n      // some amount of data has already been sent to the client.\n      // The best we can do is terminate the response immediately\n      // and log the error.\n      clearInterval(i);\n      response.end();\n      console.error('An error occurred:', err);\n    }\n  });\n\n  i = setInterval(() => {\n    output.write(`The current time is ${Date()}\\n`, () => {\n      // The data has been passed to zlib, but the compression algorithm may\n      // have decided to buffer the data for more efficient compression.\n      // Calling .flush() will make the data available as soon as the client\n      // is ready to receive it.\n      output.flush();\n    });\n  }, 1000);\n}).listen(1337);\n
", "type": "module", "displayName": "Flushing" } ], "miscs": [ { "textRaw": "Memory usage tuning", "name": "Memory usage tuning", "type": "misc", "miscs": [ { "textRaw": "For zlib-based streams", "name": "for_zlib-based_streams", "desc": "

From zlib/zconf.h, modified for Node.js usage:

\n

The memory requirements for deflate are (in bytes):

\n\n
(1 << (windowBits + 2)) + (1 << (memLevel + 9))\n
\n

That is: 128K for windowBits = 15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.

\n

For example, to reduce the default memory requirements from 256K to 128K, the\noptions should be set to:

\n
const options = { windowBits: 14, memLevel: 7 };\n
\n

This will, however, generally degrade compression.

\n

The memory requirements for inflate are (in bytes) 1 << windowBits.\nThat is, 32K for windowBits = 15 (default value) plus a few kilobytes\nfor small objects.

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.

\n

In general, greater memory usage options will mean that Node.js has to make\nfewer calls to zlib because it will be able to process more data on\neach write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.

", "type": "misc", "displayName": "For zlib-based streams" }, { "textRaw": "For Brotli-based streams", "name": "for_brotli-based_streams", "desc": "

There are equivalents to the zlib options for Brotli-based streams, although\nthese options have different ranges than the zlib ones:

\n
    \n
  • zlib’s level option matches Brotli’s BROTLI_PARAM_QUALITY option.
  • \n
  • zlib’s windowBits option matches Brotli’s BROTLI_PARAM_LGWIN option.
  • \n
\n

See below for more details on Brotli-specific options.

", "type": "misc", "displayName": "For Brotli-based streams" } ] }, { "textRaw": "Constants", "name": "Constants", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "type": "misc", "miscs": [ { "textRaw": "zlib constants", "name": "zlib_constants", "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').constants. In the normal course of operations, it will not be\nnecessary to use these constants. They are documented so that their presence is\nnot surprising. This section is taken almost directly from the\nzlib documentation.

\n

Previously, the constants were available directly from require('zlib'), for\ninstance zlib.Z_NO_FLUSH. Accessing the constants directly from the module is\ncurrently still possible but is deprecated.

\n

Allowed flush values.

\n
    \n
  • zlib.constants.Z_NO_FLUSH
  • \n
  • zlib.constants.Z_PARTIAL_FLUSH
  • \n
  • zlib.constants.Z_SYNC_FLUSH
  • \n
  • zlib.constants.Z_FULL_FLUSH
  • \n
  • zlib.constants.Z_FINISH
  • \n
  • zlib.constants.Z_BLOCK
  • \n
  • zlib.constants.Z_TREES
  • \n
\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.

\n
    \n
  • zlib.constants.Z_OK
  • \n
  • zlib.constants.Z_STREAM_END
  • \n
  • zlib.constants.Z_NEED_DICT
  • \n
  • zlib.constants.Z_ERRNO
  • \n
  • zlib.constants.Z_STREAM_ERROR
  • \n
  • zlib.constants.Z_DATA_ERROR
  • \n
  • zlib.constants.Z_MEM_ERROR
  • \n
  • zlib.constants.Z_BUF_ERROR
  • \n
  • zlib.constants.Z_VERSION_ERROR
  • \n
\n

Compression levels.

\n
    \n
  • zlib.constants.Z_NO_COMPRESSION
  • \n
  • zlib.constants.Z_BEST_SPEED
  • \n
  • zlib.constants.Z_BEST_COMPRESSION
  • \n
  • zlib.constants.Z_DEFAULT_COMPRESSION
  • \n
\n

Compression strategy.

\n
    \n
  • zlib.constants.Z_FILTERED
  • \n
  • zlib.constants.Z_HUFFMAN_ONLY
  • \n
  • zlib.constants.Z_RLE
  • \n
  • zlib.constants.Z_FIXED
  • \n
  • zlib.constants.Z_DEFAULT_STRATEGY
  • \n
", "type": "misc", "displayName": "zlib constants" }, { "textRaw": "Brotli constants", "name": "brotli_constants", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "desc": "

There are several options and other constants available for Brotli-based\nstreams:

", "modules": [ { "textRaw": "Flush operations", "name": "flush_operations", "desc": "

The following values are valid flush operations for Brotli-based streams:

\n
    \n
  • zlib.constants.BROTLI_OPERATION_PROCESS (default for all operations)
  • \n
  • zlib.constants.BROTLI_OPERATION_FLUSH (default when calling .flush())
  • \n
  • zlib.constants.BROTLI_OPERATION_FINISH (default for the last chunk)
  • \n
  • zlib.constants.BROTLI_OPERATION_EMIT_METADATA\n
      \n
    • This particular operation may be hard to use in a Node.js context,\nas the streaming layer makes it hard to know which data will end up\nin this frame. Also, there is currently no way to consume this data through\nthe Node.js API.
    • \n
    \n
  • \n
", "type": "module", "displayName": "Flush operations" }, { "textRaw": "Compressor options", "name": "compressor_options", "desc": "

There are several options that can be set on Brotli encoders, affecting\ncompression efficiency and speed. Both the keys and the values can be accessed\nas properties of the zlib.constants object.

\n

The most important options are:

\n
    \n
  • BROTLI_PARAM_MODE\n
      \n
    • BROTLI_MODE_GENERIC (default)
    • \n
    • BROTLI_MODE_TEXT, adjusted for UTF-8 text
    • \n
    • BROTLI_MODE_FONT, adjusted for WOFF 2.0 fonts
    • \n
    \n
  • \n
  • BROTLI_PARAM_QUALITY\n
      \n
    • Ranges from BROTLI_MIN_QUALITY to BROTLI_MAX_QUALITY,\nwith a default of BROTLI_DEFAULT_QUALITY.
    • \n
    \n
  • \n
  • BROTLI_PARAM_SIZE_HINT\n
      \n
    • Integer value representing the expected input size;\ndefaults to 0 for an unknown input size.
    • \n
    \n
  • \n
\n

The following flags can be set for advanced control over the compression\nalgorithm and memory usage tuning:

\n
    \n
  • BROTLI_PARAM_LGWIN\n
      \n
    • Ranges from BROTLI_MIN_WINDOW_BITS to BROTLI_MAX_WINDOW_BITS,\nwith a default of BROTLI_DEFAULT_WINDOW, or up to\nBROTLI_LARGE_MAX_WINDOW_BITS if the BROTLI_PARAM_LARGE_WINDOW flag\nis set.
    • \n
    \n
  • \n
  • BROTLI_PARAM_LGBLOCK\n
      \n
    • Ranges from BROTLI_MIN_INPUT_BLOCK_BITS to BROTLI_MAX_INPUT_BLOCK_BITS.
    • \n
    \n
  • \n
  • BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING\n
      \n
    • Boolean flag that decreases compression ratio in favour of\ndecompression speed.
    • \n
    \n
  • \n
  • BROTLI_PARAM_LARGE_WINDOW\n
      \n
    • Boolean flag enabling “Large Window Brotli” mode (not compatible with the\nBrotli format as standardized in RFC 7932).
    • \n
    \n
  • \n
  • BROTLI_PARAM_NPOSTFIX\n
      \n
    • Ranges from 0 to BROTLI_MAX_NPOSTFIX.
    • \n
    \n
  • \n
  • BROTLI_PARAM_NDIRECT\n
      \n
    • Ranges from 0 to 15 << NPOSTFIX in steps of 1 << NPOSTFIX.
    • \n
    \n
  • \n
", "type": "module", "displayName": "Compressor options" }, { "textRaw": "Decompressor options", "name": "decompressor_options", "desc": "

These advanced options are available for controlling decompression:

\n
    \n
  • BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION\n
      \n
    • Boolean flag that affects internal memory allocation patterns.
    • \n
    \n
  • \n
  • BROTLI_DECODER_PARAM_LARGE_WINDOW\n
      \n
    • Boolean flag enabling “Large Window Brotli” mode (not compatible with the\nBrotli format as standardized in RFC 7932).
    • \n
    \n
  • \n
", "type": "module", "displayName": "Decompressor options" } ], "type": "misc", "displayName": "Brotli constants" } ] }, { "textRaw": "Class: `Options`", "type": "misc", "name": "Options", "meta": { "added": [ "v0.11.1" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33516", "description": "The `maxOutputLength` option is supported now." }, { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `dictionary` option can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `dictionary` option can be an `Uint8Array` now." }, { "version": "v5.11.0", "pr-url": "https://github.com/nodejs/node/pull/6069", "description": "The `finishFlush` option is supported now." } ] }, "desc": "

Each zlib-based class takes an options object. No options are required.

\n

Some options are only relevant when compressing and are\nignored by the decompression classes.

\n\n

See the deflateInit2 and inflateInit2 documentation for more\ninformation.

" }, { "textRaw": "Class: `BrotliOptions`", "type": "misc", "name": "BrotliOptions", "meta": { "added": [ "v11.7.0" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33516", "description": "The `maxOutputLength` option is supported now." } ] }, "desc": "

Each Brotli-based class takes an options object. All options are optional.

\n\n

For example:

\n
const stream = zlib.createBrotliCompress({\n  chunkSize: 32 * 1024,\n  params: {\n    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,\n    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,\n    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size\n  }\n});\n
" }, { "textRaw": "Convenience methods", "name": "Convenience methods", "type": "misc", "desc": "

All of these take a Buffer, TypedArray, DataView,\nArrayBuffer or string as the first argument, an optional second argument\nto supply options to the zlib classes and will call the supplied callback\nwith callback(error, result).

\n

Every method has a *Sync counterpart, which accept the same arguments, but\nwithout a callback.

", "methods": [ { "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", "type": "method", "name": "brotliCompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", "type": "method", "name": "brotliCompressSync", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Compress a chunk of data with BrotliCompress.

" }, { "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", "type": "method", "name": "brotliDecompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", "type": "method", "name": "brotliDecompressSync", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Decompress a chunk of data with BrotliDecompress.

" }, { "textRaw": "`zlib.deflate(buffer[, options], callback)`", "type": "method", "name": "deflate", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.deflateSync(buffer[, options])`", "type": "method", "name": "deflateSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with Deflate.

" }, { "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", "type": "method", "name": "deflateRaw", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.deflateRawSync(buffer[, options])`", "type": "method", "name": "deflateRawSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with DeflateRaw.

" }, { "textRaw": "`zlib.gunzip(buffer[, options], callback)`", "type": "method", "name": "gunzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.gunzipSync(buffer[, options])`", "type": "method", "name": "gunzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Gunzip.

" }, { "textRaw": "`zlib.gzip(buffer[, options], callback)`", "type": "method", "name": "gzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.gzipSync(buffer[, options])`", "type": "method", "name": "gzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with Gzip.

" }, { "textRaw": "`zlib.inflate(buffer[, options], callback)`", "type": "method", "name": "inflate", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.inflateSync(buffer[, options])`", "type": "method", "name": "inflateSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Inflate.

" }, { "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", "type": "method", "name": "inflateRaw", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.inflateRawSync(buffer[, options])`", "type": "method", "name": "inflateRawSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with InflateRaw.

" }, { "textRaw": "`zlib.unzip(buffer[, options], callback)`", "type": "method", "name": "unzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.unzipSync(buffer[, options])`", "type": "method", "name": "unzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Unzip.

" } ] } ], "meta": { "added": [ "v0.5.8" ], "changes": [] }, "classes": [ { "textRaw": "Class: `zlib.BrotliCompress`", "type": "class", "name": "zlib.BrotliCompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "desc": "

Compress data using the Brotli algorithm.

" }, { "textRaw": "Class: `zlib.BrotliDecompress`", "type": "class", "name": "zlib.BrotliDecompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "desc": "

Decompress data using the Brotli algorithm.

" }, { "textRaw": "Class: `zlib.Deflate`", "type": "class", "name": "zlib.Deflate", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

Compress data using deflate.

" }, { "textRaw": "Class: `zlib.DeflateRaw`", "type": "class", "name": "zlib.DeflateRaw", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

Compress data using deflate, and do not append a zlib header.

" }, { "textRaw": "Class: `zlib.Gunzip`", "type": "class", "name": "zlib.Gunzip", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5883", "description": "Trailing garbage at the end of the input stream will now result in an `'error'` event." }, { "version": "v5.9.0", "pr-url": "https://github.com/nodejs/node/pull/5120", "description": "Multiple concatenated gzip file members are supported now." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2595", "description": "A truncated input stream will now result in an `'error'` event." } ] }, "desc": "

Decompress a gzip stream.

" }, { "textRaw": "Class: `zlib.Gzip`", "type": "class", "name": "zlib.Gzip", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

Compress data using gzip.

" }, { "textRaw": "Class: `zlib.Inflate`", "type": "class", "name": "zlib.Inflate", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2595", "description": "A truncated input stream will now result in an `'error'` event." } ] }, "desc": "

Decompress a deflate stream.

" }, { "textRaw": "Class: `zlib.InflateRaw`", "type": "class", "name": "zlib.InflateRaw", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v6.8.0", "pr-url": "https://github.com/nodejs/node/pull/8512", "description": "Custom dictionaries are now supported by `InflateRaw`." }, { "version": "v5.0.0", "pr-url": "https://github.com/nodejs/node/pull/2595", "description": "A truncated input stream will now result in an `'error'` event." } ] }, "desc": "

Decompress a raw deflate stream.

" }, { "textRaw": "Class: `zlib.Unzip`", "type": "class", "name": "zlib.Unzip", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.

" }, { "textRaw": "Class: `zlib.ZlibBase`", "type": "class", "name": "zlib.ZlibBase", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": [ "v11.7.0", "v10.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/24939", "description": "This class was renamed from `Zlib` to `ZlibBase`." } ] }, "desc": "

Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.

\n

This class inherits from stream.Transform, allowing zlib objects to be\nused in pipes and similar stream operations.

", "properties": [ { "textRaw": "`bytesRead` {number}", "type": "number", "name": "bytesRead", "meta": { "added": [ "v8.1.0" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`zlib.bytesWritten`][] instead.", "desc": "

Deprecated 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.

" }, { "textRaw": "`bytesWritten` {number}", "type": "number", "name": "bytesWritten", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

The zlib.bytesWritten property specifies the number of bytes written to\nthe engine, before the bytes are processed (compressed or decompressed,\nas appropriate for the derived class).

" } ], "methods": [ { "textRaw": "`zlib.close([callback])`", "type": "method", "name": "close", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Close the underlying handle.

" }, { "textRaw": "`zlib.flush([kind, ]callback)`", "type": "method", "name": "flush", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.", "name": "kind", "default": "`zlib.constants.Z_FULL_FLUSH` for zlib-based streams, `zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.

\n

Calling this only flushes data from the internal zlib state, and does not\nperform flushing of any kind on the streams level. Rather, it behaves like a\nnormal call to .write(), i.e. it will be queued up behind other pending\nwrites and will only produce output when data is being read from the stream.

" }, { "textRaw": "`zlib.params(level, strategy, callback)`", "type": "method", "name": "params", "meta": { "added": [ "v0.11.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`level` {integer}", "name": "level", "type": "integer" }, { "textRaw": "`strategy` {integer}", "name": "strategy", "type": "integer" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

This function is only available for zlib-based streams, i.e. not Brotli.

\n

Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.

" }, { "textRaw": "`zlib.reset()`", "type": "method", "name": "reset", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.

" } ] } ], "properties": [ { "textRaw": "`zlib.constants`", "name": "constants", "meta": { "added": [ "v7.0.0" ], "changes": [] }, "desc": "

Provides an object enumerating Zlib-related constants.

" } ], "methods": [ { "textRaw": "`zlib.createBrotliCompress([options])`", "type": "method", "name": "createBrotliCompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Creates and returns a new BrotliCompress object.

" }, { "textRaw": "`zlib.createBrotliDecompress([options])`", "type": "method", "name": "createBrotliDecompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Creates and returns a new BrotliDecompress object.

" }, { "textRaw": "`zlib.createDeflate([options])`", "type": "method", "name": "createDeflate", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new Deflate object.

" }, { "textRaw": "`zlib.createDeflateRaw([options])`", "type": "method", "name": "createDeflateRaw", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new DeflateRaw object.

\n

An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits\nis set to 8 for raw deflate streams. zlib would automatically set windowBits\nto 9 if was initially set to 8. Newer versions of zlib will throw an exception,\nso Node.js restored the original behavior of upgrading a value of 8 to 9,\nsince passing windowBits = 9 to zlib actually results in a compressed stream\nthat effectively uses an 8-bit window only.

" }, { "textRaw": "`zlib.createGunzip([options])`", "type": "method", "name": "createGunzip", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new Gunzip object.

" }, { "textRaw": "`zlib.createGzip([options])`", "type": "method", "name": "createGzip", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new Gzip object.\nSee example.

" }, { "textRaw": "`zlib.createInflate([options])`", "type": "method", "name": "createInflate", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new Inflate object.

" }, { "textRaw": "`zlib.createInflateRaw([options])`", "type": "method", "name": "createInflateRaw", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new InflateRaw object.

" }, { "textRaw": "`zlib.createUnzip([options])`", "type": "method", "name": "createUnzip", "meta": { "added": [ "v0.5.8" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Creates and returns a new Unzip object.

" }, { "textRaw": "`zlib.brotliCompress(buffer[, options], callback)`", "type": "method", "name": "brotliCompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.brotliCompressSync(buffer[, options])`", "type": "method", "name": "brotliCompressSync", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Compress a chunk of data with BrotliCompress.

" }, { "textRaw": "`zlib.brotliDecompress(buffer[, options], callback)`", "type": "method", "name": "brotliDecompress", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.brotliDecompressSync(buffer[, options])`", "type": "method", "name": "brotliDecompressSync", "meta": { "added": [ "v11.7.0", "v10.16.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {brotli options}", "name": "options", "type": "brotli options" } ] } ], "desc": "

Decompress a chunk of data with BrotliDecompress.

" }, { "textRaw": "`zlib.deflate(buffer[, options], callback)`", "type": "method", "name": "deflate", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.deflateSync(buffer[, options])`", "type": "method", "name": "deflateSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with Deflate.

" }, { "textRaw": "`zlib.deflateRaw(buffer[, options], callback)`", "type": "method", "name": "deflateRaw", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.deflateRawSync(buffer[, options])`", "type": "method", "name": "deflateRawSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with DeflateRaw.

" }, { "textRaw": "`zlib.gunzip(buffer[, options], callback)`", "type": "method", "name": "gunzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.gunzipSync(buffer[, options])`", "type": "method", "name": "gunzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Gunzip.

" }, { "textRaw": "`zlib.gzip(buffer[, options], callback)`", "type": "method", "name": "gzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.gzipSync(buffer[, options])`", "type": "method", "name": "gzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Compress a chunk of data with Gzip.

" }, { "textRaw": "`zlib.inflate(buffer[, options], callback)`", "type": "method", "name": "inflate", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.inflateSync(buffer[, options])`", "type": "method", "name": "inflateSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Inflate.

" }, { "textRaw": "`zlib.inflateRaw(buffer[, options], callback)`", "type": "method", "name": "inflateRaw", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.inflateRawSync(buffer[, options])`", "type": "method", "name": "inflateRawSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with InflateRaw.

" }, { "textRaw": "`zlib.unzip(buffer[, options], callback)`", "type": "method", "name": "unzip", "meta": { "added": [ "v0.6.0" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ] }, { "textRaw": "`zlib.unzipSync(buffer[, options])`", "type": "method", "name": "unzipSync", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v9.4.0", "pr-url": "https://github.com/nodejs/node/pull/16042", "description": "The `buffer` parameter can be an `ArrayBuffer`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `buffer` parameter can be any `TypedArray` or `DataView`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12001", "description": "The `buffer` parameter can be an `Uint8Array` now." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}", "name": "buffer", "type": "Buffer|TypedArray|DataView|ArrayBuffer|string" }, { "textRaw": "`options` {zlib options}", "name": "options", "type": "zlib options" } ] } ], "desc": "

Decompress a chunk of data with Unzip.

" } ], "type": "module", "displayName": "Zlib", "source": "doc/api/zlib.md" } ], "classes": [ { "textRaw": "Class: `Error`", "type": "class", "name": "Error", "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.

\n

All errors generated by Node.js, including all system and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

", "methods": [ { "textRaw": "`Error.captureStackTrace(targetObject[, constructorOpt])`", "type": "method", "name": "captureStackTrace", "signatures": [ { "params": [ { "textRaw": "`targetObject` {Object}", "name": "targetObject", "type": "Object" }, { "textRaw": "`constructorOpt` {Function}", "name": "constructorOpt", "type": "Function" } ] } ], "desc": "

Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack;  // Similar to `new Error().stack`\n
\n

The first line of the trace will be prefixed with\n${myObject.name}: ${myObject.message}.

\n

The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from the user. For instance:

\n
function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
" } ], "properties": [ { "textRaw": "`stackTraceLimit` {number}", "type": "number", "name": "stackTraceLimit", "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)).

\n

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.

\n

If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.

" }, { "textRaw": "`code` {string}", "type": "string", "name": "code", "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.

" }, { "textRaw": "`message` {string}", "type": "string", "name": "message", "desc": "

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).

\n
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
" }, { "textRaw": "`stack` {string}", "type": "string", "name": "stack", "desc": "

The error.stack property is a string describing the point in the code at which\nthe Error was instantiated.

\n
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
\n

The 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.

\n

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:

\n
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
\n

The location information will be one of:

\n
    \n
  • native, if the frame represents a call internal to V8 (as in [].forEach).
  • \n
  • plain-filename.js:line:column, if the frame represents a call internal\nto Node.js.
  • \n
  • /absolute/path/to/file.js:line:column, if the frame represents a call in\na user program, or its dependencies.
  • \n
\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

\n

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.

" } ], "signatures": [ { "params": [ { "textRaw": "`message` {string}", "name": "message", "type": "string" } ], "desc": "

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 message.toString(). 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.

" } ], "source": "doc/api/errors.md" }, { "textRaw": "Class: `AssertionError`", "type": "class", "name": "AssertionError", "desc": "\n

Indicates the failure of an assertion. For details, see\nClass: assert.AssertionError.

", "source": "doc/api/errors.md" }, { "textRaw": "Class: `RangeError`", "type": "class", "name": "RangeError", "desc": "\n

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.

\n
require('net').connect(-1);\n// Throws \"RangeError: \"port\" option should be >= 0 and < 65536: -1\"\n
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

", "source": "doc/api/errors.md" }, { "textRaw": "Class: `ReferenceError`", "type": "class", "name": "ReferenceError", "desc": "\n

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.

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.

\n
doesNotExist;\n// Throws ReferenceError, doesNotExist is not a variable in this program.\n
\n

Unless an application is dynamically generating and running code,\nReferenceError instances indicate a bug in the code or its dependencies.

", "source": "doc/api/errors.md" }, { "textRaw": "Class: `SyntaxError`", "type": "class", "name": "SyntaxError", "desc": "\n

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.

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n  // 'err' will be a SyntaxError.\n}\n
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

", "source": "doc/api/errors.md" }, { "textRaw": "Class: `SystemError`", "type": "class", "name": "SystemError", "desc": "\n

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.

\n
    \n
  • address <string> If present, the address to which a network connection\nfailed
  • \n
  • code <string> The string error code
  • \n
  • dest <string> If present, the file path destination when reporting a file\nsystem error
  • \n
  • errno <number> The system-provided error number
  • \n
  • info <Object> If present, extra details about the error condition
  • \n
  • message <string> A system-provided human-readable description of the error
  • \n
  • path <string> If present, the file path when reporting a file system error
  • \n
  • port <number> If present, the network connection port that is not available
  • \n
  • syscall <string> The name of the system call that triggered the error
  • \n
", "properties": [ { "textRaw": "`address` {string}", "type": "string", "name": "address", "desc": "

If present, error.address is a string describing the address to which a\nnetwork connection failed.

" }, { "textRaw": "`code` {string}", "type": "string", "name": "code", "desc": "

The error.code property is a string representing the error code.

" }, { "textRaw": "`dest` {string}", "type": "string", "name": "dest", "desc": "

If present, error.dest is the file path destination when reporting a file\nsystem error.

" }, { "textRaw": "`errno` {number}", "type": "number", "name": "errno", "desc": "

The error.errno property is a negative number which corresponds\nto the error code defined in libuv Error handling.

\n

On Windows the error number provided by the system will be normalized by libuv.

\n

To get the string representation of the error code, use\nutil.getSystemErrorName(error.errno).

" }, { "textRaw": "`info` {Object}", "type": "Object", "name": "info", "desc": "

If present, error.info is an object with details about the error condition.

" }, { "textRaw": "`message` {string}", "type": "string", "name": "message", "desc": "

error.message is a system-provided human-readable description of the error.

" }, { "textRaw": "`path` {string}", "type": "string", "name": "path", "desc": "

If present, error.path is a string containing a relevant invalid pathname.

" }, { "textRaw": "`port` {number}", "type": "number", "name": "port", "desc": "

If present, error.port is the network connection port that is not available.

" }, { "textRaw": "`syscall` {string}", "type": "string", "name": "syscall", "desc": "

The error.syscall property is a string describing the syscall that failed.

" } ], "modules": [ { "textRaw": "Common system errors", "name": "common_system_errors", "desc": "

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.

\n
    \n
  • \n

    EACCES (Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    EEXIST (File exists): An existing file was the target of an operation that\nrequired that the target not exist.

    \n
  • \n
  • \n

    EISDIR (Is a directory): An operation expected a file, but the given\npathname was a directory.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    ENOTDIR (Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir.

    \n
  • \n
  • \n

    ENOTEMPTY (Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory, usually fs.unlink.

    \n
  • \n
  • \n

    ENOTFOUND (DNS lookup failed): Indicates a DNS failure of either\nEAI_NODATA or EAI_NONAME. This is not a standard POSIX error.

    \n
  • \n
  • \n

    EPERM (Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.

    \n
  • \n
  • \n

    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.

    \n
  • \n
  • \n

    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.

    \n
  • \n
", "type": "module", "displayName": "Common system errors" } ], "source": "doc/api/errors.md" }, { "textRaw": "Class: `TypeError`", "type": "class", "name": "TypeError", "desc": "\n

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.

\n
require('url').parse(() => { });\n// Throws TypeError, since it expected a string.\n
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

", "source": "doc/api/errors.md" } ], "globals": [ { "textRaw": "Class: `AbortController`", "type": "global", "name": "AbortController", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "desc": "

A utility class used to signal cancelation in selected Promise-based APIs.\nThe API is based on the Web API AbortController.

\n
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()`", "type": "method", "name": "abort", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Triggers the abort signal, causing the abortController.signal to emit\nthe 'abort' event.

" } ], "properties": [ { "textRaw": "`signal` Type: {AbortSignal}", "type": "AbortSignal", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] } } ], "classes": [ { "textRaw": "Class: `AbortSignal`", "type": "class", "name": "AbortSignal", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "\n

The AbortSignal is used to notify observers when the\nabortController.abort() method is called.

", "classMethods": [ { "textRaw": "Static method: `AbortSignal.abort()`", "type": "classMethod", "name": "abort", "meta": { "added": [ "v15.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {AbortSignal}", "name": "return", "type": "AbortSignal" }, "params": [] } ], "desc": "

Returns a new already aborted AbortSignal.

" } ], "events": [ { "textRaw": "Event: `'abort'`", "type": "event", "name": "abort", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "params": [], "desc": "

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':

\n
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
\n

The 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.

\n

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.

" } ], "properties": [ { "textRaw": "`aborted` Type: {boolean} True after the `AbortController` has been aborted.", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "True after the `AbortController` has been aborted." }, { "textRaw": "`onabort` Type: {Function}", "type": "Function", "name": "Type", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

An optional callback function that may be set by user code to be notified\nwhen the abortController.abort() function has been called.

" } ] } ], "source": "doc/api/globals.md" }, { "textRaw": "Class: `Buffer`", "type": "global", "name": "Buffer", "meta": { "added": [ "v0.1.103" ], "changes": [] }, "desc": "\n

Used to handle binary data. See the buffer section.

", "source": "doc/api/globals.md" }, { "textRaw": "`clearImmediate(immediateObject)`", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "desc": "

clearImmediate is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`clearInterval(intervalObject)`", "type": "global", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

clearInterval is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`clearTimeout(timeoutObject)`", "type": "global", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

clearTimeout is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`console`", "name": "`console`", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "type": "global", "desc": "\n

Used to print to stdout and stderr. See the console section.

", "source": "doc/api/globals.md" }, { "textRaw": "`Event`", "name": "`Event`", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "type": "global", "desc": "

A browser-compatible implementation of the Event class. See\nEventTarget and Event API for more details.

", "source": "doc/api/globals.md" }, { "textRaw": "`EventTarget`", "name": "`EventTarget`", "meta": { "added": [ "v15.0.0" ], "changes": [ { "version": "v15.4.0", "pr-url": "https://github.com/nodejs/node/pull/35949", "description": "No longer experimental." } ] }, "type": "global", "desc": "

A browser-compatible implementation of the EventTarget class. See\nEventTarget and Event API for more details.

", "source": "doc/api/globals.md" }, { "textRaw": "`global`", "name": "`global`", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "type": "global", "desc": "
    \n
  • <Object> The global namespace object.
  • \n
\n

In browsers, the top-level scope is the global scope. This means that\nwithin the browser var something will define a new global variable. In\nNode.js this is different. The top-level scope is not the global scope;\nvar something inside a Node.js module will be local to that module.

", "source": "doc/api/globals.md" }, { "textRaw": "`MessageChannel`", "name": "`MessageChannel`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessageChannel class. See MessageChannel for more details.

", "source": "doc/api/globals.md" }, { "textRaw": "`MessageEvent`", "name": "`MessageEvent`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessageEvent class. See MessageEvent for more details.

", "source": "doc/api/globals.md" }, { "textRaw": "`MessagePort`", "name": "`MessagePort`", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "type": "global", "desc": "

The MessagePort class. See MessagePort for more details.

", "source": "doc/api/globals.md" }, { "textRaw": "`process`", "name": "`process`", "meta": { "added": [ "v0.1.7" ], "changes": [] }, "type": "global", "desc": "\n

The process object. See the process object section.

", "source": "doc/api/globals.md" }, { "textRaw": "`queueMicrotask(callback)`", "type": "global", "name": "queueMicrotask", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "desc": "\n

The queueMicrotask() method queues a microtask to invoke callback. If\ncallback throws an exception, the process object 'uncaughtException'\nevent will be emitted.

\n

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.

\n
// 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
", "source": "doc/api/globals.md" }, { "textRaw": "`setImmediate(callback[, ...args])`", "type": "global", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ], "changes": [] }, "desc": "

setImmediate is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`setInterval(callback, delay[, ...args])`", "type": "global", "name": "setInterval", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

setInterval is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`setTimeout(callback, delay[, ...args])`", "type": "global", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ], "changes": [] }, "desc": "

setTimeout is described in the timers section.

", "source": "doc/api/globals.md" }, { "textRaw": "`TextDecoder`", "name": "`TextDecoder`", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG TextDecoder class. See the TextDecoder section.

", "source": "doc/api/globals.md" }, { "textRaw": "`TextEncoder`", "name": "`TextEncoder`", "meta": { "added": [ "v11.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG TextEncoder class. See the TextEncoder section.

", "source": "doc/api/globals.md" }, { "textRaw": "`URL`", "name": "`URL`", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG URL class. See the URL section.

", "source": "doc/api/globals.md" }, { "textRaw": "`URLSearchParams`", "name": "`URLSearchParams`", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "type": "global", "desc": "

The WHATWG URLSearchParams class. See the URLSearchParams section.

", "source": "doc/api/globals.md" }, { "textRaw": "`WebAssembly`", "name": "`WebAssembly`", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "type": "global", "desc": "\n

The object that acts as the namespace for all W3C\nWebAssembly related functionality. See the\nMozilla Developer Network for usage and compatibility.

", "source": "doc/api/globals.md" }, { "textRaw": "Process", "name": "Process", "introduced_in": "v0.10.0", "type": "global", "desc": "

Source Code: lib/process.js

\n

The process object provides information about, and control over, the current\nNode.js process. While it is available as a global, it is recommended to\nexplicitly access it via require or import:

\n
import process from 'process';\n
\n
const process = require('process');\n
", "modules": [ { "textRaw": "Process events", "name": "process_events", "desc": "

The process object is an instance of EventEmitter.

", "events": [ { "textRaw": "Event: `'beforeExit'`", "type": "event", "name": "beforeExit", "meta": { "added": [ "v0.11.12" ], "changes": [] }, "params": [], "desc": "

The 'beforeExit' event is emitted when Node.js empties its event loop and has\nno additional work to schedule. Normally, the Node.js process will exit when\nthere is no work scheduled, but a listener registered on the 'beforeExit'\nevent can make asynchronous calls, and thereby cause the Node.js process to\ncontinue.

\n

The listener callback function is invoked with the value of\nprocess.exitCode passed as the only argument.

\n

The 'beforeExit' event is not emitted for conditions causing explicit\ntermination, such as calling process.exit() or uncaught exceptions.

\n

The 'beforeExit' should not be used as an alternative to the 'exit' event\nunless the intention is to schedule additional work.

\n
import process from 'process';\n\nprocess.on('beforeExit', (code) => {\n  console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n  console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
\n
const process = require('process');\n\nprocess.on('beforeExit', (code) => {\n  console.log('Process beforeExit event with code: ', code);\n});\n\nprocess.on('exit', (code) => {\n  console.log('Process exit event with code: ', code);\n});\n\nconsole.log('This message is displayed first.');\n\n// Prints:\n// This message is displayed first.\n// Process beforeExit event with code: 0\n// Process exit event with code: 0\n
" }, { "textRaw": "Event: `'disconnect'`", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "params": [], "desc": "

If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'disconnect' event will be emitted when\nthe IPC channel is closed.

" }, { "textRaw": "Event: `'exit'`", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.7" ], "changes": [] }, "params": [ { "textRaw": "`code` {integer}", "name": "code", "type": "integer" } ], "desc": "

The 'exit' event is emitted when the Node.js process is about to exit as a\nresult of either:

\n
    \n
  • The process.exit() method being called explicitly;
  • \n
  • The Node.js event loop no longer having any additional work to perform.
  • \n
\n

There is no way to prevent the exiting of the event loop at this point, and once\nall 'exit' listeners have finished running the Node.js process will terminate.

\n

The listener callback function is invoked with the exit code specified either\nby the process.exitCode property, or the exitCode argument passed to the\nprocess.exit() method.

\n
import process from 'process';\n\nprocess.on('exit', (code) => {\n  console.log(`About to exit with code: ${code}`);\n});\n
\n
const process = require('process');\n\nprocess.on('exit', (code) => {\n  console.log(`About to exit with code: ${code}`);\n});\n
\n

Listener functions must only perform synchronous operations. The Node.js\nprocess will exit immediately after calling the 'exit' event listeners\ncausing any additional work still queued in the event loop to be abandoned.\nIn the following example, for instance, the timeout will never occur:

\n
import process from 'process';\n\nprocess.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
\n
const process = require('process');\n\nprocess.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
" }, { "textRaw": "Event: `'message'`", "type": "event", "name": "message", "meta": { "added": [ "v0.5.10" ], "changes": [] }, "params": [ { "textRaw": "`message` { Object | boolean | number | string | null } a parsed JSON object or a serializable primitive value.", "name": "message", "type": " Object | boolean | number | string | null ", "desc": "a parsed JSON object or a serializable primitive value." }, { "textRaw": "`sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] object, or undefined.", "name": "sendHandle", "type": "net.Server|net.Socket", "desc": "a [`net.Server`][] or [`net.Socket`][] object, or undefined." } ], "desc": "

If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'message' event is emitted whenever a\nmessage sent by a parent process using childprocess.send() is received by\nthe child process.

\n

The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

\n

If the serialization option was set to advanced used when spawning the\nprocess, the message argument can contain data that JSON is not able\nto represent.\nSee Advanced serialization for child_process for more details.

" }, { "textRaw": "Event: `'multipleResolves'`", "type": "event", "name": "multipleResolves", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {string} The resolution type. One of `'resolve'` or `'reject'`.", "name": "type", "type": "string", "desc": "The resolution type. One of `'resolve'` or `'reject'`." }, { "textRaw": "`promise` {Promise} The promise that resolved or rejected more than once.", "name": "promise", "type": "Promise", "desc": "The promise that resolved or rejected more than once." }, { "textRaw": "`value` {any} The value with which the promise was either resolved or rejected after the original resolve.", "name": "value", "type": "any", "desc": "The value with which the promise was either resolved or rejected after the original resolve." } ], "desc": "

The 'multipleResolves' event is emitted whenever a Promise has been either:

\n
    \n
  • Resolved more than once.
  • \n
  • Rejected more than once.
  • \n
  • Rejected after resolve.
  • \n
  • Resolved after reject.
  • \n
\n

This is useful for tracking potential errors in an application while using the\nPromise constructor, as multiple resolutions are silently swallowed. However,\nthe occurrence of this event does not necessarily indicate an error. For\nexample, Promise.race() can trigger a 'multipleResolves' event.

\n
import process from 'process';\n\nprocess.on('multipleResolves', (type, promise, reason) => {\n  console.error(type, promise, reason);\n  setImmediate(() => process.exit(1));\n});\n\nasync function main() {\n  try {\n    return await new Promise((resolve, reject) => {\n      resolve('First call');\n      resolve('Swallowed resolve');\n      reject(new Error('Swallowed reject'));\n    });\n  } catch {\n    throw new Error('Failed');\n  }\n}\n\nmain().then(console.log);\n// resolve: Promise { 'First call' } 'Swallowed resolve'\n// reject: Promise { 'First call' } Error: Swallowed reject\n//     at Promise (*)\n//     at new Promise (<anonymous>)\n//     at main (*)\n// First call\n
\n
const process = require('process');\n\nprocess.on('multipleResolves', (type, promise, reason) => {\n  console.error(type, promise, reason);\n  setImmediate(() => process.exit(1));\n});\n\nasync function main() {\n  try {\n    return await new Promise((resolve, reject) => {\n      resolve('First call');\n      resolve('Swallowed resolve');\n      reject(new Error('Swallowed reject'));\n    });\n  } catch {\n    throw new Error('Failed');\n  }\n}\n\nmain().then(console.log);\n// resolve: Promise { 'First call' } 'Swallowed resolve'\n// reject: Promise { 'First call' } Error: Swallowed reject\n//     at Promise (*)\n//     at new Promise (<anonymous>)\n//     at main (*)\n// First call\n
" }, { "textRaw": "Event: `'rejectionHandled'`", "type": "event", "name": "rejectionHandled", "meta": { "added": [ "v1.4.1" ], "changes": [] }, "params": [ { "textRaw": "`promise` {Promise} The late handled promise.", "name": "promise", "type": "Promise", "desc": "The late handled promise." } ], "desc": "

The 'rejectionHandled' event is emitted whenever a Promise has been rejected\nand an error handler was attached to it (using promise.catch(), for\nexample) later than one turn of the Node.js event loop.

\n

The Promise object would have previously been emitted in an\n'unhandledRejection' event, but during the course of processing gained a\nrejection handler.

\n

There is no notion of a top level for a Promise chain at which rejections can\nalways be handled. Being inherently asynchronous in nature, a Promise\nrejection can be handled at a future point in time, possibly much later than\nthe event loop turn it takes for the 'unhandledRejection' event to be emitted.

\n

Another way of stating this is that, unlike in synchronous code where there is\nan ever-growing list of unhandled exceptions, with Promises there can be a\ngrowing-and-shrinking list of unhandled rejections.

\n

In synchronous code, the 'uncaughtException' event is emitted when the list of\nunhandled exceptions grows.

\n

In asynchronous code, the 'unhandledRejection' event is emitted when the list\nof unhandled rejections grows, and the 'rejectionHandled' event is emitted\nwhen the list of unhandled rejections shrinks.

\n
import process from 'process';\n\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n  unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n  unhandledRejections.delete(promise);\n});\n
\n
const process = require('process');\n\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, promise) => {\n  unhandledRejections.set(promise, reason);\n});\nprocess.on('rejectionHandled', (promise) => {\n  unhandledRejections.delete(promise);\n});\n
\n

In this example, the unhandledRejections Map will grow and shrink over time,\nreflecting rejections that start unhandled and then become handled. It is\npossible to record such errors in an error log, either periodically (which is\nlikely best for long-running application) or upon process exit (which is likely\nmost convenient for scripts).

" }, { "textRaw": "Event: `'uncaughtException'`", "type": "event", "name": "uncaughtException", "meta": { "added": [ "v0.1.18" ], "changes": [ { "version": [ "v12.0.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/26599", "description": "Added the `origin` argument." } ] }, "params": [ { "textRaw": "`err` {Error} The uncaught exception.", "name": "err", "type": "Error", "desc": "The uncaught exception." }, { "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` or `throw` and an unhandled rejection.", "name": "origin", "type": "string", "desc": "Indicates if the exception originates from an unhandled rejection or from an synchronous error. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` or `throw` and an unhandled rejection." } ], "desc": "

The 'uncaughtException' event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr and exiting\nwith code 1, overriding any previously set process.exitCode.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior. Alternatively, change the process.exitCode in the\n'uncaughtException' handler which will result in the process exiting with the\nprovided exit code. Otherwise, in the presence of such handler the process will\nexit with 0.

\n
import process from 'process';\n\nprocess.on('uncaughtException', (err, origin) => {\n  fs.writeSync(\n    process.stderr.fd,\n    `Caught exception: ${err}\\n` +\n    `Exception origin: ${origin}`\n  );\n});\n\nsetTimeout(() => {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
\n
const process = require('process');\n\nprocess.on('uncaughtException', (err, origin) => {\n  fs.writeSync(\n    process.stderr.fd,\n    `Caught exception: ${err}\\n` +\n    `Exception origin: ${origin}`\n  );\n});\n\nsetTimeout(() => {\n  console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
\n

It is possible to monitor 'uncaughtException' events without overriding the\ndefault behavior to exit the process by installing a\n'uncaughtExceptionMonitor' listener.

", "modules": [ { "textRaw": "Warning: Using `'uncaughtException'` correctly", "name": "warning:_using_`'uncaughtexception'`_correctly", "desc": "

'uncaughtException' is a crude mechanism for exception handling\nintended to be used only as a last resort. The event should not be used as\nan equivalent to On Error Resume Next. Unhandled exceptions inherently mean\nthat an application is in an undefined state. Attempting to resume application\ncode without properly recovering from the exception can cause additional\nunforeseen and unpredictable issues.

\n

Exceptions thrown from within the event handler will not be caught. Instead the\nprocess will exit with a non-zero exit code and the stack trace will be printed.\nThis is to avoid infinite recursion.

\n

Attempting to resume normally after an uncaught exception can be similar to\npulling out the power cord when upgrading a computer. Nine out of ten\ntimes, nothing happens. But the tenth time, the system becomes corrupted.

\n

The correct use of 'uncaughtException' is to perform synchronous cleanup\nof allocated resources (e.g. file descriptors, handles, etc) before shutting\ndown the process. It is not safe to resume normal operation after\n'uncaughtException'.

\n

To restart a crashed application in a more reliable way, whether\n'uncaughtException' is emitted or not, an external monitor should be employed\nin a separate process to detect application failures and recover or restart as\nneeded.

", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ] }, { "textRaw": "Event: `'uncaughtExceptionMonitor'`", "type": "event", "name": "uncaughtExceptionMonitor", "meta": { "added": [ "v13.7.0", "v12.17.0" ], "changes": [] }, "params": [ { "textRaw": "`err` {Error} The uncaught exception.", "name": "err", "type": "Error", "desc": "The uncaught exception." }, { "textRaw": "`origin` {string} Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` or `throw` and an unhandled rejection.", "name": "origin", "type": "string", "desc": "Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be `'uncaughtException'` or `'unhandledRejection'`. The latter is only used in conjunction with the [`--unhandled-rejections`][] flag set to `strict` or `throw` and an unhandled rejection." } ], "desc": "

The 'uncaughtExceptionMonitor' event is emitted before an\n'uncaughtException' event is emitted or a hook installed via\nprocess.setUncaughtExceptionCaptureCallback() is called.

\n

Installing an 'uncaughtExceptionMonitor' listener does not change the behavior\nonce an 'uncaughtException' event is emitted. The process will\nstill crash if no 'uncaughtException' listener is installed.

\n
import process from 'process';\n\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n  MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
\n
const process = require('process');\n\nprocess.on('uncaughtExceptionMonitor', (err, origin) => {\n  MyMonitoringTool.logSync(err, origin);\n});\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\n// Still crashes Node.js\n
" }, { "textRaw": "Event: `'unhandledRejection'`", "type": "event", "name": "unhandledRejection", "meta": { "added": [ "v1.4.1" ], "changes": [ { "version": "v7.0.0", "pr-url": "https://github.com/nodejs/node/pull/8217", "description": "Not handling `Promise` rejections is deprecated." }, { "version": "v6.6.0", "pr-url": "https://github.com/nodejs/node/pull/8223", "description": "Unhandled `Promise` rejections will now emit a process warning." } ] }, "params": [ { "textRaw": "`reason` {Error|any} The object with which the promise was rejected (typically an [`Error`][] object).", "name": "reason", "type": "Error|any", "desc": "The object with which the promise was rejected (typically an [`Error`][] object)." }, { "textRaw": "`promise` {Promise} The rejected promise.", "name": "promise", "type": "Promise", "desc": "The rejected promise." } ], "desc": "

The 'unhandledRejection' event is emitted whenever a Promise is rejected and\nno error handler is attached to the promise within a turn of the event loop.\nWhen programming with Promises, exceptions are encapsulated as \"rejected\npromises\". Rejections can be caught and handled using promise.catch() and\nare propagated through a Promise chain. The 'unhandledRejection' event is\nuseful for detecting and keeping track of promises that were rejected whose\nrejections have not yet been handled.

\n
import process from 'process';\n\nprocess.on('unhandledRejection', (reason, promise) => {\n  console.log('Unhandled Rejection at:', promise, 'reason:', reason);\n  // Application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)\n}); // No `.catch()` or `.then()`\n
\n
const process = require('process');\n\nprocess.on('unhandledRejection', (reason, promise) => {\n  console.log('Unhandled Rejection at:', promise, 'reason:', reason);\n  // Application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)\n}); // No `.catch()` or `.then()`\n
\n

The following will also trigger the 'unhandledRejection' event to be\nemitted:

\n
import process from 'process';\n\nfunction SomeResource() {\n  // Initially set the loaded status to a rejected promise\n  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));\n}\n\nconst resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
\n
const process = require('process');\n\nfunction SomeResource() {\n  // Initially set the loaded status to a rejected promise\n  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));\n}\n\nconst resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn\n
\n

In this example case, it is possible to track the rejection as a developer error\nas would typically be the case for other 'unhandledRejection' events. To\naddress such failures, a non-operational\n.catch(() => { }) handler may be attached to\nresource.loaded, which would prevent the 'unhandledRejection' event from\nbeing emitted.

" }, { "textRaw": "Event: `'warning'`", "type": "event", "name": "warning", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "params": [ { "textRaw": "`warning` {Error} Key properties of the warning are:", "name": "warning", "type": "Error", "desc": "Key properties of the warning are:", "options": [ { "textRaw": "`name` {string} The name of the warning. **Default:** `'Warning'`.", "name": "name", "type": "string", "default": "`'Warning'`", "desc": "The name of the warning." }, { "textRaw": "`message` {string} A system-provided description of the warning.", "name": "message", "type": "string", "desc": "A system-provided description of the warning." }, { "textRaw": "`stack` {string} A stack trace to the location in the code where the warning was issued.", "name": "stack", "type": "string", "desc": "A stack trace to the location in the code where the warning was issued." } ] } ], "desc": "

The 'warning' event is emitted whenever Node.js emits a process warning.

\n

A process warning is similar to an error in that it describes exceptional\nconditions that are being brought to the user's attention. However, warnings\nare not part of the normal Node.js and JavaScript error handling flow.\nNode.js can emit warnings whenever it detects bad coding practices that could\nlead to sub-optimal application performance, bugs, or security vulnerabilities.

\n
import process from 'process';\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);    // Print the warning name\n  console.warn(warning.message); // Print the warning message\n  console.warn(warning.stack);   // Print the stack trace\n});\n
\n
const process = require('process');\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);    // Print the warning name\n  console.warn(warning.message); // Print the warning message\n  console.warn(warning.stack);   // Print the stack trace\n});\n
\n

By default, Node.js will print process warnings to stderr. The --no-warnings\ncommand-line option can be used to suppress the default console output but the\n'warning' event will still be emitted by the process object.

\n

The following example illustrates the warning that is printed to stderr when\ntoo many listeners have been added to an event:

\n
$ node\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak\ndetected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit\n
\n

In contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning' event:

\n
$ node --no-warnings\n> const p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> events.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\n
\n

The --trace-warnings command-line option can be used to have the default\nconsole output for warnings include the full stack trace of the warning.

\n

Launching Node.js using the --throw-deprecation command-line flag will\ncause custom deprecation warnings to be thrown as exceptions.

\n

Using the --trace-deprecation command-line flag will cause the custom\ndeprecation to be printed to stderr along with the stack trace.

\n

Using the --no-deprecation command-line flag will suppress all reporting\nof the custom deprecation.

\n

The *-deprecation command-line flags only affect warnings that use the name\n'DeprecationWarning'.

" }, { "textRaw": "Event: `'worker'`", "type": "event", "name": "worker", "meta": { "added": [ "v16.2.0" ], "changes": [] }, "params": [ { "textRaw": "`worker` {Worker} The {Worker} that was created.", "name": "worker", "type": "Worker", "desc": "The {Worker} that was created." } ], "desc": "

The 'worker' event is emitted after a new <Worker> thread has been created.

", "modules": [ { "textRaw": "Emitting custom warnings", "name": "emitting_custom_warnings", "desc": "

See the process.emitWarning() method for issuing\ncustom or application-specific warnings.

", "type": "module", "displayName": "Emitting custom warnings" }, { "textRaw": "Node.js warning names", "name": "node.js_warning_names", "desc": "

There are no strict guidelines for warning types (as identified by the name\nproperty) emitted by Node.js. New types of warnings can be added at any time.\nA few of the warning types that are most common include:

\n
    \n
  • 'DeprecationWarning' - Indicates use of a deprecated Node.js API or feature.\nSuch warnings must include a 'code' property identifying the\ndeprecation code.
  • \n
  • 'ExperimentalWarning' - Indicates use of an experimental Node.js API or\nfeature. Such features must be used with caution as they may change at any\ntime and are not subject to the same strict semantic-versioning and long-term\nsupport policies as supported features.
  • \n
  • 'MaxListenersExceededWarning' - Indicates that too many listeners for a\ngiven event have been registered on either an EventEmitter or EventTarget.\nThis is often an indication of a memory leak.
  • \n
  • 'TimeoutOverflowWarning' - Indicates that a numeric value that cannot fit\nwithin a 32-bit signed integer has been provided to either the setTimeout()\nor setInterval() functions.
  • \n
  • 'UnsupportedWarning' - Indicates use of an unsupported option or feature\nthat will be ignored rather than treated as an error. One example is use of\nthe HTTP response status message when using the HTTP/2 compatibility API.
  • \n
", "type": "module", "displayName": "Node.js warning names" } ] }, { "textRaw": "Signal events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "params": [], "desc": "

Signal events will be emitted when the Node.js process receives a signal. Please\nrefer to signal(7) for a listing of standard POSIX signal names such as\n'SIGINT', 'SIGHUP', etc.

\n

Signals are not available on Worker threads.

\n

The signal handler will receive the signal's name ('SIGINT',\n'SIGTERM', etc.) as the first argument.

\n

The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).

\n
import process from 'process';\n\n// Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Received SIGINT. Press Control-D to exit.');\n});\n\n// Using a single function to handle multiple signals\nfunction handle(signal) {\n  console.log(`Received ${signal}`);\n}\n\nprocess.on('SIGINT', handle);\nprocess.on('SIGTERM', handle);\n
\n
const process = require('process');\n\n// Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Received SIGINT. Press Control-D to exit.');\n});\n\n// Using a single function to handle multiple signals\nfunction handle(signal) {\n  console.log(`Received ${signal}`);\n}\n\nprocess.on('SIGINT', handle);\nprocess.on('SIGTERM', handle);\n
\n
    \n
  • 'SIGUSR1' is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so might interfere with the debugger.
  • \n
  • 'SIGTERM' and 'SIGINT' have default handlers on non-Windows platforms that\nreset the terminal mode before exiting with code 128 + signal number. If one\nof these signals has a listener installed, its default behavior will be\nremoved (Node.js will no longer exit).
  • \n
  • 'SIGPIPE' is ignored by default. It can have a listener installed.
  • \n
  • 'SIGHUP' is generated on Windows when the console window is closed, and on\nother platforms under various similar conditions. See signal(7). It can have a\nlistener installed, however Node.js will be unconditionally terminated by\nWindows about 10 seconds later. On non-Windows platforms, the default\nbehavior of SIGHUP is to terminate Node.js, but once a listener has been\ninstalled its default behavior will be removed.
  • \n
  • 'SIGTERM' is not supported on Windows, it can be listened on.
  • \n
  • 'SIGINT' from the terminal is supported on all platforms, and can usually be\ngenerated with Ctrl+C (though this may be configurable).\nIt is not generated when terminal raw mode is enabled and\nCtrl+C is used.
  • \n
  • 'SIGBREAK' is delivered on Windows when Ctrl+Break is\npressed. On non-Windows platforms, it can be listened on, but there is no way\nto send or generate it.
  • \n
  • 'SIGWINCH' is delivered when the console has been resized. On Windows, this\nwill only happen on write to the console when the cursor is being moved, or\nwhen a readable tty is used in raw mode.
  • \n
  • 'SIGKILL' cannot have a listener installed, it will unconditionally\nterminate Node.js on all platforms.
  • \n
  • 'SIGSTOP' cannot have a listener installed.
  • \n
  • 'SIGBUS', 'SIGFPE', 'SIGSEGV' and 'SIGILL', when not raised\nartificially using kill(2), inherently leave the process in a state from\nwhich it is not safe to call JS listeners. Doing so might cause the process\nto stop responding.
  • \n
  • 0 can be sent to test for the existence of a process, it has no effect if\nthe process exists, but will throw an error if the process does not exist.
  • \n
\n

Windows does not support signals so has no equivalent to termination by signal,\nbut Node.js offers some emulation with process.kill(), and\nsubprocess.kill():

\n
    \n
  • Sending SIGINT, SIGTERM, and SIGKILL will cause the unconditional\ntermination of the target process, and afterwards, subprocess will report that\nthe process was terminated by signal.
  • \n
  • Sending signal 0 can be used as a platform independent way to test for the\nexistence of a process.
  • \n
" } ], "type": "module", "displayName": "Process events" }, { "textRaw": "Exit codes", "name": "exit_codes", "desc": "

Node.js will normally exit with a 0 status code when no more async\noperations are pending. The following status codes are used in other\ncases:

\n
    \n
  • 1 Uncaught Fatal Exception: There was an uncaught exception,\nand it was not handled by a domain or an 'uncaughtException' event\nhandler.
  • \n
  • 2: Unused (reserved by Bash for builtin misuse)
  • \n
  • 3 Internal JavaScript Parse Error: The JavaScript source code\ninternal in the Node.js bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node.js itself.
  • \n
  • 4 Internal JavaScript Evaluation Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node.js itself.
  • \n
  • 5 Fatal Error: There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL ERROR.
  • \n
  • 6 Non-function Internal Exception Handler: There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.
  • \n
  • 7 Internal Exception Handler Run-Time Failure: There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if an 'uncaughtException' or\ndomain.on('error') handler throws an error.
  • \n
  • 8: Unused. In previous versions of Node.js, exit code 8 sometimes\nindicated an uncaught exception.
  • \n
  • 9 Invalid Argument: Either an unknown option was specified,\nor an option requiring a value was provided without a value.
  • \n
  • 10 Internal JavaScript Run-Time Failure: The JavaScript\nsource code internal in the Node.js bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node.js itself.
  • \n
  • 12 Invalid Debug Argument: The --inspect and/or --inspect-brk\noptions were set, but the port number chosen was invalid or unavailable.
  • \n
  • 13 Unfinished Top-Level Await: await was used outside of a function\nin the top-level code, but the passed Promise never resolved.
  • \n
  • >128 Signal Exits: If Node.js receives a fatal signal such as\nSIGKILL or SIGHUP, then its exit code will be 128 plus the\nvalue of the signal code. This is a standard POSIX practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.\nFor example, signal SIGABRT has value 6, so the expected exit\ncode will be 128 + 6, or 134.
  • \n
", "type": "module", "displayName": "Exit codes" } ], "methods": [ { "textRaw": "`process.abort()`", "type": "method", "name": "abort", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.

\n

This feature is not available in Worker threads.

" }, { "textRaw": "`process.chdir(directory)`", "type": "method", "name": "chdir", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`directory` {string}", "name": "directory", "type": "string" } ] } ], "desc": "

The process.chdir() method changes the current working directory of the\nNode.js process or throws an exception if doing so fails (for instance, if\nthe specified directory does not exist).

\n
import { chdir, cwd } from 'process';\n\nconsole.log(`Starting directory: ${cwd()}`);\ntry {\n  chdir('/tmp');\n  console.log(`New directory: ${cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
\n
const { chdir, cwd } = require('process');\n\nconsole.log(`Starting directory: ${cwd()}`);\ntry {\n  chdir('/tmp');\n  console.log(`New directory: ${cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
\n

This feature is not available in Worker threads.

" }, { "textRaw": "`process.cpuUsage([previousValue])`", "type": "method", "name": "cpuUsage", "meta": { "added": [ "v6.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`user` {integer}", "name": "user", "type": "integer" }, { "textRaw": "`system` {integer}", "name": "system", "type": "integer" } ] }, "params": [ { "textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()`", "name": "previousValue", "type": "Object", "desc": "A previous return value from calling `process.cpuUsage()`" } ] } ], "desc": "

The process.cpuUsage() method returns the user and system CPU time usage of\nthe current process, in an object with properties user and system, whose\nvalues are microsecond values (millionth of a second). These values measure time\nspent in user and system code respectively, and may end up being greater than\nactual elapsed time if multiple CPU cores are performing work for this process.

\n

The result of a previous call to process.cpuUsage() can be passed as the\nargument to the function, to get a diff reading.

\n
import { cpuUsage } from 'process';\n\nconst startUsage = cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
\n
const { cpuUsage } = require('process');\n\nconst startUsage = cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
" }, { "textRaw": "`process.cwd()`", "type": "method", "name": "cwd", "meta": { "added": [ "v0.1.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [] } ], "desc": "

The process.cwd() method returns the current working directory of the Node.js\nprocess.

\n
import { cwd } from 'process';\n\nconsole.log(`Current directory: ${cwd()}`);\n
\n
const { cwd } = require('process');\n\nconsole.log(`Current directory: ${cwd()}`);\n
" }, { "textRaw": "`process.disconnect()`", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.disconnect() method will close the\nIPC channel to the parent process, allowing the child process to exit gracefully\nonce there are no other connections keeping it alive.

\n

The effect of calling process.disconnect() is the same as calling\nChildProcess.disconnect() from the parent process.

\n

If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.

" }, { "textRaw": "`process.dlopen(module, filename[, flags])`", "type": "method", "name": "dlopen", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/12794", "description": "Added support for the `flags` argument." } ] }, "signatures": [ { "params": [ { "textRaw": "`module` {Object}", "name": "module", "type": "Object" }, { "textRaw": "`filename` {string}", "name": "filename", "type": "string" }, { "textRaw": "`flags` {os.constants.dlopen} **Default:** `os.constants.dlopen.RTLD_LAZY`", "name": "flags", "type": "os.constants.dlopen", "default": "`os.constants.dlopen.RTLD_LAZY`" } ] } ], "desc": "

The process.dlopen() method allows dynamically loading shared objects. It is\nprimarily used by require() to load C++ Addons, and should not be used\ndirectly, except in special cases. In other words, require() should be\npreferred over process.dlopen() unless there are specific reasons such as\ncustom dlopen flags or loading from ES modules.

\n

The flags argument is an integer that allows to specify dlopen\nbehavior. See the os.constants.dlopen documentation for details.

\n

An important requirement when calling process.dlopen() is that the module\ninstance must be passed. Functions exported by the C++ Addon are then\naccessible via module.exports.

\n

The example below shows how to load a C++ Addon, named local.node,\nthat exports a foo function. All the symbols are loaded before\nthe call returns, by passing the RTLD_NOW constant. In this example\nthe constant is assumed to be available.

\n
import { dlopen } from 'process';\nimport { constants } from 'os';\nimport { fileURLToPath } from 'url';\n\nconst module = { exports: {} };\ndlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),\n       constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
\n
const { dlopen } = require('process');\nconst { constants } = require('os');\nconst { join } = require('path');\n\nconst module = { exports: {} };\ndlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW);\nmodule.exports.foo();\n
" }, { "textRaw": "`process.emitWarning(warning[, options])`", "type": "method", "name": "emitWarning", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string|Error} The warning to emit.", "name": "warning", "type": "string|Error", "desc": "The warning to emit." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", "name": "type", "type": "string", "default": "`'Warning'`", "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." }, { "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", "name": "code", "type": "string", "desc": "A unique identifier for the warning instance being emitted." }, { "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", "name": "ctor", "type": "Function", "default": "`process.emitWarning`", "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." }, { "textRaw": "`detail` {string} Additional text to include with the error.", "name": "detail", "type": "string", "desc": "Additional text to include with the error." } ] } ] } ], "desc": "

The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

\n
import { emitWarning } from 'process';\n\n// Emit a warning with a code and additional detail.\nemitWarning('Something happened!', {\n  code: 'MY_WARNING',\n  detail: 'This is some additional information'\n});\n// Emits:\n// (node:56338) [MY_WARNING] Warning: Something happened!\n// This is some additional information\n
\n
const { emitWarning } = require('process');\n\n// Emit a warning with a code and additional detail.\nemitWarning('Something happened!', {\n  code: 'MY_WARNING',\n  detail: 'This is some additional information'\n});\n// Emits:\n// (node:56338) [MY_WARNING] Warning: Something happened!\n// This is some additional information\n
\n

In this example, an Error object is generated internally by\nprocess.emitWarning() and passed through to the\n'warning' handler.

\n
import process from 'process';\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);    // 'Warning'\n  console.warn(warning.message); // 'Something happened!'\n  console.warn(warning.code);    // 'MY_WARNING'\n  console.warn(warning.stack);   // Stack trace\n  console.warn(warning.detail);  // 'This is some additional information'\n});\n
\n
const process = require('process');\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);    // 'Warning'\n  console.warn(warning.message); // 'Something happened!'\n  console.warn(warning.code);    // 'MY_WARNING'\n  console.warn(warning.stack);   // Stack trace\n  console.warn(warning.detail);  // 'This is some additional information'\n});\n
\n

If warning is passed as an Error object, the options argument is ignored.

" }, { "textRaw": "`process.emitWarning(warning[, type[, code]][, ctor])`", "type": "method", "name": "emitWarning", "meta": { "added": [ "v6.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string|Error} The warning to emit.", "name": "warning", "type": "string|Error", "desc": "The warning to emit." }, { "textRaw": "`type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`.", "name": "type", "type": "string", "default": "`'Warning'`", "desc": "When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted." }, { "textRaw": "`code` {string} A unique identifier for the warning instance being emitted.", "name": "code", "type": "string", "desc": "A unique identifier for the warning instance being emitted." }, { "textRaw": "`ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`.", "name": "ctor", "type": "Function", "default": "`process.emitWarning`", "desc": "When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace." } ] } ], "desc": "

The process.emitWarning() method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\n'warning' event.

\n
import { emitWarning } from 'process';\n\n// Emit a warning using a string.\nemitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n
const { emitWarning } = require('process');\n\n// Emit a warning using a string.\nemitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n
import { emitWarning } from 'process';\n\n// Emit a warning using a string and a type.\nemitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
\n
const { emitWarning } = require('process');\n\n// Emit a warning using a string and a type.\nemitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
\n
import { emitWarning } from 'process';\n\nemitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
\n
const { emitWarning } = require('process');\n\nprocess.emitWarning('Something happened!', 'CustomWarning', 'WARN001');\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
\n

In each of the previous examples, an Error object is generated internally by\nprocess.emitWarning() and passed through to the 'warning'\nhandler.

\n
import process from 'process';\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.code);\n  console.warn(warning.stack);\n});\n
\n
const process = require('process');\n\nprocess.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.code);\n  console.warn(warning.stack);\n});\n
\n

If warning is passed as an Error object, it will be passed through to the\n'warning' event handler unmodified (and the optional type,\ncode and ctor arguments will be ignored):

\n
import { emitWarning } from 'process';\n\n// Emit a warning using an Error object.\nconst myWarning = new Error('Something happened!');\n// Use the Error name property to specify the type name\nmyWarning.name = 'CustomWarning';\nmyWarning.code = 'WARN001';\n\nemitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
\n
const { emitWarning } = require('process');\n\n// Emit a warning using an Error object.\nconst myWarning = new Error('Something happened!');\n// Use the Error name property to specify the type name\nmyWarning.name = 'CustomWarning';\nmyWarning.code = 'WARN001';\n\nemitWarning(myWarning);\n// Emits: (node:56338) [WARN001] CustomWarning: Something happened!\n
\n

A TypeError is thrown if warning is anything other than a string or Error\nobject.

\n

While process warnings use Error objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.

\n

The following additional handling is implemented if the warning type is\n'DeprecationWarning':

\n
    \n
  • If the --throw-deprecation command-line flag is used, the deprecation\nwarning is thrown as an exception rather than being emitted as an event.
  • \n
  • If the --no-deprecation command-line flag is used, the deprecation\nwarning is suppressed.
  • \n
  • If the --trace-deprecation command-line flag is used, the deprecation\nwarning is printed to stderr along with the full stack trace.
  • \n
", "modules": [ { "textRaw": "Avoiding duplicate warnings", "name": "avoiding_duplicate_warnings", "desc": "

As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning() behind a simple boolean\nflag as illustrated in the example below:

\n
import { emitWarning } from 'process';\n\nfunction emitMyWarning() {\n  if (!emitMyWarning.warned) {\n    emitMyWarning.warned = true;\n    emitWarning('Only warn once!');\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
\n
const { emitWarning } = require('process');\n\nfunction emitMyWarning() {\n  if (!emitMyWarning.warned) {\n    emitMyWarning.warned = true;\n    emitWarning('Only warn once!');\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
", "type": "module", "displayName": "Avoiding duplicate warnings" } ] }, { "textRaw": "`process.exit([code])`", "type": "method", "name": "exit", "meta": { "added": [ "v0.1.13" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {integer} The exit code. **Default:** `0`.", "name": "code", "type": "integer", "default": "`0`", "desc": "The exit code." } ] } ], "desc": "

The process.exit() method instructs Node.js to terminate the process\nsynchronously with an exit status of code. If code is omitted, exit uses\neither the 'success' code 0 or the value of process.exitCode if it has been\nset. Node.js will not terminate until all the 'exit' event listeners are\ncalled.

\n

To exit with a 'failure' code:

\n
import { exit } from 'process';\n\nexit(1);\n
\n
const { exit } = require('process');\n\nexit(1);\n
\n

The shell that executed Node.js should see the exit code as 1.

\n

Calling process.exit() will force the process to exit as quickly as possible\neven if there are still asynchronous operations pending that have not yet\ncompleted fully, including I/O operations to process.stdout and\nprocess.stderr.

\n

In most situations, it is not actually necessary to call process.exit()\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode property can be set to\ntell the process which exit code to use when the process exits gracefully.

\n

For instance, the following example illustrates a misuse of the\nprocess.exit() method that could lead to data printed to stdout being\ntruncated and lost:

\n
import { exit } from 'process';\n\n// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  exit(1);\n}\n
\n
const { exit } = require('process');\n\n// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  exit(1);\n}\n
\n

The reason this is problematic is because writes to process.stdout in Node.js\nare sometimes asynchronous and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit(), however, forces the process to exit\nbefore those additional writes to stdout can be performed.

\n

Rather than calling process.exit() directly, the code should set the\nprocess.exitCode and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:

\n
import process from 'process';\n\n// How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exitCode = 1;\n}\n
\n
const process = require('process');\n\n// How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.exitCode = 1;\n}\n
\n

If it is necessary to terminate the Node.js process due to an error condition,\nthrowing an uncaught error and allowing the process to terminate accordingly\nis safer than calling process.exit().

\n

In Worker threads, this function stops the current thread rather\nthan the current process.

" }, { "textRaw": "`process.getegid()`", "type": "method", "name": "getegid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)

\n
import process from 'process';\n\nif (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
\n
const process = require('process');\n\nif (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

" }, { "textRaw": "`process.geteuid()`", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)

\n
import process from 'process';\n\nif (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
\n
const process = require('process');\n\nif (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

" }, { "textRaw": "`process.getgid()`", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [] } ], "desc": "

The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)

\n
import process from 'process';\n\nif (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
\n
const process = require('process');\n\nif (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

" }, { "textRaw": "`process.getgroups()`", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer[]}", "name": "return", "type": "integer[]" }, "params": [] } ], "desc": "

The process.getgroups() method returns an array with the supplementary group\nIDs. POSIX leaves it unspecified if the effective group ID is included but\nNode.js ensures it always is.

\n
import process from 'process';\n\nif (process.getgroups) {\n  console.log(process.getgroups()); // [ 16, 21, 297 ]\n}\n
\n
const process = require('process');\n\nif (process.getgroups) {\n  console.log(process.getgroups()); // [ 16, 21, 297 ]\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

" }, { "textRaw": "`process.getuid()`", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)

\n
import process from 'process';\n\nif (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
\n
const process = require('process');\n\nif (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).

" }, { "textRaw": "`process.hasUncaughtExceptionCaptureCallback()`", "type": "method", "name": "hasUncaughtExceptionCaptureCallback", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

Indicates whether a callback has been set using\nprocess.setUncaughtExceptionCaptureCallback().

" }, { "textRaw": "`process.hrtime([time])`", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use [`process.hrtime.bigint()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {integer[]}", "name": "return", "type": "integer[]" }, "params": [ { "textRaw": "`time` {integer[]} The result of a previous call to `process.hrtime()`", "name": "time", "type": "integer[]", "desc": "The result of a previous call to `process.hrtime()`" } ] } ], "desc": "

This is the legacy version of process.hrtime.bigint()\nbefore bigint was introduced in JavaScript.

\n

The process.hrtime() method returns the current high-resolution real time\nin a [seconds, nanoseconds] tuple Array, where nanoseconds is the\nremaining part of the real time that can't be represented in second precision.

\n

time is an optional parameter that must be the result of a previous\nprocess.hrtime() call to diff with the current time. If the parameter\npassed in is not a tuple Array, a TypeError will be thrown. Passing in a\nuser-defined array instead of the result of a previous call to\nprocess.hrtime() will lead to undefined behavior.

\n

These times are relative to an arbitrary time in the\npast, and not related to the time of day and therefore not subject to clock\ndrift. The primary use is for measuring performance between intervals:

\n
import { hrtime } from 'process';\n\nconst NS_PER_SEC = 1e9;\nconst time = hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);\n  // Benchmark took 1000000552 nanoseconds\n}, 1000);\n
\n
const { hrtime } = require('process');\n\nconst NS_PER_SEC = 1e9;\nconst time = hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);\n  // Benchmark took 1000000552 nanoseconds\n}, 1000);\n
" }, { "textRaw": "`process.hrtime.bigint()`", "type": "method", "name": "bigint", "meta": { "added": [ "v10.7.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {bigint}", "name": "return", "type": "bigint" }, "params": [] } ], "desc": "

The bigint version of the process.hrtime() method returning the\ncurrent high-resolution real time in nanoseconds as a bigint.

\n

Unlike process.hrtime(), it does not support an additional time\nargument since the difference can just be computed directly\nby subtraction of the two bigints.

\n
import { hrtime } from 'process';\n\nconst start = hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n  const end = hrtime.bigint();\n  // 191052633396993n\n\n  console.log(`Benchmark took ${end - start} nanoseconds`);\n  // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
\n
const { hrtime } = require('process');\n\nconst start = hrtime.bigint();\n// 191051479007711n\n\nsetTimeout(() => {\n  const end = hrtime.bigint();\n  // 191052633396993n\n\n  console.log(`Benchmark took ${end - start} nanoseconds`);\n  // Benchmark took 1154389282 nanoseconds\n}, 1000);\n
" }, { "textRaw": "`process.initgroups(user, extraGroup)`", "type": "method", "name": "initgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`user` {string|number} The user name or numeric identifier.", "name": "user", "type": "string|number", "desc": "The user name or numeric identifier." }, { "textRaw": "`extraGroup` {string|number} A group name or numeric identifier.", "name": "extraGroup", "type": "string|number", "desc": "A group name or numeric identifier." } ] } ], "desc": "

The process.initgroups() method reads the /etc/group file and initializes\nthe group access list, using all groups of which the user is a member. This is\na privileged operation that requires that the Node.js process either have root\naccess or the CAP_SETGID capability.

\n

Use care when dropping privileges:

\n
import { getgroups, initgroups, setgid } from 'process';\n\nconsole.log(getgroups());         // [ 0 ]\ninitgroups('nodeuser', 1000);     // switch user\nconsole.log(getgroups());         // [ 27, 30, 46, 1000, 0 ]\nsetgid(1000);                     // drop root gid\nconsole.log(getgroups());         // [ 27, 30, 46, 1000 ]\n
\n
const { getgroups, initgroups, setgid } = require('process');\n\nconsole.log(getgroups());         // [ 0 ]\ninitgroups('nodeuser', 1000);     // switch user\nconsole.log(getgroups());         // [ 27, 30, 46, 1000, 0 ]\nsetgid(1000);                     // drop root gid\nconsole.log(getgroups());         // [ 27, 30, 46, 1000 ]\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.kill(pid[, signal])`", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`pid` {number} A process ID", "name": "pid", "type": "number", "desc": "A process ID" }, { "textRaw": "`signal` {string|number} The signal to send, either as a string or number. **Default:** `'SIGTERM'`.", "name": "signal", "type": "string|number", "default": "`'SIGTERM'`", "desc": "The signal to send, either as a string or number." } ] } ], "desc": "

The process.kill() method sends the signal to the process identified by\npid.

\n

Signal names are strings such as 'SIGINT' or 'SIGHUP'. See Signal Events\nand kill(2) for more information.

\n

This method will throw an error if the target pid does not exist. As a special\ncase, a signal of 0 can be used to test for the existence of a process.\nWindows platforms will throw an error if the pid is used to kill a process\ngroup.

\n

Even though the name of this function is process.kill(), it is really just a\nsignal sender, like the kill system call. The signal sent may do something\nother than kill the target process.

\n
import process, { kill } from 'process';\n\nprocess.on('SIGHUP', () => {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nkill(process.pid, 'SIGHUP');\n
\n
const process = require('process');\n\nprocess.on('SIGHUP', () => {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
\n

When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger. See Signal Events.

" }, { "textRaw": "`process.memoryUsage()`", "type": "method", "name": "memoryUsage", "meta": { "added": [ "v0.1.16" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31550", "description": "Added `arrayBuffers` to the returned object." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9587", "description": "Added `external` to the returned object." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`rss` {integer}", "name": "rss", "type": "integer" }, { "textRaw": "`heapTotal` {integer}", "name": "heapTotal", "type": "integer" }, { "textRaw": "`heapUsed` {integer}", "name": "heapUsed", "type": "integer" }, { "textRaw": "`external` {integer}", "name": "external", "type": "integer" }, { "textRaw": "`arrayBuffers` {integer}", "name": "arrayBuffers", "type": "integer" } ] }, "params": [] } ], "desc": "

Returns an object describing the memory usage of the Node.js process measured in\nbytes.

\n
import { memoryUsage } from 'process';\n\nconsole.log(memoryUsage());\n// Prints:\n// {\n//  rss: 4935680,\n//  heapTotal: 1826816,\n//  heapUsed: 650472,\n//  external: 49879,\n//  arrayBuffers: 9386\n// }\n
\n
const { memoryUsage } = require('process');\n\nconsole.log(memoryUsage());\n// Prints:\n// {\n//  rss: 4935680,\n//  heapTotal: 1826816,\n//  heapUsed: 650472,\n//  external: 49879,\n//  arrayBuffers: 9386\n// }\n
\n
    \n
  • heapTotal and heapUsed refer to V8's memory usage.
  • \n
  • external refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8.
  • \n
  • rss, Resident Set Size, is the amount of space occupied in the main\nmemory device (that is a subset of the total allocated memory) for the\nprocess, including all C++ and JavaScript objects and code.
  • \n
  • arrayBuffers refers to memory allocated for ArrayBuffers and\nSharedArrayBuffers, including all Node.js Buffers.\nThis is also included in the external value. When Node.js is used as an\nembedded library, this value may be 0 because allocations for ArrayBuffers\nmay not be tracked in that case.
  • \n
\n

When using Worker threads, rss will be a value that is valid for the\nentire process, while the other fields will only refer to the current thread.

\n

The process.memoryUsage() method iterates over each page to gather\ninformation about memory usage which might be slow depending on the\nprogram memory allocations.

" }, { "textRaw": "`process.memoryUsage.rss()`", "type": "method", "name": "rss", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {integer}", "name": "return", "type": "integer" }, "params": [] } ], "desc": "

The process.memoryUsage.rss() method returns an integer representing the\nResident Set Size (RSS) in bytes.

\n

The Resident Set Size, is the amount of space occupied in the main\nmemory device (that is a subset of the total allocated memory) for the\nprocess, including all C++ and JavaScript objects and code.

\n

This is the same value as the rss property provided by process.memoryUsage()\nbut process.memoryUsage.rss() is faster.

\n
import { memoryUsage } from 'process';\n\nconsole.log(memoryUsage.rss());\n// 35655680\n
\n
const { rss } = require('process');\n\nconsole.log(memoryUsage.rss());\n// 35655680\n
" }, { "textRaw": "`process.nextTick(callback[, ...args])`", "type": "method", "name": "nextTick", "meta": { "added": [ "v0.1.26" ], "changes": [ { "version": "v1.8.1", "pr-url": "https://github.com/nodejs/node/pull/1077", "description": "Additional arguments after `callback` are now supported." } ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" }, { "textRaw": "`...args` {any} Additional arguments to pass when invoking the `callback`", "name": "...args", "type": "any", "desc": "Additional arguments to pass when invoking the `callback`" } ] } ], "desc": "

process.nextTick() adds callback to the \"next tick queue\". This queue is\nfully drained after the current operation on the JavaScript stack runs to\ncompletion and before the event loop is allowed to continue. It's possible to\ncreate an infinite loop if one were to recursively call process.nextTick().\nSee the Event Loop guide for more background.

\n
import { nextTick } from 'process';\n\nconsole.log('start');\nnextTick(() => {\n  console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
\n
const { nextTick } = require('process');\n\nconsole.log('start');\nnextTick(() => {\n  console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
\n

This is important when developing APIs in order to give users the opportunity\nto assign event handlers after an object has been constructed but before any\nI/O has occurred:

\n
import { nextTick } from 'process';\n\nfunction MyThing(options) {\n  this.setupOptions(options);\n\n  nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
\n
const { nextTick } = require('process');\n\nfunction MyThing(options) {\n  this.setupOptions(options);\n\n  nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nconst thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.\n
\n

It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:

\n
// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n

This API is hazardous because in the following case:

\n
const maybeTrue = Math.random() > 0.5;\n\nmaybeSync(maybeTrue, () => {\n  foo();\n});\n\nbar();\n
\n

It is not clear whether foo() or bar() will be called first.

\n

The following approach is much better:

\n
import { nextTick } from 'process';\n\nfunction definitelyAsync(arg, cb) {\n  if (arg) {\n    nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n
const { nextTick } = require('process');\n\nfunction definitelyAsync(arg, cb) {\n  if (arg) {\n    nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
", "modules": [ { "textRaw": "When to use `queueMicrotask()` vs. `process.nextTick()`", "name": "when_to_use_`queuemicrotask()`_vs._`process.nexttick()`", "desc": "

The queueMicrotask() API is an alternative to process.nextTick() that\nalso defers execution of a function using the same microtask queue used to\nexecute the then, catch, and finally handlers of resolved promises. Within\nNode.js, every time the \"next tick queue\" is drained, the microtask queue\nis drained immediately after.

\n
import { nextTick } from 'process';\n\nPromise.resolve().then(() => console.log(2));\nqueueMicrotask(() => console.log(3));\nnextTick(() => console.log(1));\n// Output:\n// 1\n// 2\n// 3\n
\n
const { nextTick } = require('process');\n\nPromise.resolve().then(() => console.log(2));\nqueueMicrotask(() => console.log(3));\nnextTick(() => console.log(1));\n// Output:\n// 1\n// 2\n// 3\n
\n

For most userland use cases, the queueMicrotask() API provides a portable\nand reliable mechanism for deferring execution that works across multiple\nJavaScript platform environments and should be favored over process.nextTick().\nIn simple scenarios, queueMicrotask() can be a drop-in replacement for\nprocess.nextTick().

\n
console.log('start');\nqueueMicrotask(() => {\n  console.log('microtask callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// microtask callback\n
\n

One note-worthy difference between the two APIs is that process.nextTick()\nallows specifying additional values that will be passed as arguments to the\ndeferred function when it is called. Achieving the same result with\nqueueMicrotask() requires using either a closure or a bound function:

\n
function deferred(a, b) {\n  console.log('microtask', a + b);\n}\n\nconsole.log('start');\nqueueMicrotask(deferred.bind(undefined, 1, 2));\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// microtask 3\n
\n

There are minor differences in the way errors raised from within the next tick\nqueue and microtask queue are handled. Errors thrown within a queued microtask\ncallback should be handled within the queued callback when possible. If they are\nnot, the process.on('uncaughtException') event handler can be used to capture\nand handle the errors.

\n

When in doubt, unless the specific capabilities of process.nextTick() are\nneeded, use queueMicrotask().

", "type": "module", "displayName": "When to use `queueMicrotask()` vs. `process.nextTick()`" } ] }, { "textRaw": "`process.resourceUsage()`", "type": "method", "name": "resourceUsage", "meta": { "added": [ "v12.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", "name": "return", "type": "Object", "desc": "the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t].", "options": [ { "textRaw": "`userCPUTime` {integer} maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage].", "name": "userCPUTime", "type": "integer", "desc": "maps to `ru_utime` computed in microseconds. It is the same value as [`process.cpuUsage().user`][process.cpuUsage]." }, { "textRaw": "`systemCPUTime` {integer} maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage].", "name": "systemCPUTime", "type": "integer", "desc": "maps to `ru_stime` computed in microseconds. It is the same value as [`process.cpuUsage().system`][process.cpuUsage]." }, { "textRaw": "`maxRSS` {integer} maps to `ru_maxrss` which is the maximum resident set size used in kilobytes.", "name": "maxRSS", "type": "integer", "desc": "maps to `ru_maxrss` which is the maximum resident set size used in kilobytes." }, { "textRaw": "`sharedMemorySize` {integer} maps to `ru_ixrss` but is not supported by any platform.", "name": "sharedMemorySize", "type": "integer", "desc": "maps to `ru_ixrss` but is not supported by any platform." }, { "textRaw": "`unsharedDataSize` {integer} maps to `ru_idrss` but is not supported by any platform.", "name": "unsharedDataSize", "type": "integer", "desc": "maps to `ru_idrss` but is not supported by any platform." }, { "textRaw": "`unsharedStackSize` {integer} maps to `ru_isrss` but is not supported by any platform.", "name": "unsharedStackSize", "type": "integer", "desc": "maps to `ru_isrss` but is not supported by any platform." }, { "textRaw": "`minorPageFault` {integer} maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault].", "name": "minorPageFault", "type": "integer", "desc": "maps to `ru_minflt` which is the number of minor page faults for the process, see [this article for more details][wikipedia_minor_fault]." }, { "textRaw": "`majorPageFault` {integer} maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows.", "name": "majorPageFault", "type": "integer", "desc": "maps to `ru_majflt` which is the number of major page faults for the process, see [this article for more details][wikipedia_major_fault]. This field is not supported on Windows." }, { "textRaw": "`swappedOut` {integer} maps to `ru_nswap` but is not supported by any platform.", "name": "swappedOut", "type": "integer", "desc": "maps to `ru_nswap` but is not supported by any platform." }, { "textRaw": "`fsRead` {integer} maps to `ru_inblock` which is the number of times the file system had to perform input.", "name": "fsRead", "type": "integer", "desc": "maps to `ru_inblock` which is the number of times the file system had to perform input." }, { "textRaw": "`fsWrite` {integer} maps to `ru_oublock` which is the number of times the file system had to perform output.", "name": "fsWrite", "type": "integer", "desc": "maps to `ru_oublock` which is the number of times the file system had to perform output." }, { "textRaw": "`ipcSent` {integer} maps to `ru_msgsnd` but is not supported by any platform.", "name": "ipcSent", "type": "integer", "desc": "maps to `ru_msgsnd` but is not supported by any platform." }, { "textRaw": "`ipcReceived` {integer} maps to `ru_msgrcv` but is not supported by any platform.", "name": "ipcReceived", "type": "integer", "desc": "maps to `ru_msgrcv` but is not supported by any platform." }, { "textRaw": "`signalsCount` {integer} maps to `ru_nsignals` but is not supported by any platform.", "name": "signalsCount", "type": "integer", "desc": "maps to `ru_nsignals` but is not supported by any platform." }, { "textRaw": "`voluntaryContextSwitches` {integer} maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows.", "name": "voluntaryContextSwitches", "type": "integer", "desc": "maps to `ru_nvcsw` which is the number of times a CPU context switch resulted due to a process voluntarily giving up the processor before its time slice was completed (usually to await availability of a resource). This field is not supported on Windows." }, { "textRaw": "`involuntaryContextSwitches` {integer} maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows.", "name": "involuntaryContextSwitches", "type": "integer", "desc": "maps to `ru_nivcsw` which is the number of times a CPU context switch resulted due to a higher priority process becoming runnable or because the current process exceeded its time slice. This field is not supported on Windows." } ] }, "params": [] } ], "desc": "
import { resourceUsage } from 'process';\n\nconsole.log(resourceUsage());\n/*\n  Will output:\n  {\n    userCPUTime: 82872,\n    systemCPUTime: 4143,\n    maxRSS: 33164,\n    sharedMemorySize: 0,\n    unsharedDataSize: 0,\n    unsharedStackSize: 0,\n    minorPageFault: 2469,\n    majorPageFault: 0,\n    swappedOut: 0,\n    fsRead: 0,\n    fsWrite: 8,\n    ipcSent: 0,\n    ipcReceived: 0,\n    signalsCount: 0,\n    voluntaryContextSwitches: 79,\n    involuntaryContextSwitches: 1\n  }\n*/\n
\n
const { resourceUsage } = require('process');\n\nconsole.log(resourceUsage());\n/*\n  Will output:\n  {\n    userCPUTime: 82872,\n    systemCPUTime: 4143,\n    maxRSS: 33164,\n    sharedMemorySize: 0,\n    unsharedDataSize: 0,\n    unsharedStackSize: 0,\n    minorPageFault: 2469,\n    majorPageFault: 0,\n    swappedOut: 0,\n    fsRead: 0,\n    fsWrite: 8,\n    ipcSent: 0,\n    ipcReceived: 0,\n    signalsCount: 0,\n    voluntaryContextSwitches: 79,\n    involuntaryContextSwitches: 1\n  }\n*/\n
" }, { "textRaw": "`process.send(message[, sendHandle[, options]][, callback])`", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object}", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {net.Server|net.Socket}", "name": "sendHandle", "type": "net.Server|net.Socket" }, { "textRaw": "`options` {Object} used to parameterize the sending of certain types of handles.`options` supports the following properties:", "name": "options", "type": "Object", "desc": "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." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

If Node.js is spawned with an IPC channel, the process.send() method can be\nused to send messages to the parent process. Messages will be received as a\n'message' event on the parent's ChildProcess object.

\n

If Node.js was not spawned with an IPC channel, process.send will be\nundefined.

\n

The message goes through serialization and parsing. The resulting message might\nnot be the same as what is originally sent.

" }, { "textRaw": "`process.setegid(id)`", "type": "method", "name": "setegid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A group name or ID", "name": "id", "type": "string|number", "desc": "A group name or ID" } ] } ], "desc": "

The process.setegid() method sets the effective group identity of the process.\n(See setegid(2).) The id can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.

\n
import process from 'process';\n\nif (process.getegid && process.setegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n  try {\n    process.setegid(501);\n    console.log(`New gid: ${process.getegid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n
const process = require('process');\n\nif (process.getegid && process.setegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n  try {\n    process.setegid(501);\n    console.log(`New gid: ${process.getegid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.seteuid(id)`", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A user name or ID", "name": "id", "type": "string|number", "desc": "A user name or ID" } ] } ], "desc": "

The process.seteuid() method sets the effective user identity of the process.\n(See seteuid(2).) The id can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.

\n
import process from 'process';\n\nif (process.geteuid && process.seteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n  try {\n    process.seteuid(501);\n    console.log(`New uid: ${process.geteuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n
const process = require('process');\n\nif (process.geteuid && process.seteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n  try {\n    process.seteuid(501);\n    console.log(`New uid: ${process.geteuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.setgid(id)`", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} The group name or ID", "name": "id", "type": "string|number", "desc": "The group name or ID" } ] } ], "desc": "

The process.setgid() method sets the group identity of the process. (See\nsetgid(2).) The id can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.

\n
import process from 'process';\n\nif (process.getgid && process.setgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n  try {\n    process.setgid(501);\n    console.log(`New gid: ${process.getgid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n
const process = require('process');\n\nif (process.getgid && process.setgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n  try {\n    process.setgid(501);\n    console.log(`New gid: ${process.getgid()}`);\n  } catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.setgroups(groups)`", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`groups` {integer[]}", "name": "groups", "type": "integer[]" } ] } ], "desc": "

The process.setgroups() method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js\nprocess to have root or the CAP_SETGID capability.

\n

The groups array can contain numeric group IDs, group names, or both.

\n
import process from 'process';\n\nif (process.getgroups && process.setgroups) {\n  try {\n    process.setgroups([501]);\n    console.log(process.getgroups()); // new groups\n  } catch (err) {\n    console.log(`Failed to set groups: ${err}`);\n  }\n}\n
\n
const process = require('process');\n\nif (process.getgroups && process.setgroups) {\n  try {\n    process.setgroups([501]);\n    console.log(process.getgroups()); // new groups\n  } catch (err) {\n    console.log(`Failed to set groups: ${err}`);\n  }\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.setuid(id)`", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`id` {integer | string}", "name": "id", "type": "integer | string" } ] } ], "desc": "

The process.setuid(id) method sets the user identity of the process. (See\nsetuid(2).) The id can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.

\n
import process from 'process';\n\nif (process.getuid && process.setuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n  try {\n    process.setuid(501);\n    console.log(`New uid: ${process.getuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n
const process = require('process');\n\nif (process.getuid && process.setuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n  try {\n    process.setuid(501);\n    console.log(`New uid: ${process.getuid()}`);\n  } catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}\n
\n

This function is only available on POSIX platforms (i.e. not Windows or\nAndroid).\nThis feature is not available in Worker threads.

" }, { "textRaw": "`process.setSourceMapsEnabled(val)`", "type": "method", "name": "setSourceMapsEnabled", "meta": { "added": [ "v16.6.0" ], "changes": [] }, "stability": 1, "stabilityText": "Experimental", "signatures": [ { "params": [ { "textRaw": "`val` {boolean}", "name": "val", "type": "boolean" } ] } ], "desc": "

This function enables or disables the Source Map v3 support for\nstack traces.

\n

It provides same features as launching Node.js process with commandline options\n--enable-source-maps.

\n

Only source maps in JavaScript files that are loaded after source maps has been\nenabled will be parsed and loaded.

" }, { "textRaw": "`process.setUncaughtExceptionCaptureCallback(fn)`", "type": "method", "name": "setUncaughtExceptionCaptureCallback", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`fn` {Function|null}", "name": "fn", "type": "Function|null" } ] } ], "desc": "

The process.setUncaughtExceptionCaptureCallback() function sets a function\nthat will be invoked when an uncaught exception occurs, which will receive the\nexception value itself as its first argument.

\n

If such a function is set, the 'uncaughtException' event will\nnot be emitted. If --abort-on-uncaught-exception was passed from the\ncommand line or set through v8.setFlagsFromString(), the process will\nnot abort. Actions configured to take place on exceptions such as report\ngenerations will be affected too

\n

To unset the capture function,\nprocess.setUncaughtExceptionCaptureCallback(null) may be used. Calling this\nmethod with a non-null argument while another capture function is set will\nthrow an error.

\n

Using this function is mutually exclusive with using the deprecated\ndomain built-in module.

" }, { "textRaw": "`process.umask()`", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ], "changes": [ { "version": [ "v14.0.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/32499", "description": "Calling `process.umask()` with no arguments is deprecated." } ] }, "stability": 0, "stabilityText": "Deprecated. Calling `process.umask()` with no argument causes\nthe process-wide umask to be written twice. This introduces a race condition\nbetween threads, and is a potential security vulnerability. There is no safe,\ncross-platform alternative API.", "signatures": [ { "params": [] } ], "desc": "

process.umask() returns the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process.

" }, { "textRaw": "`process.umask(mask)`", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`mask` {string|integer}", "name": "mask", "type": "string|integer" } ] } ], "desc": "

process.umask(mask) sets the Node.js process's file mode creation mask. Child\nprocesses inherit the mask from the parent process. Returns the previous mask.

\n
import { umask } from 'process';\n\nconst newmask = 0o022;\nconst oldmask = umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n
const { umask } = require('process');\n\nconst newmask = 0o022;\nconst oldmask = umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n

In Worker threads, process.umask(mask) will throw an exception.

" }, { "textRaw": "`process.uptime()`", "type": "method", "name": "uptime", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number}", "name": "return", "type": "number" }, "params": [] } ], "desc": "

The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

\n

The return value includes fractions of a second. Use Math.floor() to get whole\nseconds.

" } ], "properties": [ { "textRaw": "`allowedNodeEnvironmentFlags` {Set}", "type": "Set", "name": "allowedNodeEnvironmentFlags", "meta": { "added": [ "v10.10.0" ], "changes": [] }, "desc": "

The process.allowedNodeEnvironmentFlags property is a special,\nread-only Set of flags allowable within the NODE_OPTIONS\nenvironment variable.

\n

process.allowedNodeEnvironmentFlags extends Set, but overrides\nSet.prototype.has to recognize several different possible flag\nrepresentations. process.allowedNodeEnvironmentFlags.has() will\nreturn true in the following cases:

\n
    \n
  • Flags may omit leading single (-) or double (--) dashes; e.g.,\ninspect-brk for --inspect-brk, or r for -r.
  • \n
  • Flags passed through to V8 (as listed in --v8-options) may replace\none or more non-leading dashes for an underscore, or vice-versa;\ne.g., --perf_basic_prof, --perf-basic-prof, --perf_basic-prof,\netc.
  • \n
  • Flags may contain one or more equals (=) characters; all\ncharacters after and including the first equals will be ignored;\ne.g., --stack-trace-limit=100.
  • \n
  • Flags must be allowable within NODE_OPTIONS.
  • \n
\n

When iterating over process.allowedNodeEnvironmentFlags, flags will\nappear only once; each will begin with one or more dashes. Flags\npassed through to V8 will contain underscores instead of non-leading\ndashes:

\n
import { allowedNodeEnvironmentFlags } from 'process';\n\nallowedNodeEnvironmentFlags.forEach((flag) => {\n  // -r\n  // --inspect-brk\n  // --abort_on_uncaught_exception\n  // ...\n});\n
\n
const { allowedNodeEnvironmentFlags } = require('process');\n\nallowedNodeEnvironmentFlags.forEach((flag) => {\n  // -r\n  // --inspect-brk\n  // --abort_on_uncaught_exception\n  // ...\n});\n
\n

The methods add(), clear(), and delete() of\nprocess.allowedNodeEnvironmentFlags do nothing, and will fail\nsilently.

\n

If Node.js was compiled without NODE_OPTIONS support (shown in\nprocess.config), process.allowedNodeEnvironmentFlags will\ncontain what would have been allowable.

" }, { "textRaw": "`arch` {string}", "type": "string", "name": "arch", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

The operating system CPU architecture for which the Node.js binary was compiled.\nPossible values are: 'arm', 'arm64', 'ia32', 'mips','mipsel', 'ppc',\n'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n
import { arch } from 'process';\n\nconsole.log(`This processor architecture is ${arch}`);\n
\n
const { arch } = require('process');\n\nconsole.log(`This processor architecture is ${process.arch}`);\n
" }, { "textRaw": "`argv` {string[]}", "type": "string[]", "name": "argv", "meta": { "added": [ "v0.1.27" ], "changes": [] }, "desc": "

The process.argv property returns an array containing the command-line\narguments passed when the Node.js process was launched. The first element will\nbe process.execPath. See process.argv0 if access to the original value\nof argv[0] is needed. The second element will be the path to the JavaScript\nfile being executed. The remaining elements will be any additional command-line\narguments.

\n

For example, assuming the following script for process-args.js:

\n
import { argv } from 'process';\n\n// print process.argv\nargv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
\n
const { argv } = require('process');\n\n// print process.argv\nargv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
\n

Launching the Node.js process as:

\n
$ node process-args.js one two=three four\n
\n

Would generate the output:

\n
0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-args.js\n2: one\n3: two=three\n4: four\n
" }, { "textRaw": "`argv0` {string}", "type": "string", "name": "argv0", "meta": { "added": [ "v6.4.0" ], "changes": [] }, "desc": "

The process.argv0 property stores a read-only copy of the original value of\nargv[0] passed when Node.js starts.

\n
$ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
" }, { "textRaw": "`channel` {Object}", "type": "Object", "name": "channel", "meta": { "added": [ "v7.1.0" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30165", "description": "The object no longer accidentally exposes native C++ bindings." } ] }, "desc": "

If the Node.js process was spawned with an IPC channel (see the\nChild Process documentation), the process.channel\nproperty is a reference to the IPC channel. If no IPC channel exists, this\nproperty is undefined.

", "methods": [ { "textRaw": "`process.channel.ref()`", "type": "method", "name": "ref", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This method makes the IPC channel keep the event loop of the process\nrunning if .unref() has been called before.

\n

Typically, this is managed through the number of 'disconnect' and 'message'\nlisteners on the process object. However, this method can be used to\nexplicitly request a specific behavior.

" }, { "textRaw": "`process.channel.unref()`", "type": "method", "name": "unref", "meta": { "added": [ "v7.1.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

This method makes the IPC channel not keep the event loop of the process\nrunning, and lets it finish even while the channel is open.

\n

Typically, this is managed through the number of 'disconnect' and 'message'\nlisteners on the process object. However, this method can be used to\nexplicitly request a specific behavior.

" } ] }, { "textRaw": "`config` {Object}", "type": "Object", "name": "config", "meta": { "added": [ "v0.7.7" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36902", "description": "Modifying process.config has been deprecated." } ] }, "desc": "

The process.config property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi file that was produced when\nrunning the ./configure script.

\n

An example of the possible output looks like:

\n\n
{\n  target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\n   {\n     host_arch: 'x64',\n     napi_build_version: 5,\n     node_install_npm: 'true',\n     node_prefix: '',\n     node_shared_cares: 'false',\n     node_shared_http_parser: 'false',\n     node_shared_libuv: 'false',\n     node_shared_zlib: 'false',\n     node_use_dtrace: 'false',\n     node_use_openssl: 'true',\n     node_shared_openssl: 'false',\n     strict_aliasing: 'true',\n     target_arch: 'x64',\n     v8_use_snapshot: 1\n   }\n}\n
\n

The process.config property is not read-only and there are existing\nmodules in the ecosystem that are known to extend, modify, or entirely replace\nthe value of process.config.

\n

Modifying the process.config property, or any child-property of the\nprocess.config object has been deprecated. The process.config will be made\nread-only in a future release.

" }, { "textRaw": "`connected` {boolean}", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "

If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.connected property will return\ntrue so long as the IPC channel is connected and will return false after\nprocess.disconnect() is called.

\n

Once process.connected is false, it is no longer possible to send messages\nover the IPC channel using process.send().

" }, { "textRaw": "`debugPort` {number}", "type": "number", "name": "debugPort", "meta": { "added": [ "v0.7.2" ], "changes": [] }, "desc": "

The port used by the Node.js debugger when enabled.

\n
import process from 'process';\n\nprocess.debugPort = 5858;\n
\n
const process = require('process');\n\nprocess.debugPort = 5858;\n
" }, { "textRaw": "`env` {Object}", "type": "Object", "name": "env", "meta": { "added": [ "v0.1.27" ], "changes": [ { "version": "v11.14.0", "pr-url": "https://github.com/nodejs/node/pull/26544", "description": "Worker threads will now use a copy of the parent thread’s `process.env` by default, configurable through the `env` option of the `Worker` constructor." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18990", "description": "Implicit conversion of variable value to string is deprecated." } ] }, "desc": "

The process.env property returns an object containing the user environment.\nSee environ(7).

\n

An example of this object looks like:

\n\n
{\n  TERM: 'xterm-256color',\n  SHELL: '/usr/local/bin/bash',\n  USER: 'maciej',\n  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n  PWD: '/Users/maciej',\n  EDITOR: 'vim',\n  SHLVL: '1',\n  HOME: '/Users/maciej',\n  LOGNAME: 'maciej',\n  _: '/usr/local/bin/node'\n}\n
\n

It is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process, or (unless explicitly requested)\nto other Worker threads.\nIn other words, the following example would not work:

\n
$ node -e 'process.env.foo = \"bar\"' && echo $foo\n
\n

While the following will:

\n
import { env } from 'process';\n\nenv.foo = 'bar';\nconsole.log(env.foo);\n
\n
const { env } = require('process');\n\nenv.foo = 'bar';\nconsole.log(env.foo);\n
\n

Assigning a property on process.env will implicitly convert the value\nto a string. This behavior is deprecated. Future versions of Node.js may\nthrow an error when the value is not a string, number, or boolean.

\n
import { env } from 'process';\n\nenv.test = null;\nconsole.log(env.test);\n// => 'null'\nenv.test = undefined;\nconsole.log(env.test);\n// => 'undefined'\n
\n
const { env } = require('process');\n\nenv.test = null;\nconsole.log(env.test);\n// => 'null'\nenv.test = undefined;\nconsole.log(env.test);\n// => 'undefined'\n
\n

Use delete to delete a property from process.env.

\n
import { env } from 'process';\n\nenv.TEST = 1;\ndelete env.TEST;\nconsole.log(env.TEST);\n// => undefined\n
\n
const { env } = require('process');\n\nenv.TEST = 1;\ndelete env.TEST;\nconsole.log(env.TEST);\n// => undefined\n
\n

On Windows operating systems, environment variables are case-insensitive.

\n
import { env } from 'process';\n\nenv.TEST = 1;\nconsole.log(env.test);\n// => 1\n
\n
const { env } = require('process');\n\nenv.TEST = 1;\nconsole.log(env.test);\n// => 1\n
\n

Unless explicitly specified when creating a Worker instance,\neach Worker thread has its own copy of process.env, based on its\nparent thread’s process.env, or whatever was specified as the env option\nto the Worker constructor. Changes to process.env will not be visible\nacross Worker threads, and only the main thread can make changes that\nare visible to the operating system or to native add-ons.

" }, { "textRaw": "`execArgv` {string[]}", "type": "string[]", "name": "execArgv", "meta": { "added": [ "v0.7.7" ], "changes": [] }, "desc": "

The process.execArgv property returns the set of Node.js-specific command-line\noptions passed when the Node.js process was launched. These options do not\nappear in the array returned by the process.argv property, and do not\ninclude the Node.js executable, the name of the script, or any options following\nthe script name. These options are useful in order to spawn child processes with\nthe same execution environment as the parent.

\n
$ node --harmony script.js --version\n
\n

Results in process.execArgv:

\n\n
['--harmony']\n
\n

And process.argv:

\n\n
['/usr/local/bin/node', 'script.js', '--version']\n
\n

Refer to Worker constructor for the detailed behavior of worker\nthreads with this property.

" }, { "textRaw": "`execPath` {string}", "type": "string", "name": "execPath", "meta": { "added": [ "v0.1.100" ], "changes": [] }, "desc": "

The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process. Symbolic links, if any, are resolved.

\n\n
'/usr/local/bin/node'\n
" }, { "textRaw": "`exitCode` {integer}", "type": "integer", "name": "exitCode", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "

A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit() without specifying\na code.

\n

Specifying a code to process.exit(code) will override any\nprevious setting of process.exitCode.

" }, { "textRaw": "`mainModule` {Object}", "type": "Object", "name": "mainModule", "meta": { "added": [ "v0.1.17" ], "deprecated": [ "v14.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`require.main`][] instead.", "desc": "

The process.mainModule property provides an alternative way of retrieving\nrequire.main. The difference is that if the main module changes at\nruntime, require.main may still refer to the original main module in\nmodules that were required before the change occurred. Generally, it's\nsafe to assume that the two refer to the same module.

\n

As with require.main, process.mainModule will be undefined if there\nis no entry script.

" }, { "textRaw": "`noDeprecation` {boolean}", "type": "boolean", "name": "noDeprecation", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

The process.noDeprecation property indicates whether the --no-deprecation\nflag is set on the current Node.js process. See the documentation for\nthe 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

" }, { "textRaw": "`pid` {integer}", "type": "integer", "name": "pid", "meta": { "added": [ "v0.1.15" ], "changes": [] }, "desc": "

The process.pid property returns the PID of the process.

\n
import { pid } from 'process';\n\nconsole.log(`This process is pid ${pid}`);\n
\n
const { pid } = require('process');\n\nconsole.log(`This process is pid ${pid}`);\n
" }, { "textRaw": "`platform` {string}", "type": "string", "name": "platform", "meta": { "added": [ "v0.1.16" ], "changes": [] }, "desc": "

The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running.

\n

Currently possible values are:

\n
    \n
  • 'aix'
  • \n
  • 'darwin'
  • \n
  • 'freebsd'
  • \n
  • 'linux'
  • \n
  • 'openbsd'
  • \n
  • 'sunos'
  • \n
  • 'win32'
  • \n
\n
import { platform } from 'process';\n\nconsole.log(`This platform is ${platform}`);\n
\n
const { platform } = require('process');\n\nconsole.log(`This platform is ${platform}`);\n
\n

The value 'android' may also be returned if the Node.js is built on the\nAndroid operating system. However, Android support in Node.js\nis experimental.

" }, { "textRaw": "`ppid` {integer}", "type": "integer", "name": "ppid", "meta": { "added": [ "v9.2.0", "v8.10.0", "v6.13.0" ], "changes": [] }, "desc": "

The process.ppid property returns the PID of the parent of the\ncurrent process.

\n
import { ppid } from 'process';\n\nconsole.log(`The parent process is pid ${ppid}`);\n
\n
const { ppid } = require('process');\n\nconsole.log(`The parent process is pid ${ppid}`);\n
" }, { "textRaw": "`release` {Object}", "type": "Object", "name": "release", "meta": { "added": [ "v3.0.0" ], "changes": [ { "version": "v4.2.0", "pr-url": "https://github.com/nodejs/node/pull/3212", "description": "The `lts` property is now supported." } ] }, "desc": "

The process.release property returns an Object containing metadata related\nto the current release, including URLs for the source tarball and headers-only\ntarball.

\n

process.release contains the following properties:

\n
    \n
  • name <string> A value that will always be 'node'.
  • \n
  • sourceUrl <string> an absolute URL pointing to a .tar.gz file containing\nthe source code of the current release.
  • \n
  • headersUrl<string> an absolute URL pointing to a .tar.gz file containing\nonly the source header files for the current release. This file is\nsignificantly smaller than the full source file and can be used for compiling\nNode.js native add-ons.
  • \n
  • libUrl <string> an absolute URL pointing to a node.lib file matching the\narchitecture and version of the current release. This file is used for\ncompiling Node.js native add-ons. This property is only present on Windows\nbuilds of Node.js and will be missing on all other platforms.
  • \n
  • lts <string> a string label identifying the LTS label for this release.\nThis property only exists for LTS releases and is undefined for all other\nrelease types, including Current releases.\nValid values include the LTS Release code names (including those\nthat are no longer supported).\n
      \n
    • 'Dubnium' for the 10.x LTS line beginning with 10.13.0.
    • \n
    • 'Erbium' for the 12.x LTS line beginning with 12.13.0.
    • \n
    \nFor other LTS Release code names, see Node.js Changelog Archive
  • \n
\n\n
{\n  name: 'node',\n  lts: 'Erbium',\n  sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v12.18.1/win-x64/node.lib'\n}\n
\n

In custom builds from non-release versions of the source tree, only the\nname property may be present. The additional properties should not be\nrelied upon to exist.

" }, { "textRaw": "`report` {Object}", "type": "Object", "name": "report", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

process.report is an object whose methods are used to generate diagnostic\nreports for the current process. Additional documentation is available in the\nreport documentation.

", "properties": [ { "textRaw": "`compact` {boolean}", "type": "boolean", "name": "compact", "meta": { "added": [ "v13.12.0", "v12.17.0" ], "changes": [] }, "desc": "

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.

\n
import { report } from 'process';\n\nconsole.log(`Reports are compact? ${report.compact}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Reports are compact? ${report.compact}`);\n
" }, { "textRaw": "`directory` {string}", "type": "string", "name": "directory", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

Directory where the report is written. The default value is the empty string,\nindicating that reports are written to the current working directory of the\nNode.js process.

\n
import { report } from 'process';\n\nconsole.log(`Report directory is ${report.directory}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report directory is ${report.directory}`);\n
" }, { "textRaw": "`filename` {string}", "type": "string", "name": "filename", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

Filename where the report is written. If set to the empty string, the output\nfilename will be comprised of a timestamp, PID, and sequence number. The default\nvalue is the empty string.

\n
import { report } from 'process';\n\nconsole.log(`Report filename is ${report.filename}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report filename is ${report.filename}`);\n
" }, { "textRaw": "`reportOnFatalError` {boolean}", "type": "boolean", "name": "reportOnFatalError", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v15.0.0" ], "pr-url": "https://github.com/nodejs/node/pull/35654", "description": "This API is no longer experimental." } ] }, "desc": "

If true, a diagnostic report is generated on fatal errors, such as out of\nmemory errors or failed C++ assertions.

\n
import { report } from 'process';\n\nconsole.log(`Report on fatal error: ${report.reportOnFatalError}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report on fatal error: ${report.reportOnFatalError}`);\n
" }, { "textRaw": "`reportOnSignal` {boolean}", "type": "boolean", "name": "reportOnSignal", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

If true, a diagnostic report is generated when the process receives the\nsignal specified by process.report.signal.

\n
import { report } from 'process';\n\nconsole.log(`Report on signal: ${report.reportOnSignal}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report on signal: ${report.reportOnSignal}`);\n
" }, { "textRaw": "`reportOnUncaughtException` {boolean}", "type": "boolean", "name": "reportOnUncaughtException", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

If true, a diagnostic report is generated on uncaught exception.

\n
import { report } from 'process';\n\nconsole.log(`Report on exception: ${report.reportOnUncaughtException}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report on exception: ${report.reportOnUncaughtException}`);\n
" }, { "textRaw": "`signal` {string}", "type": "string", "name": "signal", "meta": { "added": [ "v11.12.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "desc": "

The signal used to trigger the creation of a diagnostic report. Defaults to\n'SIGUSR2'.

\n
import { report } from 'process';\n\nconsole.log(`Report signal: ${report.signal}`);\n
\n
const { report } = require('process');\n\nconsole.log(`Report signal: ${report.signal}`);\n
" } ], "methods": [ { "textRaw": "`process.report.getReport([err])`", "type": "method", "name": "getReport", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", "name": "err", "type": "Error", "desc": "A custom error used for reporting the JavaScript stack." } ] } ], "desc": "

Returns a JavaScript Object representation of a diagnostic report for the\nrunning process. The report's JavaScript stack trace is taken from err, if\npresent.

\n
import { report } from 'process';\n\nconst data = report.getReport();\nconsole.log(data.header.nodejsVersion);\n\n// Similar to process.report.writeReport()\nimport fs from 'fs';\nfs.writeFileSync('my-report.log', util.inspect(data), 'utf8');\n
\n
const { report } = require('process');\n\nconst data = report.getReport();\nconsole.log(data.header.nodejsVersion);\n\n// Similar to process.report.writeReport()\nconst fs = require('fs');\nfs.writeFileSync('my-report.log', util.inspect(data), 'utf8');\n
\n

Additional documentation is available in the report documentation.

" }, { "textRaw": "`process.report.writeReport([filename][, err])`", "type": "method", "name": "writeReport", "meta": { "added": [ "v11.8.0" ], "changes": [ { "version": [ "v13.12.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/32242", "description": "This API is no longer experimental." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} Returns the filename of the generated report.", "name": "return", "type": "string", "desc": "Returns the filename of the generated report." }, "params": [ { "textRaw": "`filename` {string} Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified.", "name": "filename", "type": "string", "desc": "Name of the file where the report is written. This should be a relative path, that will be appended to the directory specified in `process.report.directory`, or the current working directory of the Node.js process, if unspecified." }, { "textRaw": "`err` {Error} A custom error used for reporting the JavaScript stack.", "name": "err", "type": "Error", "desc": "A custom error used for reporting the JavaScript stack." } ] } ], "desc": "

Writes a diagnostic report to a file. If filename is not provided, the default\nfilename includes the date, time, PID, and a sequence number. The report's\nJavaScript stack trace is taken from err, if present.

\n
import { report } from 'process';\n\nreport.writeReport();\n
\n
const { report } = require('process');\n\nreport.writeReport();\n
\n

Additional documentation is available in the report documentation.

" } ] }, { "textRaw": "`stderr` {Stream}", "type": "Stream", "name": "stderr", "desc": "

The process.stderr property returns a stream connected to\nstderr (fd 2). It is a net.Socket (which is a Duplex\nstream) unless fd 2 refers to a file, in which case it is\na Writable stream.

\n

process.stderr differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

", "properties": [ { "textRaw": "`fd` {number}", "type": "number", "name": "fd", "desc": "

This property refers to the value of underlying file descriptor of\nprocess.stderr. The value is fixed at 2. In Worker threads,\nthis field does not exist.

" } ] }, { "textRaw": "`stdin` {Stream}", "type": "Stream", "name": "stdin", "desc": "

The process.stdin property returns a stream connected to\nstdin (fd 0). It is a net.Socket (which is a Duplex\nstream) unless fd 0 refers to a file, in which case it is\na Readable stream.

\n

For details of how to read from stdin see readable.read().

\n

As a Duplex stream, process.stdin can also be used in \"old\" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.

\n

In \"old\" streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to \"old\" mode.

", "properties": [ { "textRaw": "`fd` {number}", "type": "number", "name": "fd", "desc": "

This property refers to the value of underlying file descriptor of\nprocess.stdin. The value is fixed at 0. In Worker threads,\nthis field does not exist.

" } ] }, { "textRaw": "`stdout` {Stream}", "type": "Stream", "name": "stdout", "desc": "

The process.stdout property returns a stream connected to\nstdout (fd 1). It is a net.Socket (which is a Duplex\nstream) unless fd 1 refers to a file, in which case it is\na Writable stream.

\n

For example, to copy process.stdin to process.stdout:

\n
import { stdin, stdout } from 'process';\n\nstdin.pipe(stdout);\n
\n
const { stdin, stdout } = require('process');\n\nstdin.pipe(stdout);\n
\n

process.stdout differs from other Node.js streams in important ways. See\nnote on process I/O for more information.

", "properties": [ { "textRaw": "`fd` {number}", "type": "number", "name": "fd", "desc": "

This property refers to the value of underlying file descriptor of\nprocess.stdout. The value is fixed at 1. In Worker threads,\nthis field does not exist.

" } ], "modules": [ { "textRaw": "A note on process I/O", "name": "a_note_on_process_i/o", "desc": "

process.stdout and process.stderr differ from other Node.js streams in\nimportant ways:

\n
    \n
  1. They are used internally by console.log() and console.error(),\nrespectively.
  2. \n
  3. Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:\n
      \n
    • Files: synchronous on Windows and POSIX
    • \n
    • TTYs (Terminals): asynchronous on Windows, synchronous on POSIX
    • \n
    • Pipes (and sockets): synchronous on Windows, asynchronous on POSIX
    • \n
    \n
  4. \n
\n

These behaviors are partly for historical reasons, as changing them would\ncreate backward incompatibility, but they are also expected by some users.

\n

Synchronous writes avoid problems such as output written with console.log() or\nconsole.error() being unexpectedly interleaved, or not written at all if\nprocess.exit() is called before an asynchronous write completes. See\nprocess.exit() for more information.

\n

Warning: Synchronous writes block the event loop until the write has\ncompleted. This can be near instantaneous in the case of output to a file, but\nunder high system load, pipes that are not being read at the receiving end, or\nwith slow terminals or file systems, its possible for the event loop to be\nblocked often enough and long enough to have severe negative performance\nimpacts. This may not be a problem when writing to an interactive terminal\nsession, but consider this particularly careful when doing production logging to\nthe process output streams.

\n

To check if a stream is connected to a TTY context, check the isTTY\nproperty.

\n

For instance:

\n
$ node -p \"Boolean(process.stdin.isTTY)\"\ntrue\n$ echo \"foo\" | node -p \"Boolean(process.stdin.isTTY)\"\nfalse\n$ node -p \"Boolean(process.stdout.isTTY)\"\ntrue\n$ node -p \"Boolean(process.stdout.isTTY)\" | cat\nfalse\n
\n

See the TTY documentation for more information.

", "type": "module", "displayName": "A note on process I/O" } ] }, { "textRaw": "`throwDeprecation` {boolean}", "type": "boolean", "name": "throwDeprecation", "meta": { "added": [ "v0.9.12" ], "changes": [] }, "desc": "

The initial value of process.throwDeprecation indicates whether the\n--throw-deprecation flag is set on the current Node.js process.\nprocess.throwDeprecation is mutable, so whether or not deprecation\nwarnings result in errors may be altered at runtime. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information.

\n
$ node --throw-deprecation -p \"process.throwDeprecation\"\ntrue\n$ node -p \"process.throwDeprecation\"\nundefined\n$ node\n> process.emitWarning('test', 'DeprecationWarning');\nundefined\n> (node:26598) DeprecationWarning: test\n> process.throwDeprecation = true;\ntrue\n> process.emitWarning('test', 'DeprecationWarning');\nThrown:\n[DeprecationWarning: test] { name: 'DeprecationWarning' }\n
" }, { "textRaw": "`title` {string}", "type": "string", "name": "title", "meta": { "added": [ "v0.1.104" ], "changes": [] }, "desc": "

The process.title property returns the current process title (i.e. returns\nthe current value of ps). Assigning a new value to process.title modifies\nthe current value of ps.

\n

When a new value is assigned, different platforms will impose different maximum\nlength restrictions on the title. Usually such restrictions are quite limited.\nFor instance, on Linux and macOS, process.title is limited to the size of the\nbinary name plus the length of the command-line arguments because setting the\nprocess.title overwrites the argv memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.

\n

Assigning a value to process.title might not result in an accurate label\nwithin process manager applications such as macOS Activity Monitor or Windows\nServices Manager.

" }, { "textRaw": "`traceDeprecation` {boolean}", "type": "boolean", "name": "traceDeprecation", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

The process.traceDeprecation property indicates whether the\n--trace-deprecation flag is set on the current Node.js process. See the\ndocumentation for the 'warning' event and the\nemitWarning() method for more information about this\nflag's behavior.

" }, { "textRaw": "`version` {string}", "type": "string", "name": "version", "meta": { "added": [ "v0.1.3" ], "changes": [] }, "desc": "

The process.version property contains the Node.js version string.

\n
import { version } from 'process';\n\nconsole.log(`Version: ${version}`);\n// Version: v14.8.0\n
\n
const { version } = require('process');\n\nconsole.log(`Version: ${version}`);\n// Version: v14.8.0\n
\n

To get the version string without the prepended v, use\nprocess.versions.node.

" }, { "textRaw": "`versions` {Object}", "type": "Object", "name": "versions", "meta": { "added": [ "v0.2.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15785", "description": "The `v8` property now includes a Node.js specific suffix." }, { "version": "v4.2.0", "pr-url": "https://github.com/nodejs/node/pull/3102", "description": "The `icu` property is now supported." } ] }, "desc": "

The process.versions property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.

\n
import { versions } from 'process';\n\nconsole.log(versions);\n
\n
const { versions } = require('process');\n\nconsole.log(versions);\n
\n

Will generate an object similar to:

\n
{ node: '11.13.0',\n  v8: '7.0.276.38-node.18',\n  uv: '1.27.0',\n  zlib: '1.2.11',\n  brotli: '1.0.7',\n  ares: '1.15.0',\n  modules: '67',\n  nghttp2: '1.34.0',\n  napi: '4',\n  llhttp: '1.1.1',\n  openssl: '1.1.1b',\n  cldr: '34.0',\n  icu: '63.1',\n  tz: '2018e',\n  unicode: '11.0' }\n
" } ], "source": "doc/api/process.md" } ], "methods": [ { "textRaw": "`atob(data)`", "type": "method", "name": "atob", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use `Buffer.from(data, 'base64')` instead.", "signatures": [ { "params": [] } ], "desc": "

Global alias for buffer.atob().

", "source": "doc/api/globals.md" }, { "textRaw": "`btoa(data)`", "type": "method", "name": "btoa", "meta": { "added": [ "v16.0.0" ], "changes": [] }, "stability": 3, "stabilityText": "Legacy. Use `buf.toString('base64')` instead.", "signatures": [ { "params": [] } ], "desc": "

Global alias for buffer.btoa().

", "source": "doc/api/globals.md" }, { "textRaw": "`require()`", "type": "method", "name": "require", "signatures": [ { "params": [] } ], "desc": "

This variable may appear to be global but is not. See require().

", "source": "doc/api/globals.md" } ] }