{ "source": "doc/api/all.md", "desc": [ { "type": "html", "pre": false, "text": "\n" } ], "introduced_in": "v0.10.0", "miscs": [ { "textRaw": "About this Documentation", "name": "About this Documentation", "introduced_in": "v0.10.0", "type": "misc", "desc": "

The goal of this documentation is to comprehensively explain the Node.js\nAPI, both from a reference as well as a conceptual point of view. Each\nsection describes a built-in module or high-level concept.

\n

Where appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.

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

If you find an error in this documentation, please submit an issue\nor see the contributing guide for directions on how to submit a patch.

\n

Every file is generated based on the corresponding .md file in the\ndoc/api/ folder in Node.js's source tree. The documentation is generated\nusing the tools/doc/generate.js program. An HTML template is located at\ndoc/template.html.

\n", "type": "misc", "displayName": "Contributing" }, { "textRaw": "Stability Index", "name": "Stability Index", "type": "misc", "desc": "

Throughout the documentation, you will see indications of a section's\nstability. The Node.js API is still somewhat changing, and as it\nmatures, certain parts are more reliable than others. Some are so\nproven, and so relied upon, that they are unlikely to ever change at\nall. Others are brand new and experimental, or known to be hazardous\nand in the process of being redesigned.

\n

The stability indices are as follows:

\n
Stability: 0 - Deprecated\nThis feature is known to be problematic, and changes may be planned. Do\nnot rely on it. Use of the feature may cause warnings to be emitted.\nBackwards compatibility across major versions should not be expected.\n
\n
Stability: 1 - Experimental\nThis feature is still under active development and subject to non-backwards\ncompatible changes, or even removal, in any future version. Use of the feature\nis not recommended in production environments. Experimental features are not\nsubject to the Node.js Semantic Versioning model.\n
\n
Stability: 2 - Stable\nThe API has proven satisfactory. Compatibility with the npm ecosystem\nis a high priority, and will not be broken unless absolutely necessary.\n
\n

Note: Caution must be used when making use of Experimental features,\nparticularly within modules that may be used as dependencies (or dependencies\nof dependencies) within a Node.js application. End users may not be aware that\nexperimental features are being used, and therefore may experience unexpected\nfailures or behavior changes when API modifications occur. To help avoid such\nsurprises, Experimental features may require a command-line flag to\nexplicitly enable them, or may cause a process warning to be emitted.\nBy default, such warnings are printed to stderr and may be handled by\nattaching a listener to the process.on('warning') event.

\n" }, { "textRaw": "JSON Output", "name": "json_output", "meta": { "added": [ "v0.6.12" ] }, "stability": 1, "stabilityText": "Experimental", "desc": "

Every .html document has a corresponding .json document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.

\n", "type": "misc", "displayName": "JSON Output" }, { "textRaw": "Syscalls and man pages", "name": "syscalls_and_man_pages", "desc": "

System calls like open(2) and read(2) define the interface between user programs\nand the underlying operating system. Node functions which simply wrap a syscall,\nlike fs.open(), will document that. The docs link to the corresponding man\npages (short for manual pages) which describe how the syscalls work.

\n

Some syscalls, like lchown(2), are BSD-specific. That means, for\nexample, that fs.lchown() only works on macOS and other BSD-derived systems,\nand is not available on Linux.

\n

Most Unix syscalls have Windows equivalents, but behavior may differ on Windows\nrelative to Linux and macOS. For an example of the subtle ways in which it's\nsometimes impossible to replace Unix syscall semantics on Windows, see Node\nissue 4760.

\n\n\n", "type": "misc", "displayName": "Syscalls and man pages" } ] }, { "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 information about\ndifferent options and ways to run scripts with Node.js.

\n

Example

\n

An example of a web server written with Node.js which responds with\n'Hello World!':

\n

Commands displayed in this document are shown starting with $ or >\nto replicate how they would appear in a user's terminal.\nDo not include the $ and > character they are there to\nindicate the start of each command.

\n

There are many tutorials and examples that follow this\nconvention: $ or > for commands run as a regular user, and #\nfor commands that should be executed as an administrator.

\n

Lines that don’t start with $ or > character are typically showing\nthe output of the previous command.

\n

Firstly, make sure to have downloaded and installed Node.js.\nSee this guide for further install information.

\n

Now, create an empty project folder called projects, navigate into it:\nProject folder can be named base on user's current project title but\nthis example will use projects as the project folder.

\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\n folder and call it hello-world.js.

\n

In Node.js it is considered good style to use\nhyphens (-) or underscores (_) to separate\n multiple words in filenames.

\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 enter the following command:

\n
$ node hello-world.js\n
\n

An output like this should appear in the terminal to indicate Node.js\nserver is running:

\n
 Server running at http://127.0.0.1:3000/\n `\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.

\n

Many of the examples in the documentation can be run similarly.

\n\n\n" }, { "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 your terminal, run man node.

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

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

\n

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

\n

node --v8-options

\n

Execute without arguments to start the REPL.

\n

For more info about node debug, please see the debugger documentation.

\n", "type": "misc", "displayName": "Synopsis" }, { "textRaw": "Options", "name": "options", "modules": [ { "textRaw": "`-v`, `--version`", "name": "`-v`,_`--version`", "meta": { "added": [ "v0.1.3" ] }, "desc": "

Print node's version.

\n", "type": "module", "displayName": "`-v`, `--version`" }, { "textRaw": "`-h`, `--help`", "name": "`-h`,_`--help`", "meta": { "added": [ "v0.1.3" ] }, "desc": "

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

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

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

\n

Note: On Windows, using cmd.exe a single quote will not work correctly\nbecause it only recognizes double " for quoting. In Powershell or\nGit bash, both ' and " are usable.

\n", "type": "module", "displayName": "`-e`, `--eval \"script\"`" }, { "textRaw": "`-p`, `--print \"script\"`", "name": "`-p`,_`--print_\"script\"`", "meta": { "added": [ "v0.6.4" ] }, "desc": "

Identical to -e but prints the result.

\n", "type": "module", "displayName": "`-p`, `--print \"script\"`" }, { "textRaw": "`-c`, `--check`", "name": "`-c`,_`--check`", "meta": { "added": [ "v5.0.0" ] }, "desc": "

Syntax check the script without executing.

\n", "type": "module", "displayName": "`-c`, `--check`" }, { "textRaw": "`-i`, `--interactive`", "name": "`-i`,_`--interactive`", "meta": { "added": [ "v0.7.7" ] }, "desc": "

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

\n", "type": "module", "displayName": "`-i`, `--interactive`" }, { "textRaw": "`-r`, `--require module`", "name": "`-r`,_`--require_module`", "meta": { "added": [ "v1.6.0" ] }, "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", "type": "module", "displayName": "`-r`, `--require module`" }, { "textRaw": "`--no-deprecation`", "name": "`--no-deprecation`", "meta": { "added": [ "v0.8.0" ] }, "desc": "

Silence deprecation warnings.

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

Print stack traces for deprecations.

\n", "type": "module", "displayName": "`--trace-deprecation`" }, { "textRaw": "`--throw-deprecation`", "name": "`--throw-deprecation`", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Throw errors for deprecations.

\n", "type": "module", "displayName": "`--throw-deprecation`" }, { "textRaw": "`--no-warnings`", "name": "`--no-warnings`", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Silence all process warnings (including deprecations).

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

Print stack traces for process warnings (including deprecations).

\n", "type": "module", "displayName": "`--trace-warnings`" }, { "textRaw": "`--redirect-warnings=file`", "name": "`--redirect-warnings=file`", "meta": { "added": [ "v6.12.0" ] }, "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", "type": "module", "displayName": "`--redirect-warnings=file`" }, { "textRaw": "`--trace-sync-io`", "name": "`--trace-sync-io`", "meta": { "added": [ "v2.1.0" ] }, "desc": "

Prints a stack trace whenever synchronous I/O is detected after the first turn\nof the event loop.

\n", "type": "module", "displayName": "`--trace-sync-io`" }, { "textRaw": "`--zero-fill-buffers`", "name": "`--zero-fill-buffers`", "meta": { "added": [ "v6.0.0" ] }, "desc": "

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

\n", "type": "module", "displayName": "`--zero-fill-buffers`" }, { "textRaw": "`--preserve-symlinks`", "name": "`--preserve-symlinks`", "meta": { "added": [ "v6.3.0" ] }, "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", "type": "module", "displayName": "`--preserve-symlinks`" }, { "textRaw": "`--track-heap-objects`", "name": "`--track-heap-objects`", "meta": { "added": [ "v2.4.0" ] }, "desc": "

Track heap object allocations for heap snapshots.

\n", "type": "module", "displayName": "`--track-heap-objects`" }, { "textRaw": "`--prof-process`", "name": "`--prof-process`", "meta": { "added": [ "v6.0.0" ] }, "desc": "

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

\n", "type": "module", "displayName": "`--prof-process`" }, { "textRaw": "`--v8-options`", "name": "`--v8-options`", "meta": { "added": [ "v0.1.3" ] }, "desc": "

Print v8 command line options.

\n

Note: v8 options allow words to be separated by both dashes (-) or underscores\n(_).

\n

For example, --stack-trace-limit is equivalent to --stack_trace_limit.

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

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

\n", "type": "module", "displayName": "`--tls-cipher-list=list`" }, { "textRaw": "`--enable-fips`", "name": "`--enable-fips`", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with\n./configure --openssl-fips)

\n", "type": "module", "displayName": "`--enable-fips`" }, { "textRaw": "`--force-fips`", "name": "`--force-fips`", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)\n(Same requirements as --enable-fips)

\n", "type": "module", "displayName": "`--force-fips`" }, { "textRaw": "`--openssl-config=file`", "name": "`--openssl-config=file`", "meta": { "added": [ "v6.9.0" ] }, "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\n./configure --openssl-fips.

\n", "type": "module", "displayName": "`--openssl-config=file`" }, { "textRaw": "`--use-openssl-ca`, `--use-bundled-ca`", "name": "`--use-openssl-ca`,_`--use-bundled-ca`", "meta": { "added": [ "v6.11.0" ] }, "desc": "

Use OpenSSL's default CA store or use bundled Mozilla CA store as supplied by\ncurrent Node.js version. The default store is selectable at build-time.

\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

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

See SSL_CERT_DIR and SSL_CERT_FILE.

\n", "type": "module", "displayName": "`--use-openssl-ca`, `--use-bundled-ca`" }, { "textRaw": "`--icu-data-dir=file`", "name": "`--icu-data-dir=file`", "meta": { "added": [ "v0.11.15" ] }, "desc": "

Specify ICU data load path. (overrides NODE_ICU_DATA)

\n", "type": "module", "displayName": "`--icu-data-dir=file`" }, { "textRaw": "`--`", "name": "`--`", "meta": { "added": [ "v6.11.0" ] }, "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 will be used as a script filename.

\n", "type": "module", "displayName": "`--`" }, { "textRaw": "`--max-http-header-size=size`", "name": "`--max-http-header-size=size`", "meta": { "added": [ "v6.16.0" ] }, "desc": "

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

\n", "type": "module", "displayName": "`--max-http-header-size=size`" } ], "type": "misc", "displayName": "Options" }, { "textRaw": "Environment Variables", "name": "environment_variables", "modules": [ { "textRaw": "`NODE_DEBUG=module[,…]`", "name": "`node_debug=module[,…]`", "meta": { "added": [ "v0.1.32" ] }, "desc": "

','-separated list of core modules that should print debug information.

\n", "type": "module", "displayName": "`NODE_DEBUG=module[,…]`" }, { "textRaw": "`NODE_PATH=path[:…]`", "name": "`node_path=path[:…]`", "meta": { "added": [ "v0.1.32" ] }, "desc": "

':'-separated list of directories prefixed to the module search path.

\n

Note: on Windows, this is a ';'-separated list instead.

\n", "type": "module", "displayName": "`NODE_PATH=path[:…]`" }, { "textRaw": "`NODE_DISABLE_COLORS=1`", "name": "`node_disable_colors=1`", "meta": { "added": [ "v0.3.0" ] }, "desc": "

When set to 1 colors will not be used in the REPL.

\n", "type": "module", "displayName": "`NODE_DISABLE_COLORS=1`" }, { "textRaw": "`NODE_ICU_DATA=file`", "name": "`node_icu_data=file`", "meta": { "added": [ "v0.11.15" ] }, "desc": "

Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.

\n", "type": "module", "displayName": "`NODE_ICU_DATA=file`" }, { "textRaw": "`NODE_NO_WARNINGS=1`", "name": "`node_no_warnings=1`", "meta": { "added": [ "v6.11.0" ] }, "desc": "

When set to 1, process warnings are silenced.

\n", "type": "module", "displayName": "`NODE_NO_WARNINGS=1`" }, { "textRaw": "`NODE_OPTIONS=options...`", "name": "`node_options=options...`", "meta": { "added": [ "v6.12.0" ] }, "desc": "

options... are interpreted as if they had been specified on the command line\nbefore the actual command line (so they can be overriden). Node will exit with\nan error if an option that is not allowed in the environment is used, such as\n-p or a script file.

\n

Node options that are allowed are:

\n\n

V8 options that are allowed are:

\n\n", "type": "module", "displayName": "`NODE_OPTIONS=options...`" }, { "textRaw": "`NODE_REPL_HISTORY=file`", "name": "`node_repl_history=file`", "meta": { "added": [ "v3.0.0" ] }, "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.

\n", "type": "module", "displayName": "`NODE_REPL_HISTORY=file`" }, { "textRaw": "`NODE_TTY_UNSAFE_ASYNC=1`", "name": "`node_tty_unsafe_async=1`", "meta": { "added": [ "6.4.0" ] }, "desc": "

When set to 1, writes to stdout and stderr will be non-blocking and\nasynchronous when outputting to a TTY on platforms which support async stdio.\nSetting this will void any guarantee that stdio will not be interleaved or\ndropped at program exit. Use of this mode is not recommended.

\n", "type": "module", "displayName": "`NODE_TTY_UNSAFE_ASYNC=1`" }, { "textRaw": "`NODE_EXTRA_CA_CERTS=file`", "name": "`node_extra_ca_certs=file`", "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

Note that 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", "type": "module", "displayName": "`NODE_EXTRA_CA_CERTS=file`" }, { "textRaw": "`OPENSSL_CONF=file`", "name": "`openssl_conf=file`", "meta": { "added": [ "v6.11.0" ] }, "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\n--openssl-fips.

\n

If the --openssl-config command line option is used, the environment\nvariable is ignored.

\n", "type": "module", "displayName": "`OPENSSL_CONF=file`" }, { "textRaw": "`SSL_CERT_DIR=dir`", "name": "`ssl_cert_dir=dir`", "desc": "

If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.

\n

Note: Be aware that unless the child environment is explicitly set, this\nevironment variable will be inherited by any child processes, and if they use\nOpenSSL, it may cause them to trust the same CAs as node.

\n", "type": "module", "displayName": "`SSL_CERT_DIR=dir`" }, { "textRaw": "`SSL_CERT_FILE=file`", "name": "`ssl_cert_file=file`", "desc": "

If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file\ncontaining trusted certificates.

\n

Note: Be aware that unless the child environment is explicitly set, this\nevironment variable will be inherited by any child processes, and if they use\nOpenSSL, it may cause them to trust the same CAs as node.

\n", "type": "module", "displayName": "`SSL_CERT_FILE=file`" }, { "textRaw": "`NODE_REDIRECT_WARNINGS=file`", "name": "`node_redirect_warnings=file`", "meta": { "added": [ "v6.12.0" ] }, "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.

\n\n\n", "type": "module", "displayName": "`NODE_REDIRECT_WARNINGS=file`" } ], "type": "misc", "displayName": "Environment Variables" } ] }, { "textRaw": "Debugger", "name": "Debugger", "introduced_in": "v0.9.12", "stability": 2, "stabilityText": "Stable", "type": "misc", "desc": "

Node.js includes an out-of-process debugging utility accessible via a\nTCP-based protocol and built-in debugging client. To use it, start Node.js\nwith the debug argument followed by the path to the script to debug; a prompt\nwill be displayed indicating successful launch of the debugger:

\n
$ node debug myscript.js\n< Debugger listening on [::]:5858\nconnecting to 127.0.0.1:5858 ... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n> 1 global.x = 5;\n  2 setTimeout(() => {\n  3   debugger;\ndebug>\n
\n

Node.js's 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 debug myscript.js\n< Debugger listening on [::]:5858\nconnecting to 127.0.0.1:5858 ... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n> 1 global.x = 5;\n  2 setTimeout(() => {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 global.x = 5;\n  2 setTimeout(() => {\n> 3   debugger;\n  4   console.log('world');\n  5 }, 1000);\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:4\n  2 setTimeout(() => {\n  3   debugger;\n> 4   console.log('world');\n  5 }, 1000);\n  6 console.log('hello');\ndebug> repl\nPress Ctrl + C to leave debug repl\n> x\n5\n> 2 + 2\n4\ndebug> next\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n< world\n  3   debugger;\n  4   console.log('world');\n> 5 }, 1000);\n  6 console.log('hello');\n  7\ndebug> quit\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.

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

\n", "type": "misc", "displayName": "Watchers" }, { "textRaw": "Command reference", "name": "command_reference", "modules": [ { "textRaw": "Stepping", "name": "Stepping", "desc": "\n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Breakpoints", "name": "breakpoints", "desc": "\n

It is also possible to set a breakpoint in a file (module) that\nis not loaded yet:

\n
$ node debug test/fixtures/break-in-module/main.js\n< Debugger listening on [::]:5858\nconnecting to 127.0.0.1:5858 ... ok\nbreak in test/fixtures/break-in-module/main.js:1\n> 1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> setBreakpoint('mod.js', 2)\nWarning: script 'mod.js' was not loaded yet.\n> 1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\n  4 debugger;\n  5\n  6 });\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:2\n  1 exports.hello = function() {\n> 2   return 'hello from module';\n  3 };\n  4\ndebug>\n
\n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Execution control", "name": "Execution control", "desc": "\n", "type": "module", "displayName": "Various" }, { "textRaw": "Various", "name": "various", "desc": "\n", "type": "module", "displayName": "Various" } ], "type": "misc", "displayName": "Command reference" }, { "textRaw": "Advanced Usage", "name": "advanced_usage", "desc": "

An alternative way of enabling and accessing the debugger is to start\nNode.js with the --debug command-line flag or by signaling an existing\nNode.js process with SIGUSR1.

\n

Once a process has been set in debug mode this way, it can be inspected\nusing the Node.js debugger by either connecting to the pid of the running\nprocess or via URI reference to the listening debugger:

\n\n", "type": "misc", "displayName": "Advanced Usage" } ], "properties": [ { "textRaw": "V8 Inspector Integration for Node.js", "name": "js", "desc": "

NOTE: This is an experimental feature.

\n

V8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling.

\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, provide the --debug-brk\nflag in addition to --inspect.

\n
$ node --inspect index.js\nDebugger listening on port 9229.\nWarning: This is an experimental feature and could change at any time.\nTo start debugging, open the following URL in Chrome:\n    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/3a6d0a9e-0707-48f8-a7c6-48f157b67ab5\n
\n

(In the example above, the UUID 3a6d0a9e-0707-48f8-a7c6-48f157b67ab5\nat the end of the URL is generated on the fly, it varies in different\ndebugging sessions.)

\n\n\n" } ] }, { "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

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.

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

\n
// Throws with a ReferenceError because z is undefined\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\n
  const fs = require('fs');\n  fs.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

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\nunhandled exception and crash unless either: The domain module is used\nappropriately or a handler has been registered for the\nprocess.on('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.

\n", "miscs": [ { "textRaw": "Node.js style callbacks", "name": "Node.js style callbacks", "type": "misc", "desc": "

Most asynchronous methods exposed by the Node.js core API follow an idiomatic\npattern referred to as a "Node.js style callback". With this pattern, a\ncallback function is passed to the method as an argument. When the operation\neither completes or an error is raised, the callback function is called with\nthe Error 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 nodeStyleCallback(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', nodeStyleCallback);\nfs.readFile('/some/file/that/does-exist', nodeStyleCallback);\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 a Node.js style 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 (err) { } block will have\nalready exited. Throwing an error inside the callback can crash the Node.js\nprocess in most cases. If domains are enabled, or a handler has been\nregistered with process.on('uncaughtException'), such errors can be\nintercepted.

\n" } ] }, { "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.

\n" }, { "textRaw": "System Errors", "name": "system_errors", "desc": "

System errors are generated when exceptions occur within the program's\nruntime environment. Typically, these are operational errors that occur\nwhen an application violates an operating system constraint such as attempting\nto read a file that does not exist or when the user does not have sufficient\npermissions.

\n

System errors are typically generated at the syscall level: an exhaustive list\nof error codes and their meanings is available by running man 2 intro or\nman 3 errno on most Unices; or online.

\n

In Node.js, system errors are represented as augmented Error objects with\nadded properties.

\n", "classes": [ { "textRaw": "Class: System Error", "type": "class", "name": "System", "properties": [ { "textRaw": "`code` {string} ", "type": "string", "name": "code", "desc": "

The error.code property is a string representing the error code, which is always\nE followed by a sequence of capital letters.

\n" }, { "textRaw": "`errno` {string|number} ", "type": "string|number", "name": "errno", "desc": "

The error.errno property is a number or a string.\nThe number is a negative value which corresponds to the error code defined in\nlibuv Error handling. See uv-errno.h header file (deps/uv/include/uv-errno.h in\nthe Node.js source tree) for details.\nIn case of a string, it is the same as error.code.

\n" }, { "textRaw": "`syscall` {string} ", "type": "string", "name": "syscall", "desc": "

The error.syscall property is a string describing the syscall that failed.

\n" }, { "textRaw": "`path` {string} ", "type": "string", "name": "path", "desc": "

When present (e.g. in fs or child_process), the error.path property is a string\ncontaining a relevant invalid pathname.

\n" }, { "textRaw": "`address` {string} ", "type": "string", "name": "address", "desc": "

When present (e.g. in net or dgram), the error.address property is a string\ndescribing the address to which the connection failed.

\n" }, { "textRaw": "`port` {number} ", "type": "number", "name": "port", "desc": "

When present (e.g. in net or dgram), the error.port property is a number representing\nthe connection's port that is not available.

\n" } ] } ], "modules": [ { "textRaw": "Common System Errors", "name": "common_system_errors", "desc": "

This list is not exhaustive, but enumerates many of the common system\nerrors encountered when writing a Node.js program. An exhaustive list may be\nfound here.

\n\n\n\n", "type": "module", "displayName": "Common System Errors" } ], "type": "misc", "displayName": "System Errors" } ], "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.

\n", "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", "optional": true } ] }, { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ], "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, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().

\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 an end 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
\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.

\n" }, { "textRaw": "`message` {string} ", "type": "string", "name": "message", "desc": "

The error.message property is the string description of the error as set by calling new Error(message).\nThe message passed to the constructor will also appear in the first line of\nthe stack trace of the Error, however changing this property after the\nError object is created may not change the first line of the stack trace\n(for example, when error.stack is read before this property is changed).

\n
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
\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

For example:

\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

It is important to note that frames are only generated for JavaScript\nfunctions. If, for example, execution synchronously passes through a C++ addon\nfunction called cheetahify, which itself calls a JavaScript function, the\nframe representing the cheetahify call will not be present in the stack\ntraces:

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

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.

\n

System-level errors are generated as augmented Error instances, which are\ndetailed here.

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

\n" }, { "params": [ { "name": "message" } ], "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.

\n" } ] }, { "textRaw": "Class: RangeError", "type": "class", "name": "RangeError", "desc": "

A subclass of Error that indicates that a provided argument was not within the\nset or range of acceptable values for a function; whether that is a numeric\nrange, or outside the set of options for a given function parameter.

\n

For example:

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

\n" }, { "textRaw": "Class: ReferenceError", "type": "class", "name": "ReferenceError", "desc": "

A subclass of Error that indicates that an attempt is being made to access a\nvariable that is not defined. Such errors commonly indicate typos in code, or\nan otherwise broken program.

\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 should always be considered a bug in the code\nor its dependencies.

\n" }, { "textRaw": "Class: SyntaxError", "type": "class", "name": "SyntaxError", "desc": "

A subclass of Error that indicates that a program is not valid JavaScript.\nThese errors may only be generated and propagated as a result of code\nevaluation. Code evaluation may happen as a result of eval, Function,\nrequire, or vm. These errors are almost always indicative of a broken\nprogram.

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

\n" }, { "textRaw": "Class: TypeError", "type": "class", "name": "TypeError", "desc": "

A subclass of Error that indicates that a provided argument is not an\nallowable type. For example, passing a function to a parameter which expects a\nstring would be considered 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.

\n" } ] }, { "textRaw": "Global Objects", "name": "Global Objects", "introduced_in": "v0.10.0", "type": "misc", "desc": "

These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.

\n

The objects listed here are specific to Node.js. There are a number of\nbuilt-in objects that are part of the JavaScript language itself, which are\nalso globally accessible.

\n", "globals": [ { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "meta": { "added": [ "v0.1.103" ] }, "desc": "\n

Used to handle binary data. See the buffer section.

\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "

clearImmediate is described in the timers section.

\n" }, { "textRaw": "clearInterval(intervalObject)", "type": "global", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ] }, "desc": "

clearInterval is described in the timers section.

\n" }, { "textRaw": "clearTimeout(timeoutObject)", "type": "global", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ] }, "desc": "

clearTimeout is described in the timers section.

\n" }, { "textRaw": "console", "name": "console", "meta": { "added": [ "v0.1.100" ] }, "type": "global", "desc": "\n

Used to print to stdout and stderr. See the console section.

\n" }, { "textRaw": "global", "name": "global", "meta": { "added": [ "v0.1.27" ] }, "type": "global", "desc": "\n

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node.js this is different. The top-level scope is not the global\nscope; var something inside an Node.js module will be local to that module.

\n" }, { "textRaw": "process", "name": "process", "meta": { "added": [ "v0.1.7" ] }, "type": "global", "desc": "\n

The process object. See the process object section.

\n" }, { "textRaw": "setImmediate(callback[, ...args])", "type": "global", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "

setImmediate is described in the timers section.

\n" }, { "textRaw": "setInterval(callback, delay[, ...args])", "type": "global", "name": "setInterval", "meta": { "added": [ "v0.0.1" ] }, "desc": "

setInterval is described in the timers section.

\n" }, { "textRaw": "setTimeout(callback, delay[, ...args])", "type": "global", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ] }, "desc": "

setTimeout is described in the timers section.

\n\n\n" }, { "textRaw": "Process", "name": "Process", "introduced_in": "v0.10.0", "type": "global", "desc": "

The process object is a global that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require().

\n", "modules": [ { "textRaw": "Process Events", "name": "process_events", "desc": "

The process object is an instance of EventEmitter.

\n", "events": [ { "textRaw": "Event: 'beforeExit'", "type": "event", "name": "beforeExit", "meta": { "added": [ "v0.11.12" ] }, "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", "params": [] }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.7" ] }, "desc": "

The 'exit' event is emitted when the Node.js process is about to exit as a\nresult of either:

\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, as the only argument.

\n

For example:

\n
process.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
process.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.10" ] }, "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 listener callback is invoked with the following arguments:

\n\n", "params": [] }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "meta": { "added": [ "v1.4.1" ] }, "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 listener callback is invoked with a reference to the rejected Promise as\nthe only argument.

\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

For example:

\n
const unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, p) => {\n  unhandledRejections.set(p, reason);\n});\nprocess.on('rejectionHandled', (p) => {\n  unhandledRejections.delete(p);\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).

\n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "meta": { "added": [ "v0.1.18" ] }, "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.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior.

\n

The listener function is called with the Error object passed as the only\nargument.

\n

For example:

\n
process.on('uncaughtException', (err) => {\n  fs.writeSync(1, `Caught exception: ${err}`);\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", "modules": [ { "textRaw": "Warning: Using `'uncaughtException'` correctly", "name": "warning:_using_`'uncaughtexception'`_correctly", "desc": "

Note that '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 of the power cord when upgrading a computer — nine out of ten\ntimes nothing happens - but the 10th 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 uncaughtException\nis emitted or not, an external monitor should be employed in a separate process\nto detect application failures and recover or restart as needed.

\n", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ], "params": [] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "meta": { "added": [ "v1.4.1" ] }, "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

The listener function is called with the following arguments:

\n\n

For example:

\n
process.on('unhandledRejection', (reason, p) => {\n  console.log('Unhandled Rejection at: Promise', p, '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
function 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. Alternatively, the 'rejectionHandled' event may be used.

\n", "params": [] }, { "textRaw": "Event: 'warning'", "type": "event", "name": "warning", "meta": { "added": [ "v6.0.0" ] }, "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

The listener function is called with a single warning argument whose value is\nan Error object. There are three key properties that describe the warning:

\n\n
process.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) Warning: Possible EventEmitter memory leak detected. 2 foo\n... 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> var 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", "modules": [ { "textRaw": "Emitting custom warnings", "name": "emitting_custom_warnings", "desc": "

The process.emitWarning() method can be used to issue\ncustom or application specific warnings.

\n
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Prints: (node 12345) Warning: Something happened!\n\n// Emit a warning using an object...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Prints: (node 12345) CustomWarning: Something happened!\n\n// Emit a warning using a custom Error object...\nclass CustomWarning extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomWarning';\n    Error.captureStackTrace(this, CustomWarning);\n  }\n}\nconst myWarning = new CustomWarning('Something happened!');\nprocess.emitWarning(myWarning);\n// Prints: (node 12345) CustomWarning: Something happened!\n
\n", "type": "module", "displayName": "Emitting custom warnings" }, { "textRaw": "Emitting custom deprecation warnings", "name": "emitting_custom_deprecation_warnings", "desc": "

Custom deprecation warnings can be emitted by setting the name of a custom\nwarning to DeprecationWarning. For instance:

\n
process.emitWarning('This API is deprecated', 'DeprecationWarning');\n
\n

Or,

\n
const err = new Error('This API is deprecated');\nerr.name = 'DeprecationWarning';\nprocess.emitWarning(err);\n
\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\nDeprecationWarning.

\n", "type": "module", "displayName": "Emitting custom deprecation warnings" } ], "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "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\nSIGINT, SIGHUP, etc.

\n

The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).

\n

For example:

\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

Note: An easy way to send the SIGINT signal is with <Ctrl>-C in most\nterminal programs.

\n

It is important to take note of the following:

\n\n

Note: Windows does not support sending signals, but Node.js offers some\nemulation with process.kill(), and subprocess.kill(). Sending\nsignal 0 can be used to test for the existence of a process. Sending SIGINT,\nSIGTERM, and SIGKILL cause the unconditional termination of the target\nprocess.

\n", "params": [] } ], "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\n\n", "type": "module", "displayName": "Exit Codes" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.7.0" ] }, "desc": "

The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "meta": { "added": [ "v0.1.17" ] }, "signatures": [ { "params": [ { "textRaw": "`directory` {string} ", "name": "directory", "type": "string" } ] }, { "params": [ { "name": "directory" } ] } ], "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
console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
\n" }, { "textRaw": "process.cpuUsage([previousValue])", "type": "method", "name": "cpuUsage", "meta": { "added": [ "v6.1.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "options": [ { "textRaw": "`user` {integer} ", "name": "user", "type": "integer" }, { "textRaw": "`system` {integer} ", "name": "system", "type": "integer" } ], "name": "return", "type": "Object" }, "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()`", "optional": true } ] }, { "params": [ { "name": "previousValue", "optional": true } ] } ], "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
const startUsage = process.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(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
\n" }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "meta": { "added": [ "v0.1.8" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The process.cwd() method returns the current working directory of the Node.js\nprocess.

\n
console.log(`Current directory: ${process.cwd()}`);\n
\n" }, { "textRaw": "process.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ] }, "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 that same as calling the parent\nprocess's ChildProcess.disconnect().

\n

If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.emitWarning(warning[, name][, ctor])", "type": "method", "name": "emitWarning", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string | Error} The warning to emit. ", "name": "warning", "type": "string | Error", "desc": "The warning to emit." }, { "textRaw": "`name` {string} When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`. ", "name": "name", "type": "string", "desc": "When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`.", "optional": true }, { "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", "desc": "When `warning` is a String, `ctor` is an optional function used to limit the generated stack trace. Default `process.emitWarning`", "optional": true } ] }, { "params": [ { "name": "warning" }, { "name": "name", "optional": true }, { "name": "ctor", "optional": true } ] } ], "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\nprocess.on('warning') event.

\n
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n
// Emit a warning using a string and a name...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) 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\nprocess.on('warning') event.

\n
process.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.stack);\n});\n
\n

If warning is passed as an Error object, it will be passed through to the\nprocess.on('warning') event handler unmodified (and the optional name\nand ctor arguments will be ignored):

\n
// Emit a warning using an Error object...\nconst myWarning = new Error('Warning! Something happened!');\nmyWarning.name = 'CustomWarning';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) CustomWarning: Warning! Something Happened!\n
\n

A TypeError is thrown if warning is anything other than a string or Error\nobject.

\n

Note that 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 name is\nDeprecationWarning:

\n\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
let warned = false;\nfunction emitMyWarning() {\n  if (!warned) {\n    process.emitWarning('Only warn once!');\n    warned = true;\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
\n", "type": "module", "displayName": "Avoiding duplicate warnings" } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "meta": { "added": [ "v0.1.13" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {integer} The exit code. Defaults to `0`. ", "name": "code", "type": "integer", "desc": "The exit code. Defaults to `0`.", "optional": true } ] }, { "params": [ { "name": "code", "optional": true } ] } ], "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
process.exit(1);\n
\n

The shell that executed Node.js should see the exit code as 1.

\n

It is important to note that calling process.exit() will force the process to\nexit as quickly as possible even if there are still asynchronous operations\npending that have not yet completed fully, including I/O operations to\nprocess.stdout and process.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
// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.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
// 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" }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)

\n
if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows\nor Android)

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)

\n
if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)

\n
if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [] }, { "params": [] } ], "desc": "

The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)

\n
if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.hrtime([time])", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ] }, "desc": "

The process.hrtime() method returns the current high-resolution real time in a\n[seconds, nanoseconds] tuple Array. time is an optional parameter that must\nbe the result of a previous process.hrtime() call (and therefore, a real time\nin a [seconds, nanoseconds] tuple Array containing a previous time) to diff\nwith the current time. 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

Passing in the result of a previous call to process.hrtime() is useful for\ncalculating an amount of time passed between calls:

\n
const time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * 1e9 + diff[1]} nanoseconds`);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);\n
\n

Constructing an array by some method other than calling process.hrtime() and\npassing the result to process.hrtime() will result in undefined behavior.

\n", "signatures": [ { "params": [ { "name": "time", "optional": true } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "meta": { "added": [ "v0.9.4" ] }, "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": "`extra_group` {string|number} A group name or numeric identifier. ", "name": "extra_group", "type": "string|number", "desc": "A group name or numeric identifier." } ] }, { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ], "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

Note that care must be taken when dropping privileges. Example:

\n
console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ] }, "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. Defaults to `'SIGTERM'`. ", "name": "signal", "type": "string|number", "desc": "The signal to send, either as a string or number. Defaults to `'SIGTERM'`.", "optional": true } ] }, { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ], "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

Note:Even though the name of this function is process.kill(), it is really\njust a signal sender, like the kill system call. The signal sent may do\nsomething other than kill the target process.

\n

For example:

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

Note: When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger, see Signal Events.

\n" }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "meta": { "added": [ "v0.1.16" ] }, "signatures": [ { "return": { "textRaw": "Returns: {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" } ], "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.memoryUsage() method returns an object describing the memory usage\nof the Node.js process measured in bytes.

\n

For example, the code:

\n
console.log(process.memoryUsage());\n
\n

Will generate:

\n\n
{\n  rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472,\n  external: 49879\n}\n
\n

heapTotal and heapUsed refer to V8's memory usage.\nexternal refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8. rss, Resident Set Size, is the amount of space\noccupied in the main memory device (that is a subset of the total allocated\nmemory) for the process, which includes the heap, code segment and stack.

\n

The heap is where objects, strings and closures are stored. Variables are\nstored in the stack and the actual JavaScript code resides in the\ncode segment.

\n" }, { "textRaw": "process.nextTick(callback[, ...args])", "type": "method", "name": "nextTick", "meta": { "added": [ "v0.1.26" ] }, "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`", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "...args", "optional": true } ] } ], "desc": "

The process.nextTick() method adds the callback to the "next tick queue".\nOnce the current turn of the event loop turn runs to completion, all callbacks\ncurrently in the next tick queue will be called.

\n

This is not a simple alias to setTimeout(fn, 0). It is much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.

\n
console.log('start');\nprocess.nextTick(() => {\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
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.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
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n

Note: the next tick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true); loop.

\n" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "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

Note: This function uses JSON.stringify() internally to serialize the\nmessage.*

\n" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A group name or ID ", "name": "id", "type": "string|number", "desc": "A group name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A user name or ID ", "name": "id", "type": "string|number", "desc": "A user name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} The group name or ID ", "name": "id", "type": "string|number", "desc": "The group name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`groups` {Array} ", "name": "groups", "type": "Array" } ] }, { "params": [ { "name": "groups" } ] } ], "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 process\nto have root or the CAP_SETGID capability.

\n

The groups array can contain numeric group IDs, group names or both.

\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ] }, "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ] }, "signatures": [ { "params": [ { "textRaw": "`mask` {number} ", "name": "mask", "type": "number", "optional": true } ] }, { "params": [ { "name": "mask", "optional": true } ] } ], "desc": "

The process.umask() method sets or returns the Node.js process's file mode\ncreation mask. Child processes inherit the mask from the parent process. Invoked\nwithout an argument, the current mask is returned, otherwise the umask is set to\nthe argument value and the previous mask is returned.

\n
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n" }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {number} ", "name": "return", "type": "number" }, "params": [] }, { "params": [] } ], "desc": "

The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

\n

Note: the return value includes fractions of a second. Use Math.floor()\nto get whole seconds.

\n" } ], "properties": [ { "textRaw": "`arch` {string} ", "type": "string", "name": "arch", "meta": { "added": [ "v0.5.0" ] }, "desc": "

The process.arch property returns a string identifying the operating system CPU\narchitecture for which the Node.js binary was compiled.

\n

The current possible values are: 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n
console.log(`This processor architecture is ${process.arch}`);\n
\n" }, { "textRaw": "`argv` {Array} ", "type": "Array", "name": "argv", "meta": { "added": [ "v0.1.27" ] }, "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 of\nargv[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
// print process.argv\nprocess.argv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
\n

Launching the Node.js process as:

\n
$ node process-2.js one two=three four\n
\n

Would generate the output:

\n
0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n
\n" }, { "textRaw": "`argv0` {string} ", "type": "string", "name": "argv0", "meta": { "added": [ "6.4.0" ] }, "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
\n" }, { "textRaw": "`config` {Object} ", "type": "Object", "name": "config", "meta": { "added": [ "v0.7.7" ] }, "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     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: 'true'\n   }\n}\n
\n

Note: The process.config property is not read-only and there are\nexisting modules in the ecosystem that are known to extend, modify, or entirely\nreplace the value of process.config.

\n" }, { "textRaw": "`connected` {boolean} ", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ] }, "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().

\n" }, { "textRaw": "`env` {Object} ", "type": "Object", "name": "env", "meta": { "added": [ "v0.1.27" ] }, "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. In other words, the following example\nwould not work:

\n
$ node -e 'process.env.foo = "bar"' && echo $foo\n
\n

While the following will:

\n
process.env.foo = 'bar';\nconsole.log(process.env.foo);\n
\n

Assigning a property on process.env will implicitly convert the value\nto a string.

\n

Example:

\n
process.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
\n

Use delete to delete a property from process.env.

\n

Example:

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\n

On Windows operating systems, environment variables are case-insensitive.

\n

Example:

\n
process.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
\n" }, { "textRaw": "`execArgv` {Object} ", "type": "Object", "name": "execArgv", "meta": { "added": [ "v0.7.7" ] }, "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

For example:

\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" }, { "textRaw": "`execPath` {string} ", "type": "string", "name": "execPath", "meta": { "added": [ "v0.1.100" ] }, "desc": "

The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process.

\n

For example:

\n\n
'/usr/local/bin/node'\n
\n" }, { "textRaw": "`exitCode` {integer} ", "type": "integer", "name": "exitCode", "meta": { "added": [ "v0.11.8" ] }, "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.

\n" }, { "textRaw": "process.mainModule", "name": "mainModule", "meta": { "added": [ "v0.1.17" ] }, "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.

\n" }, { "textRaw": "`noDeprecation` {boolean} ", "type": "boolean", "name": "noDeprecation", "meta": { "added": [ "v0.8.0" ] }, "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.

\n" }, { "textRaw": "`pid` {integer} ", "type": "integer", "name": "pid", "meta": { "added": [ "v0.1.15" ] }, "desc": "

The process.pid property returns the PID of the process.

\n
console.log(`This process is pid ${process.pid}`);\n
\n" }, { "textRaw": "`platform` {string} ", "type": "string", "name": "platform", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running. For instance\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

\n
console.log(`This platform is ${process.platform}`);\n
\n" }, { "textRaw": "`ppid` {integer} ", "type": "integer", "name": "ppid", "meta": { "added": [ "v6.13.0" ] }, "desc": "

The process.ppid property returns the PID of the current parent process.

\n
console.log(`The parent process is pid ${process.ppid}`);\n
\n" }, { "textRaw": "process.release", "name": "release", "meta": { "added": [ "v3.0.0" ] }, "desc": "

The process.release property returns an Object containing metadata related to\nthe current release, including URLs for the source tarball and headers-only\ntarball.

\n

process.release contains the following properties:

\n\n

For example:

\n\n
{\n  name: 'node',\n  lts: 'Argon',\n  sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.4.5/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.

\n" }, { "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

Note: process.stderr differs from other Node.js streams in important ways,\nsee note on process I/O for more information.

\n" }, { "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 example:

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  const chunk = process.stdin.read();\n  if (chunk !== null) {\n    process.stdout.write(`data: ${chunk}`);\n  }\n});\n\nprocess.stdin.on('end', () => {\n  process.stdout.write('end');\n});\n
\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

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

\n" }, { "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
process.stdin.pipe(process.stdout);\n
\n

Note: process.stdout differs from other Node.js streams in important ways,\nsee note on process I/O for more information.

\n", "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. They cannot be closed (end() will throw).
  4. \n
  5. They will never emit the 'finish' event.
  6. \n
  7. Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:\n
  8. \n
\n

These behaviors are partly for historical reasons, as changing them would\ncreate backwards 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.

\n", "type": "module", "displayName": "A note on process I/O" } ] }, { "textRaw": "`throwDeprecation` {boolean} ", "type": "boolean", "name": "throwDeprecation", "meta": { "added": [ "v0.9.12" ] }, "desc": "

The process.throwDeprecation property indicates whether the\n--throw-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.

\n" }, { "textRaw": "`title` {string} ", "type": "string", "name": "title", "meta": { "added": [ "v0.1.104" ] }, "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

Note: When a new value is assigned, different platforms will impose different\nmaximum length restrictions on the title. Usually such restrictions are quite\nlimited. For instance, on Linux and macOS, process.title is limited to the\nsize of the binary name plus the length of the command line arguments because\nsetting the process.title overwrites the argv memory of the process.\nNode.js v0.8 allowed for longer process title strings by also overwriting the\nenviron memory but that was potentially insecure and confusing in some\n(rather obscure) cases.

\n" }, { "textRaw": "`traceDeprecation` {boolean} ", "type": "boolean", "name": "traceDeprecation", "meta": { "added": [ "v0.8.0" ] }, "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.

\n" }, { "textRaw": "`version` {string} ", "type": "string", "name": "version", "meta": { "added": [ "v0.1.3" ] }, "desc": "

The process.version property returns the Node.js version string.

\n
console.log(`Version: ${process.version}`);\n
\n" }, { "textRaw": "`versions` {Object} ", "type": "Object", "name": "versions", "meta": { "added": [ "v0.2.0" ] }, "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
console.log(process.versions);\n
\n

Will generate an object similar to:

\n\n
{\n  http_parser: '2.3.0',\n  node: '1.1.1',\n  v8: '4.1.0.14',\n  uv: '1.3.0',\n  zlib: '1.2.8',\n  ares: '1.10.0-DEV',\n  modules: '43',\n  icu: '55.1',\n  openssl: '1.0.1k'\n}\n
\n" } ] } ], "vars": [ { "textRaw": "\\_\\_dirname", "name": "\\_\\_dirname", "meta": { "added": [ "v0.1.27" ] }, "type": "var", "desc": "\n

The directory name of the current module. This the same as the\npath.dirname() of the __filename.

\n

__dirname is not actually a global but rather local to each module.

\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
\n" }, { "textRaw": "\\_\\_filename", "name": "\\_\\_filename", "meta": { "added": [ "v0.0.1" ] }, "type": "var", "desc": "\n

The file name of the current module. This is the resolved absolute path of the\ncurrent module file.

\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

__filename is not actually a global but rather local to each 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

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.

\n" }, { "textRaw": "exports", "name": "exports", "meta": { "added": [ "v0.1.12" ] }, "type": "var", "desc": "

A reference to the module.exports that is shorter to type.\nSee module system documentation for details on when to use exports and\nwhen to use module.exports.

\n

exports is not actually a global but rather local to each module.

\n

See the module system documentation for more information.

\n" }, { "textRaw": "module", "name": "module", "meta": { "added": [ "v0.1.16" ] }, "type": "var", "desc": "\n

A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().

\n

module is not actually a global but rather local to each module.

\n

See the module system documentation for more information.

\n" }, { "textRaw": "require()", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ] }, "desc": "\n

To require modules. See the Modules section. require is not actually a\nglobal but rather local to each module.

\n", "properties": [ { "textRaw": "`cache` {Object} ", "type": "Object", "name": "cache", "meta": { "added": [ "v0.3.0" ] }, "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. Note that\nthis does not apply to native addons, for which reloading will result in an\nError.

\n" }, { "textRaw": "`extensions` {Object} ", "type": "Object", "name": "extensions", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.10.6" ] }, "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\nnon-JavaScript modules into Node.js by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node.js program, or compiling them to\nJavaScript ahead of time.

\n

Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.

\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.0" ] }, "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", "signatures": [ { "params": [] } ] } ] } ] } ], "modules": [ { "textRaw": "C++ Addons", "name": "c++_addons", "introduced_in": "v0.10.0", "desc": "

Node.js Addons are dynamically-linked shared objects, written in C++, that\ncan be loaded into Node.js using the require() function, and used\njust as if they were an ordinary Node.js module. They are used primarily to\nprovide an interface between JavaScript running in Node.js and C/C++ libraries.

\n

At the moment, the method for implementing Addons is rather complicated,\ninvolving knowledge of several components and APIs :

\n\n

All of the following examples are available for download and may\nbe used as a starting-point for your own Addon.

\n", "modules": [ { "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(isolate, "world"));\n}\n\nvoid init(Local<Object> exports) {\n  NODE_SET_METHOD(exports, "hello", Method);\n}\n\nNODE_MODULE(addon, init)\n\n}  // namespace demo\n
\n

Note that all Node.js Addons must export an initialization function following\nthe pattern:

\n
void Initialize(Local<Object> exports);\nNODE_MODULE(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 init and the\nAddon module name is addon.

\n", "modules": [ { "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 your 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

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

Please see the examples below for further information or\nhttps://github.com/arturadib/node-qt for an example in production.

\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

Note that while the bindings package implementation is more sophisticated\nin how it locates Addon modules, it is essentially using a try-catch pattern\nsimilar to:

\n
try {\n  return require('./build/Release/addon.node');\n} catch (err) {\n  return require('./build/Debug/addon.node');\n}\n
\n", "type": "module", "displayName": "Building" }, { "textRaw": "Linking to Node.js' own dependencies", "name": "linking_to_node.js'_own_dependencies", "desc": "

Node.js uses a number of statically linked libraries such as V8, libuv and\nOpenSSL. All Addons are required to link to V8 and may link to any of the\nother dependencies as well. Typically, this is as simple as including\nthe appropriate #include <...> statements (e.g. #include <v8.h>) and\nnode-gyp will locate the appropriate headers automatically. However, there\nare a few caveats to be aware of:

\n\n", "type": "module", "displayName": "Linking to Node.js' own dependencies" }, { "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.

\n", "type": "module", "displayName": "Loading Addons using require()" } ], "type": "module", "displayName": "Hello world" }, { "textRaw": "N-API", "name": "n-api", "stability": 1, "stabilityText": "Experimental", "desc": "

N-API is an API for building native Addons. It is independent from\nthe underlying JavaScript runtime (ex V8) and is maintained as part of\nNode.js itself. This API will be Application Binary Interface (ABI) stable\nacross version 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 N-API are used.

\n

The functions available and how to use them are documented in the\nsection titled C/C++ Addons - N-API.

\n", "type": "module", "displayName": "N-API" }, { "textRaw": "Addon examples", "name": "addon_examples", "desc": "

Following are some example Addons intended to help developers get started. The\nexamples make use of 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. For example:

\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
\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, "Wrong number of arguments")));\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, "Wrong arguments")));\n    return;\n  }\n\n  // Perform the operation\n  double value = args[0]->NumberValue() + args[1]->NumberValue();\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(addon, 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
\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::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<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };\n  cb->Call(Null(isolate), argc, argv);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n  NODE_SET_METHOD(module, "exports", RunCallback);\n}\n\nNODE_MODULE(addon, Init)\n\n}  // namespace demo\n
\n

Note that this example uses a two-argument form of Init() that receives\nthe full module object as the second argument. This allows the Addon\nto completely overwrite exports with a single function instead of\nadding the function as a property 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

Note that, in this example, the callback function is invoked synchronously.

\n", "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::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\n  Local<Object> obj = Object::New(isolate);\n  obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());\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(addon, 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
\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::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(isolate, "hello world"));\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n\n  // omit this to make it anonymous\n  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));\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(addon, 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
\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(addon, 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  static v8::Persistent<v8::Function> constructor;\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::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\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\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);\n\n  constructor.Reset(isolate, tpl->GetFunction());\n  exports->Set(String::NewFromUtf8(isolate, "MyObject"),\n               tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\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<Context> context = isolate->GetCurrentContext();\n    Local<Function> cons = Local<Function>::New(isolate, constructor);\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", "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(addon, 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::Persistent<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 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::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<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"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  // Prototype\n  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);\n\n  constructor.Reset(isolate, tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\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<Context> context = isolate->GetCurrentContext();\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
\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::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\n  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(\n      args[0]->ToObject());\n  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(\n      args[1]->ToObject());\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(addon, 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::Persistent<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 v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<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"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n  constructor.Reset(isolate, tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n  Isolate* isolate = args.GetIsolate();\n\n  if (args.IsConstructCall()) {\n    // Invoked as constructor: `new MyObject(...)`\n    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\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<Context> context = isolate->GetCurrentContext();\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
\n", "type": "module", "displayName": "Passing wrapped objects around" }, { "textRaw": "AtExit hooks", "name": "atexit_hooks", "desc": "

An "AtExit" hook is a function that is invoked after the Node.js event loop\nhas ended but before the JavaScript VM is terminated and Node.js shuts down.\n"AtExit" hooks are registered using the node::AtExit API.

\n", "modules": [ { "textRaw": "void AtExit(callback, args)", "name": "void_atexit(callback,_args)", "desc": "\n

Registers exit hooks that run after the event loop has ended but before the VM\nis killed.

\n

AtExit takes two parameters: a pointer to a callback function to run at exit,\nand a pointer to untyped context data to be passed to that callback.

\n

Callbacks are run in last-in first-out order.

\n

The following addon.cc implements AtExit:

\n
// addon.cc\n#include <assert.h>\n#include <stdlib.h>\n#include <node.h>\n\nnamespace demo {\n\nusing node::AtExit;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\n\nstatic char cookie[] = "yum yum";\nstatic int at_exit_cb1_called = 0;\nstatic int at_exit_cb2_called = 0;\n\nstatic void at_exit_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  at_exit_cb1_called++;\n}\n\nstatic void at_exit_cb2(void* arg) {\n  assert(arg == static_cast<void*>(cookie));\n  at_exit_cb2_called++;\n}\n\nstatic void sanity_check(void*) {\n  assert(at_exit_cb1_called == 1);\n  assert(at_exit_cb2_called == 2);\n}\n\nvoid init(Local<Object> exports) {\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb1, exports->GetIsolate());\n  AtExit(sanity_check);\n}\n\nNODE_MODULE(addon, init)\n\n}  // namespace demo\n
\n

Test in JavaScript by running:

\n
// test.js\nrequire('./build/Release/addon');\n
\n\n\n", "type": "module", "displayName": "void AtExit(callback, args)" } ], "type": "module", "displayName": "AtExit hooks" } ], "type": "module", "displayName": "Addon examples" } ], "properties": [ { "textRaw": "Native Abstractions for Node.js", "name": "js", "desc": "

Each of the examples illustrated in this document make direct use of the\nNode.js and V8 APIs for implementing Addons. It is important to understand\nthat the V8 API can, and has, changed dramatically from one V8 release to the\nnext (and one major Node.js release to the next). With each change, Addons may\nneed to be updated and recompiled in order to continue functioning. The Node.js\nrelease schedule is designed to minimize the frequency and impact of such\nchanges but there is little that Node.js can do currently to ensure stability\nof 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.

\n" } ], "type": "module", "displayName": "C++ Addons" }, { "textRaw": "Assert", "name": "assert", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The assert module provides a simple set of assertion tests that can be used to\ntest invariants.

\n", "methods": [ { "textRaw": "assert(value[, message])", "type": "method", "name": "assert", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} ", "name": "value", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "message", "optional": true } ] } ], "desc": "

An alias of assert.ok().

\n" }, { "textRaw": "assert.deepEqual(actual, expected[, message])", "type": "method", "name": "deepEqual", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests for deep equality between the actual and expected parameters.\nPrimitive values are compared with the equal comparison operator ( == ).

\n

Only enumerable "own" properties are considered. The deepEqual()\nimplementation does not test object prototypes, attached symbols, or\nnon-enumerable properties. This can lead to some potentially surprising\nresults. For example, the following example does not throw an AssertionError\nbecause the properties on the Error object are non-enumerable:

\n
// WARNING: This does not throw an AssertionError!\nassert.deepEqual(Error('a'), Error('b'));\n
\n

"Deep" equality means that the enumerable "own" properties of child objects\nare evaluated also:

\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, object is equal to itself\n\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n// values of b are different\n\nassert.deepEqual(obj1, obj3);\n// OK, objects are equal\n\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n// Prototypes are ignored\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.

\n" }, { "textRaw": "assert.deepStrictEqual(actual, expected[, message])", "type": "method", "name": "deepStrictEqual", "meta": { "added": [ "v1.2.0" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Generally identical to assert.deepEqual() with two exceptions. First,\nprimitive values are compared using the strict equality operator ( === ).\nSecond, object comparisons include a strict equality check of their prototypes.

\n
const assert = require('assert');\n\nassert.deepEqual({ a: 1 }, { a: '1' });\n// OK, because 1 == '1'\n\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: { a: 1 } deepStrictEqual { a: '1' }\n// because 1 !== '1' using strict equality\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.

\n" }, { "textRaw": "assert.doesNotThrow(block[, error][, message])", "type": "method", "name": "doesNotThrow", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`block` {Function} ", "name": "block", "type": "Function" }, { "textRaw": "`error` {RegExp|Function} ", "name": "error", "type": "RegExp|Function", "optional": true }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ], "desc": "

Asserts that the function block does not throw an error. See\nassert.throws() for more details.

\n

When assert.doesNotThrow() is called, it will immediately call the block\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 different\ntype, or if the error parameter is undefined, the error is propagated back\nto the caller.

\n

The following, for instance, will throw the TypeError because there is no\nmatching error type in the assertion:

\n
assert.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 (TypeError)..':

\n
assert.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
assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  TypeError,\n  'Whoops'\n);\n// Throws: AssertionError: Got unwanted exception (TypeError). Whoops\n
\n" }, { "textRaw": "assert.equal(actual, expected[, message])", "type": "method", "name": "equal", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests shallow, coercive equality between the actual and expected parameters\nusing the equal comparison operator ( == ).

\n
const assert = require('assert');\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\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.

\n" }, { "textRaw": "assert.fail(message)", "type": "method", "name": "fail", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true }, { "textRaw": "`operator` {string} **Default:** '!=' ", "name": "operator", "type": "string", "desc": "**Default:** '!='", "optional": true }, { "textRaw": "`stackStartFunction` {function} **Default:** `assert.fail` ", "name": "stackStartFunction", "type": "function", "desc": "**Default:** `assert.fail`", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true }, { "name": "operator", "optional": true }, { "name": "stackStartFunction", "optional": true } ] }, { "params": [ { "name": "message" } ] } ], "desc": "

Throws an AssertionError. If message is falsy, the error message is set as\nthe values of actual and expected separated by the provided operator.\nOtherwise, the error message is the value of message.\nIf stackStartFunction is provided, all stack frames above that function will\nbe removed from stacktrace (see Error.captureStackTrace).

\n
const assert = require('assert');\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError: whoops\n\nassert.fail('boom');\n// AssertionError: boom\n\nassert.fail('a', 'b');\n// AssertionError: 'a' != 'b'\n
\n

Example use of stackStartFunction for truncating the exception's stacktrace:

\n
function suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
\n" }, { "textRaw": "assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])", "type": "method", "name": "fail", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true }, { "textRaw": "`operator` {string} **Default:** '!=' ", "name": "operator", "type": "string", "desc": "**Default:** '!='", "optional": true }, { "textRaw": "`stackStartFunction` {function} **Default:** `assert.fail` ", "name": "stackStartFunction", "type": "function", "desc": "**Default:** `assert.fail`", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true }, { "name": "operator", "optional": true }, { "name": "stackStartFunction", "optional": true } ] } ], "desc": "

Throws an AssertionError. If message is falsy, the error message is set as\nthe values of actual and expected separated by the provided operator.\nOtherwise, the error message is the value of message.\nIf stackStartFunction is provided, all stack frames above that function will\nbe removed from stacktrace (see Error.captureStackTrace).

\n
const assert = require('assert');\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError: whoops\n\nassert.fail('boom');\n// AssertionError: boom\n\nassert.fail('a', 'b');\n// AssertionError: 'a' != 'b'\n
\n

Example use of stackStartFunction for truncating the exception's stacktrace:

\n
function suppressFrame() {\n  assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError: 'a' !== 'b'\n//     at repl:1:1\n//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n//     ...\n
\n" }, { "textRaw": "assert.ifError(value)", "type": "method", "name": "ifError", "meta": { "added": [ "v0.1.97" ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} ", "name": "value", "type": "any" } ] }, { "params": [ { "name": "value" } ] } ], "desc": "

Throws value if value is truthy. This is useful when testing the error\nargument in callbacks.

\n
const assert = require('assert');\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// OK\nassert.ifError(1);\n// Throws 1\nassert.ifError('error');\n// Throws 'error'\nassert.ifError(new Error());\n// Throws Error\n
\n" }, { "textRaw": "assert.notDeepEqual(actual, expected[, message])", "type": "method", "name": "notDeepEqual", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests for any deep inequality. Opposite of assert.deepEqual().

\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: obj1 and obj2 are not deeply equal\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK: obj1 and obj4 are not deeply equal\n
\n

If the values are deeply 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.

\n" }, { "textRaw": "assert.notDeepStrictEqual(actual, expected[, message])", "type": "method", "name": "notDeepStrictEqual", "meta": { "added": [ "v1.2.0" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests for deep strict inequality. Opposite of assert.deepStrictEqual().

\n
const assert = require('assert');\n\nassert.notDeepEqual({a: 1}, {a: '1'});\n// AssertionError: { a: 1 } notDeepEqual { a: '1' }\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.

\n" }, { "textRaw": "assert.notEqual(actual, expected[, message])", "type": "method", "name": "notEqual", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests shallow, coercive inequality with the not equal comparison operator\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.

\n" }, { "textRaw": "assert.notStrictEqual(actual, expected[, message])", "type": "method", "name": "notStrictEqual", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests strict inequality as determined by the strict not equal operator\n( !== ).

\n
const assert = require('assert');\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError: 1 !== 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.

\n" }, { "textRaw": "assert.ok(value[, message])", "type": "method", "name": "ok", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`value` {any} ", "name": "value", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "message", "optional": true } ] } ], "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.

\n
const assert = require('assert');\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\nassert.ok(false);\n// throws "AssertionError: false == true"\nassert.ok(0);\n// throws "AssertionError: 0 == true"\nassert.ok(false, 'it\\'s false');\n// throws "AssertionError: it's false"\n
\n" }, { "textRaw": "assert.strictEqual(actual, expected[, message])", "type": "method", "name": "strictEqual", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`actual` {any} ", "name": "actual", "type": "any" }, { "textRaw": "`expected` {any} ", "name": "expected", "type": "any" }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ], "desc": "

Tests strict equality as determined by the strict equality operator ( === ).

\n
const assert = require('assert');\n\nassert.strictEqual(1, 2);\n// AssertionError: 1 === 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual(1, '1');\n// AssertionError: 1 === '1'\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.

\n" }, { "textRaw": "assert.throws(block[, error][, message])", "type": "method", "name": "throws", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`block` {Function} ", "name": "block", "type": "Function" }, { "textRaw": "`error` {RegExp|Function} ", "name": "error", "type": "RegExp|Function", "optional": true }, { "textRaw": "`message` {any} ", "name": "message", "type": "any", "optional": true } ] }, { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ], "desc": "

Expects the function block to throw an error.

\n

If specified, error can be a constructor, RegExp, or validation\nfunction.

\n

If specified, message will be the message provided by the AssertionError if\nthe block fails to throw.

\n

Validate instanceof using constructor:

\n
assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  Error\n);\n
\n

Validate error message using RegExp:

\n
assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  /value/\n);\n
\n

Custom error validation:

\n
assert.throws(\n  () => {\n    throw new Error('Wrong value');\n  },\n  function(err) {\n    if ((err instanceof Error) && /value/.test(err)) {\n      return true;\n    }\n  },\n  'unexpected error'\n);\n
\n

Note that error can not 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:

\n\n
// THIS IS A MISTAKE! DO NOT DO THIS!\nassert.throws(myFunction, 'missing foo', 'did not throw with expected message');\n\n// Do this instead.\nassert.throws(myFunction, /missing foo/, 'did not throw with expected message');\n
\n\n\n" } ], "type": "module", "displayName": "Assert" }, { "textRaw": "Buffer", "name": "buffer", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

Prior to the introduction of TypedArray in ECMAScript 2015 (ES6), the\nJavaScript language had no mechanism for reading or manipulating streams\nof binary data. The Buffer class was introduced as part of the Node.js\nAPI to make it possible to interact with octet streams in the context of things\nlike TCP streams and file system operations.

\n

Now that TypedArray has been added in ES6, the Buffer class implements the\nUint8Array API in a manner that is more optimized and suitable for Node.js'\nuse cases.

\n

Instances of the Buffer class are similar to arrays of integers but\ncorrespond to fixed-sized, raw memory allocations outside the V8 heap.\nThe size of the Buffer is established when it is created and cannot be\nresized.

\n

The Buffer class is a global within Node.js, making it unlikely that one\nwould need to ever use require('buffer').Buffer.

\n

Examples:

\n
// Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10, filled with 0x1.\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 either fill() or write().\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing [0x1, 0x2, 0x3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].\nconst buf5 = Buffer.from('tést');\n\n// Creates a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].\nconst buf6 = Buffer.from('tést', 'latin1');\n
\n", "modules": [ { "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", "desc": "

In versions of Node.js prior to v6, Buffer instances were created using the\nBuffer constructor function, which allocates the returned Buffer\ndifferently based on what arguments are provided:

\n\n

Because the behavior of new Buffer() changes significantly based on the type\nof value passed as the first argument, applications that do not properly\nvalidate the input arguments passed to new Buffer(), or that fail to\nappropriately initialize newly allocated Buffer content, can inadvertently\nintroduce security and reliability issues into their code.

\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() may be allocated off\na shared internal memory pool if size is less than or equal to half\nBuffer.poolSize. Instances returned by Buffer.allocUnsafeSlow() never\nuse the shared internal memory pool.

\n", "modules": [ { "textRaw": "The `--zero-fill-buffers` command line option", "name": "the_`--zero-fill-buffers`_command_line_option", "meta": { "added": [ "v5.10.0" ] }, "desc": "

Node.js can be started using the --zero-fill-buffers command line option to\nforce all newly allocated Buffer instances created using either\nnew Buffer(size), Buffer.allocUnsafe(), Buffer.allocUnsafeSlow() or\nnew SlowBuffer(size) to be automatically zero-filled upon creation. Use of\nthis flag changes the default behavior of these methods and can have a significant\nimpact on performance. Use of the --zero-fill-buffers option is recommended\nonly when necessary to enforce that newly allocated Buffer instances cannot\ncontain potentially sensitive data.

\n

Example:

\n
$ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n
\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 memory\ncan allow this old data to be leaked when the Buffer memory is read.

\n

While there are clear performance advantages to using Buffer.allocUnsafe(),\nextra care must be taken in order to avoid introducing security\nvulnerabilities into an application.

\n", "type": "module", "displayName": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?" } ], "type": "module", "displayName": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`" }, { "textRaw": "Buffers and Character Encodings", "name": "buffers_and_character_encodings", "desc": "

Buffer instances are commonly used to represent sequences of encoded characters\nsuch as UTF-8, UCS2, Base64 or even Hex-encoded data. It is possible to\nconvert back and forth between Buffer instances and ordinary JavaScript strings\nby using an explicit character encoding.

\n

Example:

\n
const buf = Buffer.from('hello world', 'ascii');\n\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('hex'));\n\n// Prints: aGVsbG8gd29ybGQ=\nconsole.log(buf.toString('base64'));\n
\n

The character encodings currently supported by Node.js include:

\n\n

Note: Today's browsers follow the WHATWG spec which aliases both 'latin1' and\nISO-8859-1 to win-1252. This means that while doing something like http.get(),\nif the returned charset is one of those listed in the WHATWG spec it's possible\nthat the server actually returned win-1252-encoded data, and using 'latin1'\nencoding may incorrectly decode the characters.

\n", "type": "module", "displayName": "Buffers and Character Encodings" }, { "textRaw": "Buffers and TypedArray", "name": "buffers_and_typedarray", "desc": "

Buffer instances are also Uint8Array instances. However, there are subtle\nincompatibilities with the TypedArray specification in ECMAScript 2015.\nFor example, while ArrayBuffer#slice() creates a copy of the slice, the\nimplementation of Buffer#slice() creates a view over the\nexisting Buffer without copying, making Buffer#slice() far\nmore efficient.

\n

It is also possible to create new TypedArray instances from a Buffer with\nthe following caveats:

\n
    \n
  1. The Buffer object's memory is copied to the TypedArray, not shared.

    \n
  2. \n
  3. The Buffer object's memory is interpreted as an array of distinct\nelements, and not as a byte array of the target type. That is,\nnew Uint32Array(Buffer.from([1, 2, 3, 4])) creates a 4-element Uint32Array\nwith elements [1, 2, 3, 4], not a Uint32Array with a single element\n[0x1020304] or [0x4030201].

    \n
  4. \n
\n

It is possible to create a new Buffer that shares the same allocated memory as\na TypedArray instance by using the TypeArray object's .buffer property.

\n

Example:

\n
const 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\n// Prints: <Buffer 88 a0>\nconsole.log(buf1);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf2);\n\narr[1] = 6000;\n\n// Prints: <Buffer 88 a0>\nconsole.log(buf1);\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf2);\n
\n

Note that 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

Example:

\n
const arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\n// Prints: 16\nconsole.log(buf.length);\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

The Buffer.from() method, however, does not support the use of a mapping\nfunction:

\n\n", "type": "module", "displayName": "Buffers and TypedArray" }, { "textRaw": "Buffers and ES6 iteration", "name": "buffers_and_es6_iteration", "desc": "

Buffer instances can be iterated over using the ECMAScript 2015 (ES6) for..of\nsyntax.

\n

Example:

\n
const buf = Buffer.from([1, 2, 3]);\n\n// Prints:\n//   1\n//   2\n//   3\nfor (const b of buf) {\n  console.log(b);\n}\n
\n

Additionally, the buf.values(), buf.keys(), and\nbuf.entries() methods can be used to create iterators.

\n", "type": "module", "displayName": "Buffers and ES6 iteration" } ], "classes": [ { "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.

\n", "classMethods": [ { "textRaw": "Class Method: Buffer.alloc(size[, fill[, encoding]])", "type": "classMethod", "name": "alloc", "meta": { "added": [ "v5.10.0" ] }, "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|integer} A value to pre-fill the new `Buffer` with. **Default:** `0` ", "name": "fill", "type": "string|Buffer|integer", "desc": "A value to pre-fill the new `Buffer` with. **Default:** `0`", "optional": true }, { "textRaw": "`encoding` {string} If `fill` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "If `fill` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "size" }, { "name": "fill", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Allocates a new Buffer of size bytes. If fill is undefined, the\nBuffer will be zero-filled.

\n

Example:

\n
const buf = Buffer.alloc(5);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\n

The size must be less than or equal to the value of buffer.kMaxLength.\nOtherwise, a RangeError is thrown. A zero-length Buffer will be created if\nsize <= 0.

\n

If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill).

\n

Example:

\n
const buf = Buffer.alloc(5, 'a');\n\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf);\n
\n

If both fill and encoding are specified, the allocated Buffer will be\ninitialized by calling buf.fill(fill, encoding).

\n

Example:

\n
const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\nconsole.log(buf);\n
\n

Calling Buffer.alloc() can be significantly slower than the alternative\nBuffer.allocUnsafe() but ensures that the newly created Buffer instance\ncontents will never contain sensitive data.

\n

A TypeError will be thrown if size is not a number.

\n" }, { "textRaw": "Class Method: Buffer.allocUnsafe(size)", "type": "classMethod", "name": "allocUnsafe", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`. ", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

Allocates a new non-zero-filled Buffer of size bytes. The size must\nbe less than or equal to the value of buffer.kMaxLength. Otherwise, a\nRangeError is thrown. A zero-length Buffer will be created if size <= 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 Buffer.alloc() instead to initialize\nBuffer instances to zeroes.

\n

Example:

\n
const buf = Buffer.allocUnsafe(10);\n\n// Prints: (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\n

A TypeError will be thrown if size is not a number.

\n

Note that 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() and the deprecated\nnew Buffer(size) constructor only when size is less than or equal to\nBuffer.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.

\n" }, { "textRaw": "Class Method: Buffer.allocUnsafeSlow(size)", "type": "classMethod", "name": "allocUnsafeSlow", "meta": { "added": [ "v5.12.0" ] }, "signatures": [ { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`. ", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

Allocates a new non-zero-filled and non-pooled Buffer of size bytes. The\nsize must be less than or equal to the value of buffer.kMaxLength.\nOtherwise, a RangeError is thrown. A zero-length Buffer will be created if\nsize <= 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 such\nBuffer instances to zeroes.

\n

When using Buffer.allocUnsafe() to allocate new Buffer instances,\nallocations under 4KB are, by default, sliced from a single pre-allocated\nBuffer. This allows applications to avoid the garbage collection overhead of\ncreating many individually allocated Buffer instances. This approach improves\nboth performance and memory usage by eliminating the need to track and cleanup as\nmany Persistent 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() then\ncopy out the relevant bits.

\n

Example:

\n
// Need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n  const data = socket.read();\n\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

Use of Buffer.allocUnsafeSlow() should be used only as a last resort after\na developer has observed undue memory retention in their applications.

\n

A TypeError will be thrown if size is not a number.

\n" }, { "textRaw": "Class Method: Buffer.byteLength(string[, encoding])", "type": "classMethod", "name": "byteLength", "meta": { "added": [ "v0.1.90" ] }, "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", "desc": "If `string` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Returns the actual byte length of a string. This is not the same as\nString.prototype.length since that returns the number of characters in\na string.

\n

Note that for 'base64' and 'hex', this function assumes valid input. For\nstrings that contain non-Base64/Hex-encoded data (e.g. whitespace), the return\nvalue might be greater than the length of a Buffer created from the string.

\n

Example:

\n
const str = '\\u00bd + \\u00bc = \\u00be';\n\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\nconsole.log(`${str}: ${str.length} characters, ` +\n            `${Buffer.byteLength(str, 'utf8')} bytes`);\n
\n

When string is a Buffer/DataView/TypedArray/ArrayBuffer/\nSharedArrayBuffer, the actual byte length is returned.

\n

Otherwise, converts to String and returns the byte length of string.

\n" }, { "textRaw": "Class Method: Buffer.compare(buf1, buf2)", "type": "classMethod", "name": "compare", "meta": { "added": [ "v0.11.13" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [ { "textRaw": "`buf1` {Buffer} ", "name": "buf1", "type": "Buffer" }, { "textRaw": "`buf2` {Buffer} ", "name": "buf2", "type": "Buffer" } ] }, { "params": [ { "name": "buf1" }, { "name": "buf2" } ] } ], "desc": "

Compares buf1 to buf2 typically for the purpose of sorting arrays of\nBuffer instances. This is equivalent to calling\nbuf1.compare(buf2).

\n

Example:

\n
const buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1])\nconsole.log(arr.sort(Buffer.compare));\n
\n" }, { "textRaw": "Class Method: Buffer.concat(list[, totalLength])", "type": "classMethod", "name": "concat", "meta": { "added": [ "v0.7.11" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`list` {Array} List of `Buffer` instances to concat. ", "name": "list", "type": "Array", "desc": "List of `Buffer` instances to concat." }, { "textRaw": "`totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated. ", "name": "totalLength", "type": "integer", "desc": "Total length of the `Buffer` instances in `list` when concatenated.", "optional": true } ] }, { "params": [ { "name": "list" }, { "name": "totalLength", "optional": true } ] } ], "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. This however causes an additional loop to be executed in order to\ncalculate the totalLength, so it is faster to provide the length explicitly if\nit is already known.

\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

Example: Create a single Buffer from a list of three Buffer instances

\n
const buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\n// Prints: 42\nconsole.log(totalLength);\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA);\n\n// Prints: 42\nconsole.log(bufA.length);\n
\n" }, { "textRaw": "Class Method: Buffer.from(array)", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "params": [ { "textRaw": "`array` {Array} ", "name": "array", "type": "Array" } ] }, { "params": [ { "name": "array" } ] } ], "desc": "

Allocates a new Buffer using an array of octets.

\n

Example:

\n
// Creates a new Buffer containing 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.

\n" }, { "textRaw": "Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "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", "desc": "Index of first byte to expose. **Default:** `0`", "optional": true }, { "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` ", "name": "length", "type": "integer", "desc": "Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset`", "optional": true } ] }, { "params": [ { "name": "arrayBuffer" }, { "name": "byteOffset", "optional": true }, { "name": "length", "optional": true } ] } ], "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.

\n

Example:

\n
const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = Buffer.from(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\n

The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

\n

Example:

\n
const ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\n// Prints: 2\nconsole.log(buf.length);\n
\n

A TypeError will be thrown if arrayBuffer is not an ArrayBuffer or a\nSharedArrayBuffer.

\n" }, { "textRaw": "Class Method: Buffer.from(buffer)", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer} An existing `Buffer` to copy data from. ", "name": "buffer", "type": "Buffer", "desc": "An existing `Buffer` to copy data from." } ] }, { "params": [ { "name": "buffer" } ] } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.

\n

Example:

\n
const buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\n

A TypeError will be thrown if buffer is not a Buffer.

\n" }, { "textRaw": "Class Method: Buffer.from(string[, encoding])", "type": "classMethod", "name": "from", "meta": { "added": [ "v5.10.0" ] }, "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", "desc": "The encoding of `string`. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Creates a new Buffer containing the given JavaScript string string. If\nprovided, the encoding parameter identifies the character encoding of string.

\n

Examples:

\n
const buf1 = Buffer.from('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\n

A TypeError will be thrown if string is not a string.

\n" }, { "textRaw": "Class Method: Buffer.isBuffer(obj)", "type": "classMethod", "name": "isBuffer", "meta": { "added": [ "v0.1.101" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`obj` {Object} ", "name": "obj", "type": "Object" } ] }, { "params": [ { "name": "obj" } ] } ], "desc": "

Returns true if obj is a Buffer, false otherwise.

\n" }, { "textRaw": "Class Method: Buffer.isEncoding(encoding)", "type": "classMethod", "name": "isEncoding", "meta": { "added": [ "v0.9.1" ] }, "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." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Returns true if encoding contains a supported character encoding, or false\notherwise.

\n" } ], "properties": [ { "textRaw": "`poolSize` {integer} **Default:** `8192` ", "type": "integer", "name": "poolSize", "meta": { "added": [ "v0.11.3" ] }, "desc": "

This is the number of bytes used to determine the size of pre-allocated, internal\nBuffer instances used for pooling. This value may be modified.

\n", "shortDesc": "**Default:** `8192`" }, { "textRaw": "buf[index]", "name": "[index]", "meta": { "type": "property", "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 - that is, getting returns undefined and\nsetting does nothing.

\n

Example: Copy an ASCII string into a Buffer, one byte at a time

\n
const 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\n// Prints: Node.js\nconsole.log(buf.toString('ascii'));\n
\n" }, { "textRaw": "`length` {integer} ", "type": "integer", "name": "length", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Returns the amount of memory allocated for buf in bytes. Note that this\ndoes not necessarily reflect the amount of "usable" data within buf.

\n

Example: Create a Buffer and write a shorter ASCII string to it

\n
const buf = Buffer.alloc(1234);\n\n// Prints: 1234\nconsole.log(buf.length);\n\nbuf.write('some string', 0, 'ascii');\n\n// Prints: 1234\nconsole.log(buf.length);\n
\n

While the length property is not immutable, changing the value of length\ncan result in undefined and inconsistent behavior. Applications that wish to\nmodify the length of a Buffer should therefore treat length as read-only and\nuse buf.slice() to create a new Buffer.

\n

Examples:

\n
let buf = Buffer.allocUnsafe(10);\n\nbuf.write('abcdefghj', 0, 'ascii');\n\n// Prints: 10\nconsole.log(buf.length);\n\nbuf = buf.slice(0, 5);\n\n// Prints: 5\nconsole.log(buf.length);\n
\n" } ], "methods": [ { "textRaw": "buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])", "type": "method", "name": "compare", "meta": { "added": [ "v0.11.13" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [ { "textRaw": "`target` {Buffer} A `Buffer` to compare to. ", "name": "target", "type": "Buffer", "desc": "A `Buffer` to compare to." }, { "textRaw": "`targetStart` {integer} The offset within `target` at which to begin comparison. **Default:** `0` ", "name": "targetStart", "type": "integer", "desc": "The offset within `target` at which to begin comparison. **Default:** `0`", "optional": true }, { "textRaw": "`targetEnd` {integer} The offset with `target` at which to end comparison (not inclusive). **Default:** `target.length` ", "name": "targetEnd", "type": "integer", "desc": "The offset with `target` at which to end comparison (not inclusive). **Default:** `target.length`", "optional": true }, { "textRaw": "`sourceStart` {integer} The offset within `buf` at which to begin comparison. **Default:** `0` ", "name": "sourceStart", "type": "integer", "desc": "The offset within `buf` at which to begin comparison. **Default:** `0`", "optional": true }, { "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to end comparison (not inclusive). **Default:** [`buf.length`] ", "name": "sourceEnd", "type": "integer", "desc": "The offset within `buf` at which to end comparison (not inclusive). **Default:** [`buf.length`]", "optional": true } ] }, { "params": [ { "name": "target" }, { "name": "targetStart", "optional": true }, { "name": "targetEnd", "optional": true }, { "name": "sourceStart", "optional": true }, { "name": "sourceEnd", "optional": true } ] } ], "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

Examples:

\n
const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\n// Prints: 0\nconsole.log(buf1.compare(buf1));\n\n// Prints: -1\nconsole.log(buf1.compare(buf2));\n\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n\n// Prints: 1\nconsole.log(buf2.compare(buf1));\n\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2])\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\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

Examples:

\n
const 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\n// Prints: 0\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n\n// Prints: -1\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n\n// Prints: 1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n
\n

A RangeError will be thrown if: targetStart < 0, sourceStart < 0,\ntargetEnd > target.byteLength or sourceEnd > source.byteLength.

\n" }, { "textRaw": "buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])", "type": "method", "name": "copy", "meta": { "added": [ "v0.1.90" ] }, "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 copying to. **Default:** `0` ", "name": "targetStart", "type": "integer", "desc": "The offset within `target` at which to begin copying to. **Default:** `0`", "optional": true }, { "textRaw": "`sourceStart` {integer} The offset within `buf` at which to begin copying from. **Default:** `0` ", "name": "sourceStart", "type": "integer", "desc": "The offset within `buf` at which to begin copying from. **Default:** `0`", "optional": true }, { "textRaw": "`sourceEnd` {integer} The offset within `buf` at which to stop copying (not inclusive). **Default:** [`buf.length`] ", "name": "sourceEnd", "type": "integer", "desc": "The offset within `buf` at which to stop copying (not inclusive). **Default:** [`buf.length`]", "optional": true } ] }, { "params": [ { "name": "target" }, { "name": "targetStart", "optional": true }, { "name": "sourceStart", "optional": true }, { "name": "sourceEnd", "optional": true } ] } ], "desc": "

Copies data from a region of buf to a region in target even if the target\nmemory region overlaps with buf.

\n

Example: Create two Buffer instances, buf1 and buf2, and copy buf1 from\nbyte 16 through byte 19 into buf2, starting at the 8th byte in buf2

\n
const 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\nbuf1.copy(buf2, 8, 16, 20);\n\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\nconsole.log(buf2.toString('ascii', 0, 25));\n
\n

Example: Create a single Buffer and copy data from one region to an\noverlapping region within the same Buffer

\n
const 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\n// Prints: efghijghijklmnopqrstuvwxyz\nconsole.log(buf.toString());\n
\n" }, { "textRaw": "buf.entries()", "type": "method", "name": "entries", "meta": { "added": [ "v1.1.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Creates and returns an iterator of [index, byte] pairs from the contents of\nbuf.

\n

Example: Log the entire contents of a Buffer

\n
const buf = Buffer.from('buffer');\n\n// Prints:\n//   [0, 98]\n//   [1, 117]\n//   [2, 102]\n//   [3, 102]\n//   [4, 101]\n//   [5, 114]\nfor (const pair of buf.entries()) {\n  console.log(pair);\n}\n
\n" }, { "textRaw": "buf.equals(otherBuffer)", "type": "method", "name": "equals", "meta": { "added": [ "v0.11.13" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`otherBuffer` {Buffer} A `Buffer` to compare to. ", "name": "otherBuffer", "type": "Buffer", "desc": "A `Buffer` to compare to." } ] }, { "params": [ { "name": "otherBuffer" } ] } ], "desc": "

Returns true if both buf and otherBuffer have exactly the same bytes,\nfalse otherwise.

\n

Examples:

\n
const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\n// Prints: true\nconsole.log(buf1.equals(buf2));\n\n// Prints: false\nconsole.log(buf1.equals(buf3));\n
\n" }, { "textRaw": "buf.fill(value[, offset[, end]][, encoding])", "type": "method", "name": "fill", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`. ", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [ { "textRaw": "`value` {string|Buffer|integer} The value to fill `buf` with. ", "name": "value", "type": "string|Buffer|integer", "desc": "The value to fill `buf` with." }, { "textRaw": "`offset` {integer} Number of bytes to skip before starting to fill `buf`. **Default:** `0` ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to fill `buf`. **Default:** `0`", "optional": true }, { "textRaw": "`end` {integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`] ", "name": "end", "type": "integer", "desc": "Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`]", "optional": true }, { "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset", "optional": true }, { "name": "end", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Fills buf with the specified value. If the offset and end are not given,\nthe entire buf will be filled. This is meant to be a small simplification to\nallow the creation and filling of a Buffer to be done on a single line.

\n

Example: Fill a Buffer with the ASCII character 'h'

\n
const b = Buffer.allocUnsafe(50).fill('h');\n\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nconsole.log(b.toString());\n
\n

value is coerced to a uint32 value if it is not a String or Integer.

\n

If the final write of a fill() operation falls on a multi-byte character,\nthen only the first bytes of that character that fit into buf are written.

\n

Example: Fill a Buffer with a two-byte character

\n
// Prints: <Buffer c8 a2 c8>\nconsole.log(Buffer.allocUnsafe(3).fill('\\u0222'));\n
\n" }, { "textRaw": "buf.includes(value[, byteOffset][, encoding])", "type": "method", "name": "includes", "meta": { "added": [ "v5.3.0" ] }, "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|integer} What to search for. ", "name": "value", "type": "string|Buffer|integer", "desc": "What to search for." }, { "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. **Default:** `0` ", "name": "byteOffset", "type": "integer", "desc": "Where to begin searching in `buf`. **Default:** `0`", "optional": true }, { "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Equivalent to buf.indexOf() !== -1.

\n

Examples:

\n
const buf = Buffer.from('this is a buffer');\n\n// Prints: true\nconsole.log(buf.includes('this'));\n\n// Prints: true\nconsole.log(buf.includes('is'));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n\n// Prints: true\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(97));\n\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n\n// Prints: false\nconsole.log(buf.includes('this', 4));\n
\n" }, { "textRaw": "buf.indexOf(value[, byteOffset][, encoding])", "type": "method", "name": "indexOf", "meta": { "added": [ "v1.5.0" ] }, "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|integer} What to search for. ", "name": "value", "type": "string|Buffer|integer", "desc": "What to search for." }, { "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. **Default:** `0` ", "name": "byteOffset", "type": "integer", "desc": "Where to begin searching in `buf`. **Default:** `0`", "optional": true }, { "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

If value is:

\n\n

Examples:

\n
const buf = Buffer.from('this is a buffer');\n\n// Prints: 0\nconsole.log(buf.indexOf('this'));\n\n// Prints: 2\nconsole.log(buf.indexOf('is'));\n\n// Prints: 8\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n\n// Prints: 8\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(97));\n\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n\n// Prints: 8\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'ucs2');\n\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'ucs2'));\n\n// Prints: 6\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'ucs2'));\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 or 0, like {}, [], null or undefined, will search\nthe whole buffer. This behavior matches String#indexOf().

\n
const 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" }, { "textRaw": "buf.includes(value[, byteOffset][, encoding])", "type": "method", "name": "includes", "meta": { "added": [ "v5.3.0" ] }, "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|Integer} What to search for. ", "name": "value", "type": "String|Buffer|Integer", "desc": "What to search for." }, { "textRaw": "`byteOffset` {Integer} Where to begin searching in `buf`. **Default:** `0` ", "name": "byteOffset", "type": "Integer", "desc": "Where to begin searching in `buf`. **Default:** `0`", "optional": true }, { "textRaw": "`encoding` {String} If `value` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "String", "desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Equivalent to buf.indexOf() !== -1.

\n

Examples:

\n
const buf = Buffer.from('this is a buffer');\n\n// Prints: true\nconsole.log(buf.includes('this'));\n\n// Prints: true\nconsole.log(buf.includes('is'));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n\n// Prints: true\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(97));\n\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n\n// Prints: false\nconsole.log(buf.includes('this', 4));\n
\n" }, { "textRaw": "buf.keys()", "type": "method", "name": "keys", "meta": { "added": [ "v1.1.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Creates and returns an iterator of buf keys (indices).

\n

Example:

\n
const buf = Buffer.from('buffer');\n\n// Prints:\n//   0\n//   1\n//   2\n//   3\n//   4\n//   5\nfor (const key of buf.keys()) {\n  console.log(key);\n}\n
\n" }, { "textRaw": "buf.lastIndexOf(value[, byteOffset][, encoding])", "type": "method", "name": "lastIndexOf", "meta": { "added": [ "v6.0.0" ] }, "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|integer} What to search for. ", "name": "value", "type": "string|Buffer|integer", "desc": "What to search for." }, { "textRaw": "`byteOffset` {integer} Where to begin searching in `buf`. **Default:** [`buf.length`]` - 1` ", "name": "byteOffset", "type": "integer", "desc": "Where to begin searching in `buf`. **Default:** [`buf.length`]` - 1`", "optional": true }, { "textRaw": "`encoding` {string} If `value` is a string, this is its encoding. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Identical to buf.indexOf(), except buf is searched from back to front\ninstead of front to back.

\n

Examples:

\n
const buf = Buffer.from('this buffer is a buffer');\n\n// Prints: 0\nconsole.log(buf.lastIndexOf('this'));\n\n// Prints: 17\nconsole.log(buf.lastIndexOf('buffer'));\n\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n\n// Prints: 15\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(97));\n\n// Prints: -1\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 5));\n\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 4));\n\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'ucs2');\n\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'ucs2'));\n\n// Prints: 4\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'ucs2'));\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#lastIndexOf().

\n
const 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" }, { "textRaw": "buf.readDoubleBE(offset[, noAssert])", "type": "method", "name": "readDoubleBE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 64-bit double from buf at the specified offset with specified\nendian format (readDoubleBE() returns big endian, readDoubleLE() returns\nlittle endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\n// Prints: 8.20788039913184e-304\nconsole.log(buf.readDoubleBE());\n\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readDoubleLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readDoubleLE(1, true));\n
\n" }, { "textRaw": "buf.readDoubleLE(offset[, noAssert])", "type": "method", "name": "readDoubleLE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 64-bit double from buf at the specified offset with specified\nendian format (readDoubleBE() returns big endian, readDoubleLE() returns\nlittle endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\n// Prints: 8.20788039913184e-304\nconsole.log(buf.readDoubleBE());\n\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readDoubleLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readDoubleLE(1, true));\n
\n" }, { "textRaw": "buf.readFloatBE(offset[, noAssert])", "type": "method", "name": "readFloatBE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 32-bit float from buf at the specified offset with specified\nendian format (readFloatBE() returns big endian, readFloatLE() returns\nlittle endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([1, 2, 3, 4]);\n\n// Prints: 2.387939260590663e-38\nconsole.log(buf.readFloatBE());\n\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readFloatLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readFloatLE(1, true));\n
\n" }, { "textRaw": "buf.readFloatLE(offset[, noAssert])", "type": "method", "name": "readFloatLE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 32-bit float from buf at the specified offset with specified\nendian format (readFloatBE() returns big endian, readFloatLE() returns\nlittle endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([1, 2, 3, 4]);\n\n// Prints: 2.387939260590663e-38\nconsole.log(buf.readFloatBE());\n\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readFloatLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readFloatLE(1, true));\n
\n" }, { "textRaw": "buf.readInt8(offset[, noAssert])", "type": "method", "name": "readInt8", "meta": { "added": [ "v0.5.0" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 1`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 8-bit integer from buf at the specified offset.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n

Examples:

\n
const buf = Buffer.from([-1, 5]);\n\n// Prints: -1\nconsole.log(buf.readInt8(0));\n\n// Prints: 5\nconsole.log(buf.readInt8(1));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt8(2));\n
\n" }, { "textRaw": "buf.readInt16BE(offset[, noAssert])", "type": "method", "name": "readInt16BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 16-bit integer from buf at the specified offset with\nthe specified endian format (readInt16BE() returns big endian,\nreadInt16LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n

Examples:

\n
const buf = Buffer.from([0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt16BE());\n\n// Prints: 1280\nconsole.log(buf.readInt16LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt16LE(1));\n
\n" }, { "textRaw": "buf.readInt16LE(offset[, noAssert])", "type": "method", "name": "readInt16LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 16-bit integer from buf at the specified offset with\nthe specified endian format (readInt16BE() returns big endian,\nreadInt16LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n

Examples:

\n
const buf = Buffer.from([0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt16BE());\n\n// Prints: 1280\nconsole.log(buf.readInt16LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt16LE(1));\n
\n" }, { "textRaw": "buf.readInt32BE(offset[, noAssert])", "type": "method", "name": "readInt32BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 32-bit integer from buf at the specified offset with\nthe specified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n

Examples:

\n
const buf = Buffer.from([0, 0, 0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt32BE());\n\n// Prints: 83886080\nconsole.log(buf.readInt32LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt32LE(1));\n
\n" }, { "textRaw": "buf.readInt32LE(offset[, noAssert])", "type": "method", "name": "readInt32LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 32-bit integer from buf at the specified offset with\nthe specified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Integers read from a Buffer are interpreted as two's complement signed values.

\n

Examples:

\n
const buf = Buffer.from([0, 0, 0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt32BE());\n\n// Prints: 83886080\nconsole.log(buf.readInt32LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt32LE(1));\n
\n" }, { "textRaw": "buf.readIntBE(offset, byteLength[, noAssert])", "type": "method", "name": "readIntBE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` and `byteLength` validation? **Default:** `false`. ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` and `byteLength` validation? **Default:** `false`.", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a two's complement signed value. Supports up to 48\nbits of accuracy.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: -546f87a9cbee\nconsole.log(buf.readIntLE(0, 6).toString(16));\n\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readIntBE(1, 6).toString(16));\n
\n" }, { "textRaw": "buf.readIntLE(offset, byteLength[, noAssert])", "type": "method", "name": "readIntLE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` and `byteLength` validation? **Default:** `false`. ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` and `byteLength` validation? **Default:** `false`.", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as a two's complement signed value. Supports up to 48\nbits of accuracy.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: -546f87a9cbee\nconsole.log(buf.readIntLE(0, 6).toString(16));\n\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readIntBE(1, 6).toString(16));\n
\n" }, { "textRaw": "buf.readUInt8(offset[, noAssert])", "type": "method", "name": "readUInt8", "meta": { "added": [ "v0.5.0" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 1`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 8-bit integer from buf at the specified offset.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([1, -2]);\n\n// Prints: 1\nconsole.log(buf.readUInt8(0));\n\n// Prints: 254\nconsole.log(buf.readUInt8(1));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt8(2));\n
\n" }, { "textRaw": "buf.readUInt16BE(offset[, noAssert])", "type": "method", "name": "readUInt16BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 16-bit integer from buf at the specified offset with\nspecified endian format (readUInt16BE() returns big endian, readUInt16LE()\nreturns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56]);\n\n// Prints: 1234\nconsole.log(buf.readUInt16BE(0).toString(16));\n\n// Prints: 3412\nconsole.log(buf.readUInt16LE(0).toString(16));\n\n// Prints: 3456\nconsole.log(buf.readUInt16BE(1).toString(16));\n\n// Prints: 5634\nconsole.log(buf.readUInt16LE(1).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt16LE(2).toString(16));\n
\n" }, { "textRaw": "buf.readUInt16LE(offset[, noAssert])", "type": "method", "name": "readUInt16LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 16-bit integer from buf at the specified offset with\nspecified endian format (readUInt16BE() returns big endian, readUInt16LE()\nreturns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56]);\n\n// Prints: 1234\nconsole.log(buf.readUInt16BE(0).toString(16));\n\n// Prints: 3412\nconsole.log(buf.readUInt16LE(0).toString(16));\n\n// Prints: 3456\nconsole.log(buf.readUInt16BE(1).toString(16));\n\n// Prints: 5634\nconsole.log(buf.readUInt16LE(1).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt16LE(2).toString(16));\n
\n" }, { "textRaw": "buf.readUInt32BE(offset[, noAssert])", "type": "method", "name": "readUInt32BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 32-bit integer from buf at the specified offset with\nspecified endian format (readUInt32BE() returns big endian,\nreadUInt32LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\n// Prints: 12345678\nconsole.log(buf.readUInt32BE(0).toString(16));\n\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(0).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt32LE(1).toString(16));\n
\n" }, { "textRaw": "buf.readUInt32LE(offset[, noAssert])", "type": "method", "name": "readUInt32LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 32-bit integer from buf at the specified offset with\nspecified endian format (readUInt32BE() returns big endian,\nreadUInt32LE() returns little endian).

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\n// Prints: 12345678\nconsole.log(buf.readUInt32BE(0).toString(16));\n\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(0).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt32LE(1).toString(16));\n
\n" }, { "textRaw": "buf.readUIntBE(offset, byteLength[, noAssert])", "type": "method", "name": "readUIntBE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned integer. Supports up to 48\nbits of accuracy.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n\n// Prints: ab9078563412\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n
\n" }, { "textRaw": "buf.readUIntLE(offset, byteLength[, noAssert])", "type": "method", "name": "readUIntLE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `offset` and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads byteLength number of bytes from buf at the specified offset\nand interprets the result as an unsigned integer. Supports up to 48\nbits of accuracy.

\n

Setting noAssert to true allows offset to be beyond the end of buf, but\nthe resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n\n// Prints: ab9078563412\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n
\n" }, { "textRaw": "buf.slice([start[, end]])", "type": "method", "name": "slice", "meta": { "added": [ "v0.3.0" ] }, "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", "desc": "Where the new `Buffer` will start. **Default:** `0`", "optional": true }, { "textRaw": "`end` {integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`] ", "name": "end", "type": "integer", "desc": "Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`]", "optional": true } ] }, { "params": [ { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

Returns a new Buffer that references the same memory as the original, but\noffset and cropped by the start and end indices.

\n

Note that modifying the new Buffer slice will modify the memory in the\noriginal Buffer because the allocated memory of the two objects overlap.

\n

Example: Create a Buffer with the ASCII alphabet, take a slice, and then modify\none byte from the original Buffer

\n
const 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.slice(0, 3);\n\n// Prints: abc\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\nbuf1[0] = 33;\n\n// Prints: !bc\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n
\n

Specifying negative indexes causes the slice to be generated relative to the\nend of buf rather than the beginning.

\n

Examples:

\n
const buf = Buffer.from('buffer');\n\n// Prints: buffe\n// (Equivalent to buf.slice(0, 5))\nconsole.log(buf.slice(-6, -1).toString());\n\n// Prints: buff\n// (Equivalent to buf.slice(0, 4))\nconsole.log(buf.slice(-6, -2).toString());\n\n// Prints: uff\n// (Equivalent to buf.slice(1, 4))\nconsole.log(buf.slice(-5, -2).toString());\n
\n" }, { "textRaw": "buf.swap16()", "type": "method", "name": "swap16", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`. ", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] }, { "params": [] } ], "desc": "

Interprets buf as an array of unsigned 16-bit integers and swaps the byte-order\nin-place. Throws a RangeError if buf.length is not a multiple of 2.

\n

Examples:

\n
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap16();\n\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits\nbuf2.swap16();\n
\n" }, { "textRaw": "buf.swap32()", "type": "method", "name": "swap32", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`. ", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] }, { "params": [] } ], "desc": "

Interprets buf as an array of unsigned 32-bit integers and swaps the byte-order\nin-place. Throws a RangeError if buf.length is not a multiple of 4.

\n

Examples:

\n
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap32();\n\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits\nbuf2.swap32();\n
\n" }, { "textRaw": "buf.swap64()", "type": "method", "name": "swap64", "meta": { "added": [ "v6.3.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A reference to `buf`. ", "name": "return", "type": "Buffer", "desc": "A reference to `buf`." }, "params": [] }, { "params": [] } ], "desc": "

Interprets buf as an array of 64-bit numbers and swaps the byte-order in-place.\nThrows a RangeError if buf.length is not a multiple of 8.

\n

Examples:

\n
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap64();\n\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits\nbuf2.swap64();\n
\n

Note that JavaScript cannot encode 64-bit integers. This method is intended\nfor working with 64-bit floats.

\n" }, { "textRaw": "buf.toString([encoding[, start[, end]]])", "type": "method", "name": "toString", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`encoding` {string} The character encoding to decode to. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "The character encoding to decode to. **Default:** `'utf8'`", "optional": true }, { "textRaw": "`start` {integer} The byte offset to start decoding at. **Default:** `0` ", "name": "start", "type": "integer", "desc": "The byte offset to start decoding at. **Default:** `0`", "optional": true }, { "textRaw": "`end` {integer} The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`] ", "name": "end", "type": "integer", "desc": "The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`]", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true }, { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "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

Examples:

\n
const 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\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('ascii'));\n\n// Prints: abcde\nconsole.log(buf1.toString('ascii', 0, 5));\n\n\nconst buf2 = Buffer.from('tést');\n\n// Prints: 74c3a97374\nconsole.log(buf2.toString('hex'));\n\n// Prints: té\nconsole.log(buf2.toString('utf8', 0, 3));\n\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n
\n" }, { "textRaw": "buf.toJSON()", "type": "method", "name": "toJSON", "meta": { "added": [ "v0.9.2" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

Returns a JSON representation of buf. JSON.stringify() implicitly calls\nthis function when stringifying a Buffer instance.

\n

Example:

\n
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\n// Prints: {"type":"Buffer","data":[1,2,3,4,5]}\nconsole.log(json);\n\nconst copy = JSON.parse(json, (key, value) => {\n  return value && value.type === 'Buffer' ?\n    Buffer.from(value.data) :\n    value;\n});\n\n// Prints: <Buffer 01 02 03 04 05>\nconsole.log(copy);\n
\n" }, { "textRaw": "buf.values()", "type": "method", "name": "values", "meta": { "added": [ "v1.1.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "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

Examples:

\n
const buf = Buffer.from('buffer');\n\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\nfor (const value of buf.values()) {\n  console.log(value);\n}\n\n// Prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\nfor (const value of buf) {\n  console.log(value);\n}\n
\n" }, { "textRaw": "buf.write(string[, offset[, length]][, encoding])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} Number of bytes written. ", "name": "return", "type": "integer", "desc": "Number of bytes written." }, "params": [ { "textRaw": "`string` {string} String to be written to `buf`. ", "name": "string", "type": "string", "desc": "String to be written to `buf`." }, { "textRaw": "`offset` {integer} Number of bytes to skip before starting to write `string`. **Default:** `0` ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write `string`. **Default:** `0`", "optional": true }, { "textRaw": "`length` {integer} Number of bytes to write. **Default:** `buf.length - offset` ", "name": "length", "type": "integer", "desc": "Number of bytes to write. **Default:** `buf.length - offset`", "optional": true }, { "textRaw": "`encoding` {string} The character encoding of `string`. **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "The character encoding of `string`. **Default:** `'utf8'`", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Writes string to buf at offset according to the character encoding in encoding.\nThe length parameter is the number of bytes to write. If buf did not contain\nenough space to fit the entire string, only a partial amount of string will\nbe written. However, partially encoded characters will not be written.

\n

Example:

\n
const buf = Buffer.allocUnsafe(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\n// Prints: 12 bytes: ½ + ¼ = ¾\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n
\n" }, { "textRaw": "buf.writeDoubleBE(value, offset[, noAssert])", "type": "method", "name": "writeDoubleBE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeDoubleBE() writes big endian, writeDoubleLE() writes little\nendian). value should be a valid 64-bit double. Behavior is undefined when\nvalue is anything other than a 64-bit double.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeDoubleLE(value, offset[, noAssert])", "type": "method", "name": "writeDoubleLE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeDoubleBE() writes big endian, writeDoubleLE() writes little\nendian). value should be a valid 64-bit double. Behavior is undefined when\nvalue is anything other than a 64-bit double.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeFloatBE(value, offset[, noAssert])", "type": "method", "name": "writeFloatBE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeFloatBE() writes big endian, writeFloatLE() writes little\nendian). value should be a valid 32-bit float. Behavior is undefined when\nvalue is anything other than a 32-bit float.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\n// Prints: <Buffer 4f 4a fe bb>\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\n// Prints: <Buffer bb fe 4a 4f>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeFloatLE(value, offset[, noAssert])", "type": "method", "name": "writeFloatLE", "meta": { "added": [ "v0.11.15" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeFloatBE() writes big endian, writeFloatLE() writes little\nendian). value should be a valid 32-bit float. Behavior is undefined when\nvalue is anything other than a 32-bit float.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\n// Prints: <Buffer 4f 4a fe bb>\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\n// Prints: <Buffer bb fe 4a 4f>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeInt8(value, offset[, noAssert])", "type": "method", "name": "writeInt8", "meta": { "added": [ "v0.5.0" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 1`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset. value should be a valid\nsigned 8-bit integer. Behavior is undefined when value is anything other than\na signed 8-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

value is interpreted and written as a two's complement signed integer.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\n// Prints: <Buffer 02 fe>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeInt16BE(value, offset[, noAssert])", "type": "method", "name": "writeInt16BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeInt16BE() writes big endian, writeInt16LE() writes little\nendian). value should be a valid signed 16-bit integer. Behavior is undefined\nwhen value is anything other than a signed 16-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

value is interpreted and written as a two's complement signed integer.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt16BE(0x0102, 0);\nbuf.writeInt16LE(0x0304, 2);\n\n// Prints: <Buffer 01 02 04 03>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeInt16LE(value, offset[, noAssert])", "type": "method", "name": "writeInt16LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeInt16BE() writes big endian, writeInt16LE() writes little\nendian). value should be a valid signed 16-bit integer. Behavior is undefined\nwhen value is anything other than a signed 16-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

value is interpreted and written as a two's complement signed integer.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt16BE(0x0102, 0);\nbuf.writeInt16LE(0x0304, 2);\n\n// Prints: <Buffer 01 02 04 03>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeInt32BE(value, offset[, noAssert])", "type": "method", "name": "writeInt32BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeInt32BE() writes big endian, writeInt32LE() writes little\nendian). value should be a valid signed 32-bit integer. Behavior is undefined\nwhen value is anything other than a signed 32-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

value is interpreted and written as a two's complement signed integer.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(8);\n\nbuf.writeInt32BE(0x01020304, 0);\nbuf.writeInt32LE(0x05060708, 4);\n\n// Prints: <Buffer 01 02 03 04 08 07 06 05>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeInt32LE(value, offset[, noAssert])", "type": "method", "name": "writeInt32LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeInt32BE() writes big endian, writeInt32LE() writes little\nendian). value should be a valid signed 32-bit integer. Behavior is undefined\nwhen value is anything other than a signed 32-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

value is interpreted and written as a two's complement signed integer.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(8);\n\nbuf.writeInt32BE(0x01020304, 0);\nbuf.writeInt32LE(0x05060708, 4);\n\n// Prints: <Buffer 01 02 03 04 08 07 06 05>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeIntBE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeIntBE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes byteLength bytes of value to buf at the specified offset.\nSupports up to 48 bits of accuracy. Behavior is undefined when value is\nanything other than a signed integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeIntLE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeIntLE", "meta": { "added": [ "v0.11.15" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes byteLength bytes of value to buf at the specified offset.\nSupports up to 48 bits of accuracy. Behavior is undefined when value is\nanything other than a signed integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUInt8(value, offset[, noAssert])", "type": "method", "name": "writeUInt8", "meta": { "added": [ "v0.5.0" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 1`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset. value should be a\nvalid unsigned 8-bit integer. Behavior is undefined when value is anything\nother than an unsigned 8-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\n// Prints: <Buffer 03 04 23 42>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUInt16BE(value, offset[, noAssert])", "type": "method", "name": "writeUInt16BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeUInt16BE() writes big endian, writeUInt16LE() writes little\nendian). value should be a valid unsigned 16-bit integer. Behavior is\nundefined when value is anything other than an unsigned 16-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\n// Prints: <Buffer de ad be ef>\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\n// Prints: <Buffer ad de ef be>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUInt16LE(value, offset[, noAssert])", "type": "method", "name": "writeUInt16LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 2`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeUInt16BE() writes big endian, writeUInt16LE() writes little\nendian). value should be a valid unsigned 16-bit integer. Behavior is\nundefined when value is anything other than an unsigned 16-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\n// Prints: <Buffer de ad be ef>\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\n// Prints: <Buffer ad de ef be>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUInt32BE(value, offset[, noAssert])", "type": "method", "name": "writeUInt32BE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeUInt32BE() writes big endian, writeUInt32LE() writes little\nendian). value should be a valid unsigned 32-bit integer. Behavior is\nundefined when value is anything other than an unsigned 32-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\n// Prints: <Buffer fe ed fa ce>\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\n// Prints: <Buffer ce fa ed fe>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUInt32LE(value, offset[, noAssert])", "type": "method", "name": "writeUInt32LE", "meta": { "added": [ "v0.5.5" ] }, "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`. ", "name": "offset", "type": "integer", "desc": "Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 4`." }, { "textRaw": "`noAssert` {boolean} Skip `value` and `offset` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value` and `offset` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to buf at the specified offset with specified endian\nformat (writeUInt32BE() writes big endian, writeUInt32LE() writes little\nendian). value should be a valid unsigned 32-bit integer. Behavior is\nundefined when value is anything other than an unsigned 32-bit integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\n// Prints: <Buffer fe ed fa ce>\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\n// Prints: <Buffer ce fa ed fe>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUIntBE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeUIntBE", "meta": { "added": [ "v0.5.5" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes byteLength bytes of value to buf at the specified offset.\nSupports up to 48 bits of accuracy. Behavior is undefined when value is\nanything other than an unsigned integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n" }, { "textRaw": "buf.writeUIntLE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeUIntLE", "meta": { "added": [ "v0.5.5" ] }, "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`." }, { "textRaw": "`noAssert` {boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ", "name": "noAssert", "type": "boolean", "desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes byteLength bytes of value to buf at the specified offset.\nSupports up to 48 bits of accuracy. Behavior is undefined when value is\nanything other than an unsigned integer.

\n

Setting noAssert to true allows the encoded form of value to extend beyond\nthe end of buf, but the resulting behavior is undefined.

\n

Examples:

\n
const buf = Buffer.allocUnsafe(6);\n\nbuf.writeIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\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": "

Allocates a new Buffer using an array of octets.

\n

Example:

\n
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'\nconst buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
\n" }, { "params": [ { "name": "array" } ], "desc": "

Allocates a new Buffer using an array of octets.

\n

Example:

\n
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'\nconst buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
\n" }, { "params": [ { "textRaw": "`buffer` {Buffer} An existing `Buffer` to copy data from. ", "name": "buffer", "type": "Buffer", "desc": "An existing `Buffer` to copy data from." } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.

\n

Example:

\n
const buf1 = new Buffer('buffer');\nconst buf2 = new Buffer(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\n" }, { "params": [ { "name": "buffer" } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.

\n

Example:

\n
const buf1 = new Buffer('buffer');\nconst buf2 = new Buffer(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\n" }, { "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", "desc": "Index of first byte to expose. **Default:** `0`", "optional": true }, { "textRaw": "`length` {integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` ", "name": "length", "type": "integer", "desc": "Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset`", "optional": true } ], "desc": "

Stability: 0 - Deprecated: Use\nBuffer.from(arrayBuffer[, byteOffset [, length]])\ninstead.

\n

This creates a view of the ArrayBuffer or SharedArrayBuffer without\ncopying the underlying memory. For example, when passed a reference to the\n.buffer property of a TypedArray instance, the newly created Buffer will\nshare the same allocated memory as the TypedArray.

\n

The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

\n

Example:

\n
const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = new Buffer(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\n" }, { "params": [ { "name": "arrayBuffer" }, { "name": "byteOffset", "optional": true }, { "name": "length", "optional": true } ], "desc": "

Stability: 0 - Deprecated: Use\nBuffer.from(arrayBuffer[, byteOffset [, length]])\ninstead.

\n

This creates a view of the ArrayBuffer or SharedArrayBuffer without\ncopying the underlying memory. For example, when passed a reference to the\n.buffer property of a TypedArray instance, the newly created Buffer will\nshare the same allocated memory as the TypedArray.

\n

The optional byteOffset and length arguments specify a memory range within\nthe arrayBuffer that will be shared by the Buffer.

\n

Example:

\n
const arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = new Buffer(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\n" }, { "params": [ { "textRaw": "`size` {integer} The desired length of the new `Buffer`. ", "name": "size", "type": "integer", "desc": "The desired length of the new `Buffer`." } ], "desc": "

Stability: 0 - Deprecated: Use Buffer.alloc() instead (also see\nBuffer.allocUnsafe()).

\n

Allocates a new Buffer of size bytes. The size must be less than or equal\nto the value of buffer.kMaxLength. Otherwise, a RangeError is thrown.\nA zero-length Buffer will be created if size <= 0.

\n

Unlike ArrayBuffers, the underlying memory for Buffer instances\ncreated in this way is not initialized. The contents of a newly created Buffer\nare unknown and could contain sensitive data. Use\nBuffer.alloc(size) instead to initialize a Buffer to zeroes.

\n

Example:

\n
const buf = new Buffer(10);\n\n// Prints: (contents may vary): <Buffer 48 21 4b 00 00 00 00 00 30 dd>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\n" }, { "params": [ { "name": "size" } ], "desc": "

Stability: 0 - Deprecated: Use Buffer.alloc() instead (also see\nBuffer.allocUnsafe()).

\n

Allocates a new Buffer of size bytes. The size must be less than or equal\nto the value of buffer.kMaxLength. Otherwise, a RangeError is thrown.\nA zero-length Buffer will be created if size <= 0.

\n

Unlike ArrayBuffers, the underlying memory for Buffer instances\ncreated in this way is not initialized. The contents of a newly created Buffer\nare unknown and could contain sensitive data. Use\nBuffer.alloc(size) instead to initialize a Buffer to zeroes.

\n

Example:

\n
const buf = new Buffer(10);\n\n// Prints: (contents may vary): <Buffer 48 21 4b 00 00 00 00 00 30 dd>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\n" }, { "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", "desc": "The encoding of `string`. **Default:** `'utf8'`", "optional": true } ], "desc": "

Stability: 0 - Deprecated:\nUse Buffer.from(string[, encoding]) instead.

\n

Creates a new Buffer containing the given JavaScript string string. If\nprovided, the encoding parameter identifies the character encoding of string.

\n

Examples:

\n
const buf1 = new Buffer('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\n" }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ], "desc": "

Stability: 0 - Deprecated:\nUse Buffer.from(string[, encoding]) instead.

\n

Creates a new Buffer containing the given JavaScript string string. If\nprovided, the encoding parameter identifies the character encoding of string.

\n

Examples:

\n
const buf1 = new Buffer('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\n" } ] }, { "textRaw": "Class: SlowBuffer", "type": "class", "name": "SlowBuffer", "meta": { "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`Buffer.allocUnsafeSlow()`] instead.", "desc": "

Returns an un-pooled Buffer.

\n

In order to avoid the garbage collection overhead of creating many individually\nallocated Buffer instances, by default allocations under 4KB are sliced from a\nsingle larger allocated object. This approach improves both performance and memory\nusage since v8 does not need to track and cleanup as many Persistent objects.

\n

In the case where a developer may need to retain a small chunk of memory from a\npool for an indeterminate amount of time, it may be appropriate to create an\nun-pooled Buffer instance using SlowBuffer then copy out the relevant bits.

\n

Example:

\n
// Need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n  const data = socket.read();\n\n  // Allocate for retained data\n  const sb = SlowBuffer(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

Use of SlowBuffer should be used only as a last resort after a developer\nhas observed undue memory retention in their applications.

\n", "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": "

Allocates a new SlowBuffer of size bytes. The size must be less than\nor equal to the value of buffer.kMaxLength. Otherwise, a RangeError is\nthrown. A zero-length Buffer will be created if size <= 0.

\n

The underlying memory for SlowBuffer instances is not initialized. The\ncontents of a newly created SlowBuffer are unknown and could contain\nsensitive data. Use buf.fill(0) to initialize a SlowBuffer to zeroes.

\n

Example:

\n
const SlowBuffer = require('buffer').SlowBuffer;\n\nconst buf = new SlowBuffer(5);\n\n// Prints: (contents may vary): <Buffer 78 e0 82 02 01>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\n\n\n" }, { "params": [ { "name": "size" } ], "desc": "

Allocates a new SlowBuffer of size bytes. The size must be less than\nor equal to the value of buffer.kMaxLength. Otherwise, a RangeError is\nthrown. A zero-length Buffer will be created if size <= 0.

\n

The underlying memory for SlowBuffer instances is not initialized. The\ncontents of a newly created SlowBuffer are unknown and could contain\nsensitive data. Use buf.fill(0) to initialize a SlowBuffer to zeroes.

\n

Example:

\n
const SlowBuffer = require('buffer').SlowBuffer;\n\nconst buf = new SlowBuffer(5);\n\n// Prints: (contents may vary): <Buffer 78 e0 82 02 01>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\n\n\n" } ] } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` {integer} **Default:** `50` ", "type": "integer", "name": "INSPECT_MAX_BYTES", "meta": { "added": [ "v0.5.4" ] }, "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.

\n

Note that this is a property on the buffer module as returned by\nrequire('buffer'), not on the Buffer global or a Buffer instance.

\n", "shortDesc": "**Default:** `50`" }, { "textRaw": "`kMaxLength` {integer} The largest size allowed for a single `Buffer` instance. ", "type": "integer", "name": "kMaxLength", "meta": { "added": [ "v3.0.0" ] }, "desc": "

On 32-bit architectures, this value is (2^30)-1 (~1GB).\nOn 64-bit architectures, this value is (2^31)-1 (~2GB).

\n", "shortDesc": "The largest size allowed for a single `Buffer` instance." } ], "type": "module", "displayName": "Buffer" }, { "textRaw": "Child Process", "name": "child_process", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The child_process module provides the ability to spawn child processes 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').spawn;\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.log(`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 child. It is possible to stream data\nthrough these pipes in a non-blocking way. Note, however, that some programs\nuse line-buffered I/O internally. While that does not affect Node.js, it can\nmean that data sent to the child process may not be immediately consumed.

\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(). Note that each of these alternatives are\nimplemented on top 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.

\n", "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 additionally\nallow for an optional callback function to be specified that is invoked\nwhen the child process terminates.

\n", "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 operating\nsystems (Unix, Linux, macOS) child_process.execFile() can be more efficient\nbecause it does not spawn a shell. On Windows, however, .bat and .cmd\nfiles are not executable on their own without a terminal, and therefore cannot\nbe launched using child_process.execFile(). When running on Windows, .bat\nand .cmd files can be invoked using child_process.spawn() with the shell\noption set, with child_process.exec(), or by spawning cmd.exe and passing\nthe .bat or .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').spawn;\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.log(data.toString());\n});\n\nbat.on('exit', (code) => {\n  console.log(`Child exited with code ${code}`);\n});\n
\n
// OR...\nconst exec = require('child_process').exec;\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
\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" ] }, "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} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "desc": "Environment key-value pairs." }, { "textRaw": "`encoding` {string} **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "**Default:** `'utf8'`" }, { "textRaw": "`shell` {string} Shell to execute the command with. **Default:** `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows. The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`. ", "name": "shell", "type": "string", "desc": "Shell to execute the command with. **Default:** `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows. The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`." }, { "textRaw": "`timeout` {number} **Default:** `0` ", "name": "timeout", "type": "number", "desc": "**Default:** `0`" }, { "textRaw": "[`maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. **Default:** `200 * 1024`. ", "name": "[", "desc": "maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. **Default:** `200 * 1024`." }, { "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'` ", "name": "killSignal", "type": "string|integer", "desc": "**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))." } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} 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" } ], "name": "callback", "type": "Function", "desc": "Called with the output when process terminates.", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Spawns a shell then executes the command within that shell, buffering any\ngenerated output.

\n

Note: Never pass unsanitised user input to this function. Any input\ncontaining shell metacharacters may be used to trigger arbitrary command\nexecution.

\n
const exec = require('child_process').exec;\nexec('cat *.js bad_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.log(`stderr: ${stderr}`);\n});\n
\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 child process while error.signal will be set to the\nsignal that terminated the process. Any exit code other than 0 is considered\nto be an error.

\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

The options argument may be passed as the second argument to customize how\nthe process is spawned. The default options are:

\n
const defaults = {\n  encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200 * 1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null\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

Note: Unlike the exec(3) POSIX system call, child_process.exec() does not\nreplace the existing process and uses a shell to execute the command.

\n" }, { "textRaw": "child_process.execFile(file[, args][, options][, callback])", "type": "method", "name": "execFile", "meta": { "added": [ "v0.1.91" ] }, "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.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "desc": "Environment key-value pairs." }, { "textRaw": "`encoding` {string} **Default:** `'utf8'` ", "name": "encoding", "type": "string", "desc": "**Default:** `'utf8'`" }, { "textRaw": "`timeout` {number} **Default:** `0` ", "name": "timeout", "type": "number", "desc": "**Default:** `0`" }, { "textRaw": "[`maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. **Default:** `200 * 1024`. ", "name": "[", "desc": "maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. **Default:** `200 * 1024`." }, { "textRaw": "`killSignal` {string|integer} **Default:** `'SIGTERM'` ", "name": "killSignal", "type": "string|integer", "desc": "**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))." } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} 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" } ], "name": "callback", "type": "Function", "desc": "Called with the output when process terminates.", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

The child_process.execFile() function is similar to child_process.exec()\nexcept that it does not spawn a shell. Rather, the specified executable file\nis spawned directly as a new process making it slightly more efficient than\nchild_process.exec().

\n

The same options as child_process.exec() are supported. Since a shell is not\nspawned, behaviors such as I/O redirection and file globbing are not supported.

\n
const execFile = require('child_process').execFile;\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" }, { "textRaw": "child_process.fork(modulePath[, args][, options])", "type": "method", "name": "fork", "meta": { "added": [ "v0.5.0" ] }, "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` {Array} List of string arguments. ", "name": "args", "type": "Array", "desc": "List of string arguments.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "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` {Array} List of string arguments passed to the executable. **Default:** `process.execArgv` ", "name": "execArgv", "type": "Array", "desc": "List of string arguments passed to the executable. **Default:** `process.execArgv`" }, { "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", "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. **Default:** `false`" }, { "textRaw": "`stdio` {Array} Supports the array version of [`child_process.spawn()`][]'s [`stdio`][] option. When this option is provided, it overrides `silent`. The array must contain exactly one item with value `'ipc'` or an error will be thrown. For instance `[0, 1, 2, 'ipc']`. ", "name": "stdio", "type": "Array", "desc": "Supports the array version of [`child_process.spawn()`][]'s [`stdio`][] option. When this option is provided, it overrides `silent`. The array 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": "`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))." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "modulePath" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "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 returned\nChildProcess will have an additional communication channel built-in that\nallows messages to be passed back and forth between the parent and child. See\nsubprocess.send() for details.

\n

It is important to 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. The input and\noutput on this fd is expected to be line delimited JSON objects.

\n

Note: Unlike the fork(2) POSIX system call, child_process.fork() does\nnot clone the current process.

\n

Note: The shell option available in child_process.spawn() is not\nsupported by child_process.fork() and will be ignored if set.

\n" }, { "textRaw": "child_process.spawn(command[, args][, options])", "type": "method", "name": "spawn", "meta": { "added": [ "v0.1.90" ] }, "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` {Array} List of string arguments. ", "name": "args", "type": "Array", "desc": "List of string arguments.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "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": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX, or `/s /c` on Windows. **Default:** `false` (no shell). ", "name": "shell", "type": "boolean|string", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX, or `/s /c` on Windows. **Default:** `false` (no shell)." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "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

Note: If the shell option is enabled, do not pass unsanitised user input to\nthis function. Any input containing shell metacharacters may be used to\ntrigger arbitrary 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.

\n

Use env to specify environment variables that will be visible to the new\nprocess, the default is process.env.

\n

Example of running ls -lh /usr, capturing stdout, stderr, and the\nexit code:

\n
const spawn = require('child_process').spawn;\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.log(`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').spawn;\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.log(`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.log(`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').spawn;\nconst subprocess = spawn('bad_command');\n\nsubprocess.on('error', (err) => {\n  console.log('Failed to start subprocess.');\n});\n
\n

Note: Certain platforms (macOS, Linux) will use the value of argv[0] for the\nprocess title while others (Windows, SunOS) will use command.

\n

Note: Node.js currently overwrites argv[0] with process.execPath on\nstartup, so process.argv[0] in a Node.js child process will not match the\nargv0 parameter passed to spawn from the parent, retrieve it with the\nprocess.argv0 property instead.

\n", "properties": [ { "textRaw": "options.detached", "name": "detached", "meta": { "added": [ "v0.7.10" ] }, "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. Note that\nchild processes may continue running after the parent exits regardless of\nwhether they 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\nthe parent from waiting for a given subprocess, use the subprocess.unref()\nmethod. Doing so will cause the parent's event loop to not include the child in\nits reference count, allowing the parent to exit independently of the child,\nunless there is an established IPC channel between the child and 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').spawn;\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').spawn;\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
\n" }, { "textRaw": "options.stdio", "name": "stdio", "meta": { "added": [ "v0.7.10" ] }, "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

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. '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 created\nfor fds 0 - 2 are also available as subprocess.stdin,\nsubprocess.stdout and subprocess.stderr, respectively.
  2. \n
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the subprocess.send()\nmethod. If the child writes JSON messages to this file descriptor, the\nsubprocess.on('message') event handler will be triggered in\nthe parent. If the child is a Node.js process, the presence of an IPC channel\nwill enable process.send(), process.disconnect(),\nprocess.on('disconnect'), and process.on('message') within the\nchild.
  4. \n
  5. 'ignore' - Instructs Node.js to ignore the fd in the child. While Node.js\nwill always open fds 0 - 2 for the processes it spawns, setting the fd to\n'ignore' will cause Node.js to open /dev/null and attach it to the\nchild's fd.
  6. \n
  7. {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. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'\nevent has occurred).
  8. \n
  9. Positive integer - The integer value is interpreted as a file descriptor\nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how {Stream} objects can be shared.
  10. \n
  11. 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'.
  12. \n
\n

Example:

\n
const spawn = require('child_process').spawn;\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 process.on('disconnect') event\nor the process.on('message') event. This allows the child to exit\nnormally without the process being held open by the open IPC channel.

\n

See also: child_process.exec() and child_process.fork()

\n" } ] } ], "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\nthe Node.js event loop, pausing execution of any additional code until the\nspawned process 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.

\n", "methods": [ { "textRaw": "child_process.execFileSync(file[, args][, options])", "type": "method", "name": "execFileSync", "meta": { "added": [ "v0.11.12" ] }, "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.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer} The value which will be passed as stdin to the spawned process. ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "string|Buffer", "desc": "The value which will be passed as stdin to the spawned process." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. **Default:** `'pipe'` ", "options": [ { "textRaw": "`stderr` by default will be output to the parent process' stderr unless `stdio` is specified ", "name": "stderr", "desc": "by default will be output to the parent process' stderr unless `stdio` is specified" } ], "name": "stdio", "type": "string|Array", "desc": "Child's stdio configuration. **Default:** `'pipe'`" }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "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", "desc": "In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`" }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'` ", "name": "killSignal", "type": "string|integer", "desc": "The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`" }, { "textRaw": "[`maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. ", "name": "[", "desc": "maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'` ", "name": "encoding", "type": "string", "desc": "The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

The child_process.execFileSync() method is generally identical to\nchild_process.execFile() 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. Note that if the child process intercepts and handles\nthe SIGTERM signal and does not exit, the parent process will still wait\nuntil the child process has exited.

\n

If the process times out, or has a non-zero exit code, this method will\nthrow an Error that will include the full result of the underlying\nchild_process.spawnSync().

\n" }, { "textRaw": "child_process.execSync(command[, options])", "type": "method", "name": "execSync", "meta": { "added": [ "v0.11.12" ] }, "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} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer} The value which will be passed as stdin to the spawned process. ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "string|Buffer", "desc": "The value which will be passed as stdin to the spawned process." }, { "textRaw": "`stdio` {string|Array} Child's stdio configuration. **Default:** `'pipe'` ", "options": [ { "textRaw": "`stderr` by default will be output to the parent process' stderr unless `stdio` is specified ", "name": "stderr", "desc": "by default will be output to the parent process' stderr unless `stdio` is specified" } ], "name": "stdio", "type": "string|Array", "desc": "Child's stdio configuration. **Default:** `'pipe'`" }, { "textRaw": "`env` {Object} Environment key-value pairs. ", "name": "env", "type": "Object", "desc": "Environment key-value pairs." }, { "textRaw": "`shell` {string} Shell to execute the command with. **Default:** `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows. The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`. ", "name": "shell", "type": "string", "desc": "Shell to execute the command with. **Default:** `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows. The shell should understand the `-c` switch on UNIX or `/s /c` on Windows. On Windows, command line parsing should be compatible with `cmd.exe`." }, { "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", "desc": "In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`" }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'` ", "name": "killSignal", "type": "string|integer", "desc": "The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`" }, { "textRaw": "[`maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. ", "name": "[", "desc": "maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'` ", "name": "encoding", "type": "string", "desc": "The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true } ] } ], "desc": "

The child_process.execSync() method is generally identical to\nchild_process.exec() with the exception that the method will not return until\nthe child process has fully closed. When a timeout has been encountered and\nkillSignal is sent, the method won't return until the process has completely\nexited. Note that if the child process intercepts and handles the SIGTERM\nsignal and doesn't exit, the parent process will wait until the child\nprocess has exited.

\n

If the process times out, or has a non-zero exit code, this method will\nthrow. The Error object will contain the entire result from\nchild_process.spawnSync()

\n

Note: Never pass unsanitised user input to this function. Any input\ncontaining shell metacharacters may be used to trigger arbitrary command\nexecution.

\n" }, { "textRaw": "child_process.spawnSync(command[, args][, options])", "type": "method", "name": "spawnSync", "meta": { "added": [ "v0.11.12" ] }, "signatures": [ { "return": { "textRaw": "Returns: {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} The exit code of the child process. ", "name": "status", "type": "number", "desc": "The exit code of the child process." }, { "textRaw": "`signal` {string} The signal used to kill the child process. ", "name": "signal", "type": "string", "desc": "The signal used to kill the child process." }, { "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." } ], "name": "return", "type": "Object" }, "params": [ { "textRaw": "`command` {string} The command to run. ", "name": "command", "type": "string", "desc": "The command to run." }, { "textRaw": "`args` {Array} List of string arguments. ", "name": "args", "type": "Array", "desc": "List of string arguments.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {string} Current working directory of the child process. ", "name": "cwd", "type": "string", "desc": "Current working directory of the child process." }, { "textRaw": "`input` {string|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]`. ", "name": "supplying", "desc": "this value will override `stdio[0]`." } ], "name": "input", "type": "string|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "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. ", "name": "env", "type": "Object", "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", "desc": "In milliseconds the maximum amount of time the process is allowed to run. **Default:** `undefined`" }, { "textRaw": "`killSignal` {string|integer} The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'` ", "name": "killSignal", "type": "string|integer", "desc": "The signal value to be used when the spawned process will be killed. **Default:** `'SIGTERM'`" }, { "textRaw": "[`maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed. ", "name": "[", "desc": "maxBuffer`][] {number} Largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed." }, { "textRaw": "`encoding` {string} The encoding used for all stdio inputs and outputs. **Default:** `'buffer'` ", "name": "encoding", "type": "string", "desc": "The encoding used for all stdio inputs and outputs. **Default:** `'buffer'`" }, { "textRaw": "`shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX, or `/s /c` on Windows. **Default:** to `false` (no shell). ", "name": "shell", "type": "boolean|string", "desc": "If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX, or `/s /c` on Windows. **Default:** to `false` (no shell)." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "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. Note that if the process intercepts and handles the\nSIGTERM signal and doesn't exit, the parent process will wait until the child\nprocess has exited.

\n

Note: If the shell option is enabled, do not pass unsanitised user input to\nthis function. Any input containing shell metacharacters may be used to\ntrigger arbitrary command execution.

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

\n\n\n", "type": "module", "displayName": "`maxBuffer` and Unicode" } ], "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "meta": { "added": [ "v2.2.0" ] }, "desc": "

Instances of the ChildProcess class are EventEmitters that represent\nspawned 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.

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.7.7" ] }, "params": [], "desc": "

The 'close' event is emitted when the stdio streams of a child process have\nbeen closed. This is distinct from the 'exit' event, since multiple\nprocesses might share the same stdio streams.

\n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.2" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "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

Note that the 'exit' event may or may not fire after an error has occurred.\nIf you are listening to both the 'exit' and 'error' events, it is important\nto guard against accidentally invoking handler functions multiple times.

\n

See also subprocess.kill() and subprocess.send().

\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.90" ] }, "params": [], "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

Note that when the 'exit' event is triggered, child process stdio streams\nmight still be open.

\n

Also, note that Node.js establishes signal handlers for SIGINT and\nSIGTERM and Node.js processes will not terminate immediately due to receipt\nof those signals. Rather, Node.js will perform a sequence of cleanup actions\nand then will re-raise the handled signal.

\n

See waitpid(2).

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.9" ] }, "params": [], "desc": "

The 'message' event is triggered when a child process uses process.send()\nto send messages.

\n

\n" } ], "properties": [ { "textRaw": "`connected` {boolean} Set to `false` after `subprocess.disconnect()` is called. ", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ] }, "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.

\n

\n", "shortDesc": "Set to `false` after `subprocess.disconnect()` is called." }, { "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" ] }, "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.

\n

\n", "shortDesc": "Set to `true` after `subprocess.kill()` is used to successfully send a signal to the child process." }, { "textRaw": "`pid` {number} Integer ", "type": "number", "name": "pid", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Returns the process identifier (PID) of the child process.

\n

Example:

\n
const spawn = require('child_process').spawn;\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
\n

\n", "shortDesc": "Integer" }, { "textRaw": "`stderr` {stream.Readable} ", "type": "stream.Readable", "name": "stderr", "meta": { "added": [ "v0.1.90" ] }, "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

\n" }, { "textRaw": "`stdin` {stream.Writable} ", "type": "stream.Writable", "name": "stdin", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A Writable Stream that represents the child process's stdin.

\n

Note that if a child process waits to read all of its input, the child will not\ncontinue until 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

\n" }, { "textRaw": "`stdio` {Array} ", "type": "Array", "name": "stdio", "meta": { "added": [ "v0.7.10" ] }, "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'. Note that subprocess.stdio[0], subprocess.stdio[1],\nand subprocess.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

\n" }, { "textRaw": "`stdout` {stream.Readable} ", "type": "stream.Readable", "name": "stdout", "meta": { "added": [ "v0.1.90" ] }, "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" } ], "methods": [ { "textRaw": "subprocess.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ] }, "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

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

\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "subprocess.kill([signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`signal` {string} ", "name": "signal", "type": "string", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "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.

\n
const spawn = require('child_process').spawn;\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 cannot be\ndelivered. Sending a signal to a child process that has already exited is not\nan error but may have unforeseen consequences. Specifically, if the process\nidentifier (PID) has been reassigned to another process, the signal will be\ndelivered to that process instead which can have unexpected results.

\n

Note that while the function is called kill, the signal delivered to the\nchild process may not actually terminate the process.

\n

See kill(2) for reference.

\n

Also note: 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 use of the shell option of ChildProcess, such\nas in this example:

\n
'use strict';\nconst spawn = require('child_process').spawn;\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 process in the shell\n}, 2000);\n
\n" }, { "textRaw": "subprocess.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle} ", "name": "sendHandle", "type": "Handle", "optional": true }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "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\nprocess.on('message') event.

\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\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\nprocess.send({ foo: 'bar' });\n
\n

Child Node.js processes will have a process.send() method of their own that\nallows 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 process.on('message')\nevent. Rather, such messages are emitted using the\nprocess.on('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 process.on('message') event. Any data that is received\nand buffered in the socket will not be sent to the child.

\n

The options argument, if present, is an object used to parameterize the\nsending of certain types of handles. options supports the following\nproperties:

\n\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 happen,\nfor 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 of\nserver.listen(). This is, however, currently only supported on UNIX platforms.

\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

Once a socket has been passed to a child, the parent is no longer capable of\ntracking when the socket is destroyed. To indicate this, the .connections\nproperty becomes null. It is recommended not to use .maxConnections when\nthis occurs.

\n

It is also recommended that any 'message' handlers in the child process\nverify that socket exists, as the connection may have been closed during the\ntime it takes to send the connection to the child.

\n

Note: this function uses JSON.stringify() internally to serialize the\nmessage.

\n

\n" } ] } ], "type": "module", "displayName": "Child Process" }, { "textRaw": "Cluster", "name": "cluster", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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 you to easily create child processes that\nall share server ports.

\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${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\nMaster 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n
\n

Please note that on Windows, it is not yet possible to set up a named pipe\nserver in a worker.

\n", "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 master 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 master 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 master\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 master,\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 master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  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. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

There is no routing logic in Node.js, or in your program, and no shared\nstate between the workers. Therefore, it is important to design your\nprogram such that it does not rely too heavily on in-memory data objects\nfor things like sessions and login.

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your 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 for you, however. It is your\nresponsibility to manage the worker pool for your application's 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.

\n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "meta": { "added": [ "v0.7.0" ] }, "desc": "

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.

\n", "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "desc": "

Similar to the cluster.on('disconnect') event, but specific to this worker.

\n
cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});\n
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.7.3" ] }, "desc": "

This event is the same as the one provided by child_process.fork().

\n

In a worker you can also use process.on('error').

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.11.2" ] }, "params": [], "desc": "

Similar to the cluster.on('exit') event, but specific to this worker.

\n
const 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" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

Similar to the cluster.on('listening') event, but specific to this worker.

\n
cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});\n
\n

It is not emitted in the worker.

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

Similar to the cluster.on('message') event, but specific to this worker. In a\nworker you can also use process.on('message').

\n

See process event: 'message'.

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:

\n
const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\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 master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}\n
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ] }, "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.

\n", "params": [] } ], "methods": [ { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "return": { "textRaw": "Returns: {cluster.Worker} A reference to `worker`. ", "name": "return", "type": "cluster.Worker", "desc": "A reference to `worker`." }, "params": [] }, { "params": [] } ], "desc": "

In a worker, this function will close all servers, wait for the 'close' event on\nthose servers, and then disconnect the IPC channel.

\n

In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.

\n

Causes .exitedAfterDisconnect to be set.

\n

Note that 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 to\ndie 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

Note that 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.isMaster) {\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
\n" }, { "textRaw": "worker.isConnected()", "type": "method", "name": "isConnected", "meta": { "added": [ "v0.11.14" ] }, "desc": "

This function returns true if the worker is connected to its master via its IPC\nchannel, false otherwise. A worker is connected to its master after it's been\ncreated. It is disconnected after the 'disconnect' event is emitted.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.isDead()", "type": "method", "name": "isDead", "meta": { "added": [ "v0.11.14" ] }, "desc": "

This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`signal` {string} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "string", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "default": "'SIGTERM'" } ] } ], "desc": "

This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.

\n

Causes .exitedAfterDisconnect to be set.

\n

This method is aliased as worker.destroy() for backwards compatibility.

\n

Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.

\n" }, { "textRaw": "worker.send(message[, sendHandle][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.7.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle} ", "name": "sendHandle", "type": "Handle", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Send a message to a worker or master, optionally with a handle.

\n

In the master this sends a message to a specific worker. It is identical to\nChildProcess.send().

\n

In a worker this sends a message to the master. It is identical to\nprocess.send().

\n

This example will echo back all messages from the master:

\n
if (cluster.isMaster) {\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
\n" } ], "properties": [ { "textRaw": "`exitedAfterDisconnect` {boolean} ", "type": "boolean", "name": "exitedAfterDisconnect", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Set by calling .kill() or .disconnect(). Until then, it is undefined.

\n

The boolean worker.exitedAfterDisconnect lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis 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
\n" }, { "textRaw": "`id` {number} ", "type": "number", "name": "id", "meta": { "added": [ "v0.8.0" ] }, "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

\n" }, { "textRaw": "`process` {ChildProcess} ", "type": "ChildProcess", "name": "process", "meta": { "added": [ "v0.7.0" ] }, "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

Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .exitedAfterDisconnect is not true. This protects against\naccidental disconnection.

\n" }, { "textRaw": "worker.suicide", "name": "suicide", "meta": { "added": [ "v0.7.0" ], "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`worker.exitedAfterDisconnect`][] instead.", "desc": "

An alias to worker.exitedAfterDisconnect.

\n

Set by calling .kill() or .disconnect(). Until then, it is undefined.

\n

The boolean worker.suicide lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis value.

\n
cluster.on('exit', (worker, code, signal) => {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just voluntary – no need to worry');\n  }\n});\n\n// kill worker\nworker.kill();\n
\n

This API only exists for backwards compatibility and will be removed in the\nfuture.

\n" } ] } ], "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.9" ] }, "params": [], "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 events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.

\n
cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});\n
\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.7.9" ] }, "params": [], "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(\n  'exit',\n  (worker, code, signal) => {\n    console.log('worker %d died (%s). restarting...',\n                worker.process.pid, signal || code);\n    cluster.fork();\n  }\n);\n
\n

See child_process event: 'exit'.

\n" }, { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "meta": { "added": [ "v0.7.0" ] }, "params": [], "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 your own 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
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

After calling listen() from a worker, when the 'listening' event is emitted on\nthe server, a 'listening' event will also be emitted on cluster in the master.

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non 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" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Emitted when the cluster master receives a message from any worker.

\n

See child_process event: 'message'.

\n

Before Node.js v6.0, this event emitted only the message and the handle,\nbut not the worker object, contrary to what the documentation stated.

\n

If you need to support older versions and don't need the worker object,\nyou can work around the discrepancy by checking the number of arguments:

\n
cluster.on('message', (worker, message, handle) => {\n  if (arguments.length === 2) {\n    handle = message;\n    message = worker;\n    worker = undefined;\n  }\n  // ...\n});\n
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster 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
\n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "meta": { "added": [ "v0.7.1" ] }, "params": [], "desc": "

Emitted every time .setupMaster() is called.

\n

The settings object is the cluster.settings object at the time\n.setupMaster() was called and is advisory only, since multiple calls to\n.setupMaster() can be made in a single tick.

\n

If accuracy is important, use cluster.settings.

\n" } ], "methods": [ { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "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.", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

Calls .disconnect() on each worker in cluster.workers.

\n

When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.

\n

The method takes an optional callback argument which will be called when finished.

\n

This can only be called from the master process.

\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "meta": { "added": [ "v0.6.0" ] }, "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.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

Spawn a new worker process.

\n

This can only be called from the master process.

\n" }, { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "meta": { "added": [ "v0.7.1" ] }, "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {string} file path to worker file. **Default:** `process.argv[1]` ", "name": "exec", "type": "string", "desc": "file path to worker file. **Default:** `process.argv[1]`" }, { "textRaw": "`args` {Array} string arguments passed to worker. **Default:**: `process.argv.slice(2)` ", "name": "args", "type": "Array", "desc": "string arguments passed to worker. **Default:**: `process.argv.slice(2)`" }, { "textRaw": "`silent` {boolean} whether or not to send output to parent's stdio. **Default:** `false` ", "name": "silent", "type": "boolean", "desc": "whether or not to send output to parent's stdio. **Default:** `false`" }, { "textRaw": "`stdio` {Array} Configures the stdio of forked processes. When this option is provided, it overrides `silent`. ", "name": "stdio", "type": "Array", "desc": "Configures the stdio of forked processes. When this option is provided, it overrides `silent`." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.

\n

Note that:

\n\n

Example:

\n
const cluster = require('cluster');\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'https'],\n  silent: true\n});\ncluster.fork(); // https worker\ncluster.setupMaster({\n  exec: 'worker.js',\n  args: ['--use', 'http']\n});\ncluster.fork(); // http worker\n
\n

This can only be called from the master process.

\n" } ], "properties": [ { "textRaw": "`isMaster` {boolean} ", "type": "boolean", "name": "isMaster", "meta": { "added": [ "v0.8.1" ] }, "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.

\n" }, { "textRaw": "`isWorker` {boolean} ", "type": "boolean", "name": "isWorker", "meta": { "added": [ "v0.6.0" ] }, "desc": "

True if the process is not a master (it is the negation of cluster.isMaster).

\n" }, { "textRaw": "cluster.schedulingPolicy", "name": "schedulingPolicy", "meta": { "added": [ "v0.11.2" ] }, "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 you spawn the first worker\nor call cluster.setupMaster(), whatever 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'.

\n" }, { "textRaw": "`settings` {Object} ", "type": "Object", "name": "settings", "meta": { "added": [ "v0.7.1" ] }, "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the Node.js executable. **Default:** `process.execArgv` ", "name": "execArgv", "type": "Array", "desc": "list of string arguments passed to the Node.js executable. **Default:** `process.execArgv`" }, { "textRaw": "`exec` {string} file path to worker file. **Default:** `process.argv[1]` ", "name": "exec", "type": "string", "desc": "file path to worker file. **Default:** `process.argv[1]`" }, { "textRaw": "`args` {Array} string arguments passed to worker. **Default:**: `process.argv.slice(2)` ", "name": "args", "type": "Array", "desc": "string arguments passed to worker. **Default:**: `process.argv.slice(2)`" }, { "textRaw": "`silent` {boolean} whether or not to send output to parent's stdio. **Default:** `false` ", "name": "silent", "type": "boolean", "desc": "whether or not to send output to parent's stdio. **Default:** `false`" }, { "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))" } ], "desc": "

After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.

\n

This object is not supposed to be changed or set manually, by you.

\n" }, { "textRaw": "`worker` {Object} ", "type": "Object", "name": "worker", "meta": { "added": [ "v0.7.0" ] }, "desc": "

A reference to the current worker object. Not available in the master process.

\n
const cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log(`I am worker #${cluster.worker.id}`);\n}\n
\n" }, { "textRaw": "`workers` {Object} ", "type": "Object", "name": "workers", "meta": { "added": [ "v0.7.0" ] }, "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 master\nprocess.

\n

A worker is removed from cluster.workers after the worker has disconnected and\nexited. The order between these two events cannot be determined in advance.\nHowever, it is guaranteed that the removal from the cluster.workers list happens\nbefore last 'disconnect' or 'exit' event is emitted.

\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

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.

\n
socket.on('data', (id) => {\n  const worker = cluster.workers[id];\n});\n
\n\n\n" } ], "type": "module", "displayName": "Cluster" }, { "textRaw": "Console", "name": "console", "introduced_in": "v0.10.13", "stability": 2, "stabilityText": "Stable", "desc": "

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

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: Whoops, something bad happened], to stderr\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
\n", "classes": [ { "textRaw": "Class: Console", "type": "class", "name": "Console", "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:

\n
const Console = require('console').Console;\n
\n
const Console = console.Console;\n
\n", "methods": [ { "textRaw": "console.assert(value[, message][, ...args])", "type": "method", "name": "assert", "meta": { "added": [ "v0.1.101" ] }, "desc": "

A simple assertion test that verifies whether value is truthy. If it is not,\nan AssertionError is thrown. If provided, the error message is formatted\nusing util.format() and used as the error message.

\n
console.assert(true, 'does nothing');\n// OK\nconsole.assert(false, 'Whoops %s', 'didn\\'t work');\n// AssertionError: Whoops didn't work\n
\n

Note: the console.assert() method is implemented differently in Node.js\nthan the console.assert() method available in browsers.

\n

Specifically, in browsers, calling console.assert() with a falsy\nassertion will cause the message to be printed to the console without\ninterrupting execution of subsequent code. In Node.js, however, a falsy\nassertion will cause an AssertionError to be thrown.

\n

Functionality approximating that implemented by browsers can be implemented\nby extending Node.js' console and overriding the console.assert() method.

\n

In the following example, a simple module is created that extends and overrides\nthe default behavior of console in Node.js.

\n
'use strict';\n\n// Creates a simple extension of console with a\n// new impl for assert without monkey-patching.\nconst myConsole = Object.create(console, {\n  assert: {\n    value(assertion, message, ...args) {\n      try {\n        console.assert(assertion, message, ...args);\n      } catch (err) {\n        console.error(err.stack);\n      }\n    },\n    configurable: true,\n    enumerable: true,\n    writable: true,\n  },\n});\n\nmodule.exports = myConsole;\n
\n

This can then be used as a direct replacement for the built in console:

\n
const console = require('./myConsole');\nconsole.assert(false, 'this message will print, but no error thrown');\nconsole.log('this will also print');\n
\n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message", "optional": true }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "console.clear()", "type": "method", "name": "clear", "meta": { "added": [ "v6.13.0" ] }, "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

Note: The specific operation of console.clear() can vary across operating\nsystems and 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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "console.count([label])", "type": "method", "name": "count", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} The display label for the counter. Defaults to `'default'`. ", "name": "label", "type": "string", "desc": "The display label for the counter. Defaults to `'default'`.", "optional": true } ] }, { "params": [ { "name": "label", "optional": true } ] } ], "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
\n" }, { "textRaw": "console.countReset([label = 'default'])", "type": "method", "name": "countReset", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} The display label for the counter. Defaults to `'default'`. ", "name": "label", "type": "string", "desc": "The display label for the counter. Defaults to `'default'`.", "optional": true, "default": " 'default'" } ] }, { "params": [ { "name": "label ", "optional": true, "default": " 'default'" } ] } ], "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
\n\n" }, { "textRaw": "console.dir(obj[, options])", "type": "method", "name": "dir", "meta": { "added": [ "v0.1.101" ] }, "signatures": [ { "params": [ { "textRaw": "`obj` {any} ", "name": "obj", "type": "any" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`showHidden` {boolean} ", "name": "showHidden", "type": "boolean" }, { "textRaw": "`depth` {number} ", "name": "depth", "type": "number" }, { "textRaw": "`colors` {boolean} ", "name": "colors", "type": "boolean" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "obj" }, { "name": "options", "optional": true } ] } ], "desc": "

Uses util.inspect() on obj and prints the resulting string to stdout.\nThis function bypasses any custom inspect() function defined on obj. An\noptional options object may be passed to alter certain aspects of the\nformatted string:

\n\n" }, { "textRaw": "console.error([data][, ...args])", "type": "method", "name": "error", "meta": { "added": [ "v0.1.100" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "console.info([data][, ...args])", "type": "method", "name": "info", "meta": { "added": [ "v0.1.100" ] }, "desc": "

The console.info() function is an alias for console.log().

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "console.log([data][, ...args])", "type": "method", "name": "log", "meta": { "added": [ "v0.1.100" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "meta": { "added": [ "v0.1.104" ] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} ", "name": "label", "type": "string" } ] }, { "params": [ { "name": "label" } ] } ], "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 you call\nconsole.timeEnd() to stop the timer and output the elapsed time in\nmilliseconds to stdout. Timer durations are accurate to the sub-millisecond.

\n" }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "meta": { "added": [ "v0.1.104" ] }, "signatures": [ { "params": [ { "textRaw": "`label` {string} ", "name": "label", "type": "string" } ] }, { "params": [ { "name": "label" } ] } ], "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
\n

Note: As of Node.js v6.0.0, console.timeEnd() deletes the timer to avoid\nleaking it. On older versions, the timer persisted. This allowed\nconsole.timeEnd() to be called multiple times for the same label. This\nfunctionality was unintended and is no longer supported.

\n" }, { "textRaw": "console.trace(message[, ...args])", "type": "method", "name": "trace", "meta": { "added": [ "v0.1.104" ] }, "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
\n", "signatures": [ { "params": [ { "name": "message" }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "console.warn([data][, ...args])", "type": "method", "name": "warn", "meta": { "added": [ "v0.1.100" ] }, "desc": "

The console.warn() function is an alias for console.error().

\n\n\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...args", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "stdout" }, { "name": "stderr", "optional": true } ], "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(output, 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(process.stdout, process.stderr);\n
\n" } ] } ], "type": "module", "displayName": "Console" }, { "textRaw": "Crypto", "name": "crypto", "introduced_in": "v0.3.6", "stability": 2, "stabilityText": "Stable", "desc": "

The crypto module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.

\n

Use require('crypto') to access this module.

\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
\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, calling require('crypto') will result in an\nerror being thrown.

\n
let crypto;\ntry {\n  crypto = require('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\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": "crypto.constants", "name": "constants", "meta": { "added": [ "v6.3.0" ] }, "desc": "

Returns an object containing commonly used constants for crypto and security\nrelated operations. The specific constants currently defined are described in\nCrypto Constants.

\n" }, { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ] }, "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 backwards compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.

\n

New applications should expect the default to be 'buffer'. This property may\nbecome deprecated in a future Node.js release.

\n" }, { "textRaw": "crypto.fips", "name": "fips", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Property for checking and controlling whether a FIPS compliant crypto provider is\ncurrently in use. Setting to true requires a FIPS build of Node.js.

\n" } ], "methods": [ { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Creates and returns a Cipher object that uses the given algorithm and\npassword.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable 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 or a Buffer.

\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 PBKDF2 instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.pbkdf2() 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.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv)", "type": "method", "name": "createCipheriv", "desc": "

Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable 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 or\nbuffers.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "meta": { "added": [ "v0.1.92" ], "deprecated": [ "v0.11.13" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.createSecureContext()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`details` {Object} Identical to [`tls.createSecureContext()`][]. ", "name": "details", "type": "Object", "desc": "Identical to [`tls.createSecureContext()`][]." } ] }, { "params": [ { "name": "details" } ] } ], "desc": "

The crypto.createCredentials() method is a deprecated function for creating\nand returning a tls.SecureContext. It should not be used. Replace it with\ntls.createSecureContext() which has the exact same arguments and return\nvalue.

\n

Returns a tls.SecureContext, as-if tls.createSecureContext() had been\ncalled.

\n" }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Creates and returns a Decipher object that uses the given algorithm and\npassword (key).

\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 PBKDF2 instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.pbkdf2() and to use crypto.createDecipheriv()\nto create the Decipher object.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable 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.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.11.12" ] }, "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

The prime_encoding and generator_encoding arguments can be 'latin1',\n'hex', or 'base64'.

\n

If prime_encoding is specified, prime is expected to be a string; otherwise\na Buffer is expected.

\n

If generator_encoding is specified, generator is expected to be a string;\notherwise either a number or Buffer is expected.

\n", "signatures": [ { "params": [ { "name": "prime" }, { "name": "prime_encoding", "optional": true }, { "name": "generator", "optional": true }, { "name": "generator_encoding", "optional": true } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime_length[, generator])", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Creates a DiffieHellman key exchange object and generates a prime of\nprime_length bits using an optional specific numeric generator.\nIf generator is not specified, the value 2 is used.

\n", "signatures": [ { "params": [ { "name": "prime_length" }, { "name": "generator", "optional": true } ] } ] }, { "textRaw": "crypto.createECDH(curve_name)", "type": "method", "name": "createECDH", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curve_name 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.

\n", "signatures": [ { "params": [ { "name": "curve_name" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm.

\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-message-digest-algorithms will\ndisplay the available digest algorithms.

\n

Example: generating the sha256 sum of a file

\n
const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\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", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Creates and returns an Hmac object that uses the given algorithm and key.

\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-message-digest-algorithms will\ndisplay the available digest algorithms.

\n

The key is the HMAC key used to generate the cryptographic HMAC hash.

\n

Example: generating the sha256 HMAC of a file

\n
const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\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", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Creates and returns a Sign object that uses the given algorithm.\nUse crypto.getHashes() to obtain an array of names of the available\nsigning algorithms.

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "meta": { "added": [ "v0.1.92" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Returns an array with the names of the supported cipher algorithms.

\n

Example:

\n
const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getCurves()", "type": "method", "name": "getCurves", "meta": { "added": [ "v2.3.0" ] }, "desc": "

Returns an array with the names of the supported elliptic curves.

\n

Example:

\n
const curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "meta": { "added": [ "v0.7.5" ] }, "desc": "

Creates a predefined DiffieHellman 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 crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.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", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Returns an array of the names of the supported hash algorithms,\nsuch as RSA-SHA256.

\n

Example:

\n
const hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)", "type": "method", "name": "pbkdf2", "meta": { "added": [ "v0.5.5" ] }, "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, err will be set; otherwise err will be\nnull. The successfully generated derivedKey will be passed as a Buffer.

\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 also be as unique as possible. It is recommended that the\nsalts are random and their lengths are at least 16 bytes. See\nNIST SP 800-132 for details.

\n

Example:

\n
const crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {\n  if (err) throw err;\n  console.log(key.toString('hex'));  // '3745e48...aa39b34'\n});\n
\n

An array of supported digest functions can be retrieved using\ncrypto.getHashes().

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest" }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)", "type": "method", "name": "pbkdf2Sync", "meta": { "added": [ "v0.9.3" ] }, "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

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 also be as unique as possible. It is recommended that the\nsalts are random and their lengths are at least 16 bytes. See\nNIST SP 800-132 for details.

\n

Example:

\n
const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...aa39b34'\n
\n

An array of supported digest functions can be retrieved using\ncrypto.getHashes().

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest" } ] } ] }, { "textRaw": "crypto.privateDecrypt(private_key, buffer)", "type": "method", "name": "privateDecrypt", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Decrypts buffer with private_key.

\n

private_key can be an object or a string. If private_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING.\nIf private_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

All paddings are defined in crypto.constants.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.timingSafeEqual(a, b)", "type": "method", "name": "timingSafeEqual", "meta": { "added": [ "v6.6.0" ] }, "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, and they must have the same length.

\n

Note: Use of crypto.timingSafeEqual does not guarantee that the\nsurrounding code is timing-safe. Care should be taken to ensure that the\nsurrounding code does not introduce timing vulnerabilities.

\n", "signatures": [ { "params": [ { "name": "a" }, { "name": "b" } ] } ] }, { "textRaw": "crypto.privateEncrypt(private_key, buffer)", "type": "method", "name": "privateEncrypt", "meta": { "added": [ "v1.1.0" ] }, "desc": "

Encrypts buffer with private_key.

\n

private_key can be an object or a string. If private_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_PADDING.\nIf private_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

All paddings are defined in crypto.constants.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicDecrypt(public_key, buffer)", "type": "method", "name": "publicDecrypt", "meta": { "added": [ "v1.1.0" ] }, "desc": "

Decrypts buffer with public_key.

\n

public_key can be an object or a string. If public_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_PADDING.\nIf public_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

\n

All paddings are defined in crypto.constants.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicEncrypt(public_key, buffer)", "type": "method", "name": "publicEncrypt", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Encrypts buffer with public_key.

\n

public_key can be an object or a string. If public_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING.\nIf public_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.

\n

All paddings are defined in crypto.constants.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.randomBytes(size[, callback])", "type": "method", "name": "randomBytes", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Generates cryptographically strong pseudo-random 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 crypto = require('crypto');\ncrypto.randomBytes(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 buf = crypto.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", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.randomFillSync(buffer[, offset][, size])", "type": "method", "name": "randomFillSync", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|Uint8Array} Must be supplied. ", "name": "buffer", "type": "Buffer|Uint8Array", "desc": "Must be supplied." }, { "textRaw": "`offset` {number} Defaults to `0`. ", "name": "offset", "type": "number", "desc": "Defaults to `0`.", "optional": true }, { "textRaw": "`size` {number} Defaults to `buffer.length - offset`. ", "name": "size", "type": "number", "desc": "Defaults to `buffer.length - offset`.", "optional": true } ] }, { "params": [ { "name": "buffer" }, { "name": "offset", "optional": true }, { "name": "size", "optional": true } ] } ], "desc": "

Synchronous version of crypto.randomFill().

\n

Returns buffer

\n
const buf = Buffer.alloc(10);\nconsole.log(crypto.randomFillSync(buf).toString('hex'));\n\ncrypto.randomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\ncrypto.randomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
\n" }, { "textRaw": "crypto.randomFill(buffer[, offset][, size], callback)", "type": "method", "name": "randomFill", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|Uint8Array} Must be supplied. ", "name": "buffer", "type": "Buffer|Uint8Array", "desc": "Must be supplied." }, { "textRaw": "`offset` {number} Defaults to `0`. ", "name": "offset", "type": "number", "desc": "Defaults to `0`.", "optional": true }, { "textRaw": "`size` {number} Defaults to `buffer.length - offset`. ", "name": "size", "type": "number", "desc": "Defaults to `buffer.length - offset`.", "optional": true }, { "textRaw": "`callback` {Function} `function(err, buf) {}`. ", "name": "callback", "type": "Function", "desc": "`function(err, buf) {}`." } ] }, { "params": [ { "name": "buffer" }, { "name": "offset", "optional": true }, { "name": "size", "optional": true }, { "name": "callback" } ] } ], "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
const buf = Buffer.alloc(10);\ncrypto.randomFill(buf, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\ncrypto.randomFill(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:\ncrypto.randomFill(buf, 5, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n
\n" }, { "textRaw": "crypto.setEngine(engine[, flags])", "type": "method", "name": "setEngine", "meta": { "added": [ "v0.11.11" ] }, "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", "signatures": [ { "params": [ { "name": "engine" }, { "name": "flags", "optional": true } ] } ] } ], "type": "module", "displayName": "`crypto` module methods and properties" }, { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Legacy Streams API (pre Node.js v0.10)", "name": "legacy_streams_api_(pre_node.js_v0.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.

\n", "type": "module", "displayName": "Legacy Streams API (pre Node.js v0.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.

\n", "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 considered to be\ntoo weak for safe use.

\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

See the reference for other recommendations and details.

\n", "type": "module", "displayName": "Support for weak or compromised algorithms" } ], "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.

\n", "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
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 for\n detail.
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_QUERY_MTU
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_PKCS1_CHECK_1
SSL_OP_PKCS1_CHECK_2
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.
\n\n", "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 \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_ECDHLimit engine usage to ECDH
ENGINE_METHOD_ECDSALimit engine usage to ECDSA
ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
ENGINE_METHOD_STORELimit engine usage to STORE
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
\n\n", "type": "module", "displayName": "OpenSSL Engine Constants" }, { "textRaw": "Other OpenSSL Constants", "name": "other_openssl_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
ConstantDescription
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
NPN_ENABLED
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 digest size\n when signing or verifying.
RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the maximum\n permissible value when signing data.
RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be determined\n automatically when verifying a signature.
POINT_CONVERSION_COMPRESSED
POINT_CONVERSION_UNCOMPRESSED
POINT_CONVERSION_HYBRID
\n\n", "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.
\n\n\n\n\n", "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" ] }, "desc": "

SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and now specified formally as part of HTML5's keygen element.

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

\n", "methods": [ { "textRaw": "new crypto.Certificate()", "type": "method", "name": "Certificate", "desc": "

Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:

\n
const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "certificate.exportChallenge(spkac)", "type": "method", "name": "exportChallenge", "meta": { "added": [ "v0.11.8" ] }, "desc": "

The spkac data structure includes a public key and a challenge. The\ncertificate.exportChallenge() returns the challenge component in the\nform of a Node.js Buffer. The spkac argument can be either a string\nor a Buffer.

\n
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
\n", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.exportPublicKey(spkac)", "type": "method", "name": "exportPublicKey", "meta": { "added": [ "v0.11.8" ] }, "desc": "

The spkac data structure includes a public key and a challenge. The\ncertificate.exportPublicKey() returns the public key component in the\nform of a Node.js Buffer. The spkac argument can be either a string\nor a Buffer.

\n
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.verifySpkac(spkac)", "type": "method", "name": "verifySpkac", "meta": { "added": [ "v0.11.8" ] }, "desc": "

Returns true if the given spkac data structure is valid, false otherwise.\nThe spkac argument must be a Node.js Buffer.

\n
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n", "signatures": [ { "params": [ { "name": "spkac" } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:

\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 crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = '';\ncipher.on('readable', () => {\n  const data = cipher.read();\n  if (data)\n    encrypted += data.toString('hex');\n});\ncipher.on('end', () => {\n  console.log(encrypted);\n  // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n});\n\ncipher.write('some clear text data');\ncipher.end();\n
\n

Example: Using Cipher and piped streams:

\n
const crypto = require('crypto');\nconst fs = require('fs');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nconst input = fs.createReadStream('test.js');\nconst output = fs.createWriteStream('test.enc');\n\ninput.pipe(cipher).pipe(output);\n
\n

Example: Using the cipher.update() and cipher.final() methods:

\n
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n
\n", "methods": [ { "textRaw": "cipher.final([output_encoding])", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Returns any remaining enciphered contents. If output_encoding\nparameter is one of 'latin1', 'base64' or 'hex', a string is returned.\nIf an output_encoding is not provided, a Buffer is returned.

\n

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.

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAAD(buffer)", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

Returns this for method chaining.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "cipher.getAuthTag()", "type": "method", "name": "getAuthTag", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the cipher.getAuthTag() method returns a Buffer containing\nthe authentication tag that has been computed from the given data.

\n

The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ] }, "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 auto_padding 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 cipher.final().

\n

Returns this for method chaining.

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "cipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the cipher with data. If the input_encoding argument is given,\nits value must be one of 'utf8', 'ascii', or 'latin1' and the data\nargument is a string using the specified encoding. If the input_encoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then input_encoding is ignored.

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'latin1', 'base64' or 'hex'. If the output_encoding\nis specified, a string using the specified encoding is returned. If no\noutput_encoding 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.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:

\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
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n  const data = decipher.read();\n  if (data)\n    decrypted += data.toString('utf8');\n});\ndecipher.on('end', () => {\n  console.log(decrypted);\n  // Prints: some clear text data\n});\n\nconst encrypted =\n  'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
\n

Example: Using Decipher and piped streams:

\n
const crypto = require('crypto');\nconst fs = require('fs');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nconst input = fs.createReadStream('test.enc');\nconst output = fs.createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
\n

Example: Using the decipher.update() and decipher.final() methods:

\n
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nconst encrypted =\n  'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
\n", "methods": [ { "textRaw": "decipher.final([output_encoding])", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Returns any remaining deciphered contents. If output_encoding\nparameter is one of 'latin1', 'ascii' or 'utf8', a string is returned.\nIf an output_encoding is not provided, a Buffer is returned.

\n

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.

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAAD(buffer)", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

Returns this for method chaining.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAuthTag(buffer)", "type": "method", "name": "setAuthTag", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), 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.

\n

Returns this for method chaining.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ] }, "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.update().

\n

Returns this for method chaining.

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "decipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the decipher with data. If the input_encoding argument is given,\nits value must be one of 'latin1', 'base64', or 'hex' and the data\nargument is a string using the specified encoding. If the input_encoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then input_encoding is ignored.

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'latin1', 'ascii' or 'utf8'. If the output_encoding\nis specified, a string using the specified encoding is returned. If no\noutput_encoding 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.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "meta": { "added": [ "v0.5.0" ] }, "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
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.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", "methods": [ { "textRaw": "diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified input_encoding, and secret is\nencoded using specified output_encoding. Encodings can be\n'latin1', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a Buffer.

\n

If output_encoding is given a string is returned; otherwise, a\nBuffer is returned.

\n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.5.0" ] }, "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. Encoding can be 'latin1', 'hex',\nor 'base64'. If encoding is provided a string is returned; otherwise a\nBuffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman generator in the specified encoding, which can\nbe 'latin1', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'latin1', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'latin1', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'latin1', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Sets the Diffie-Hellman private key. If the encoding argument is provided\nand is either 'latin1', 'hex', or 'base64', private_key is expected\nto be a string. If no encoding is provided, private_key is expected\nto be a Buffer.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Sets the Diffie-Hellman public key. If the encoding argument is provided\nand is either 'latin1', 'hex' or 'base64', public_key is expected\nto be a string. If no encoding is provided, public_key is expected\nto be a Buffer.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "diffieHellman.verifyError", "name": "verifyError", "meta": { "added": [ "v0.11.12" ] }, "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" } ] }, { "textRaw": "Class: ECDH", "type": "class", "name": "ECDH", "meta": { "added": [ "v0.11.14" ] }, "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
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.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", "methods": [ { "textRaw": "ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified input_encoding, and the returned secret\nis encoded using the specified output_encoding. Encodings can be\n'latin1', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a Buffer.

\n

If output_encoding is given a string will be returned; otherwise a\nBuffer is returned.

\n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.generateKeys([encoding[, format]])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.11.14" ] }, "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 arguments specifies point encoding and can be 'compressed',\n'uncompressed', or 'hybrid'. If format is not specified, the point will\nbe returned in 'uncompressed' format.

\n

The encoding argument can be 'latin1', 'hex', or 'base64'. If\nencoding is provided a string is returned; otherwise a Buffer\nis returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Returns the EC Diffie-Hellman private key in the specified encoding,\nwhich can be 'latin1', 'hex', or 'base64'. If encoding is provided\na string is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.getPublicKey([encoding[, format]])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Returns the EC Diffie-Hellman public key in the specified encoding and\nformat.

\n

The format argument specifies point encoding and can be 'compressed',\n'uncompressed', or 'hybrid'. If format is not specified the point will be\nreturned in 'uncompressed' format.

\n

The encoding argument can be 'latin1', 'hex', or 'base64'. If\nencoding is specified, a string is returned; otherwise a Buffer is\nreturned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Sets the EC Diffie-Hellman private key. The encoding can be 'latin1',\n'hex' or 'base64'. If encoding is provided, private_key is expected\nto be a string; otherwise private_key is expected to be a Buffer. If\nprivate_key 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.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.11.14" ], "deprecated": [ "v5.2.0" ] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

Sets the EC Diffie-Hellman public key. Key encoding can be 'latin1',\n'hex' or 'base64'. If encoding is provided public_key is expected to\nbe a string; otherwise a Buffer is expected.

\n

Note that 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 crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.createECDH('secp256k1');\n\n// Note: This is a shortcut way to specify 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  crypto.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", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "meta": { "added": [ "v0.1.92" ] }, "desc": "

The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:

\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 crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\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
const crypto = require('crypto');\nconst fs = require('fs');\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hash).pipe(process.stdout);\n
\n

Example: Using the hash.update() and hash.digest() methods:

\n
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
\n", "methods": [ { "textRaw": "hash.digest([encoding])", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method). The encoding can be 'hex', 'latin1' or\n'base64'. If 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.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hash.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the hash content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'latin1'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

This can be called many times with new data as it is streamed.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ] }, "desc": "

The Hmac Class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:

\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 crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\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
const crypto = require('crypto');\nconst fs = require('fs');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hmac).pipe(process.stdout);\n
\n

Example: Using the hmac.update() and hmac.digest() methods:

\n
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
\n", "methods": [ { "textRaw": "hmac.digest([encoding])", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Calculates the HMAC digest of all of the data passed using hmac.update().\nThe encoding can be 'hex', 'latin1' or 'base64'. If 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.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hmac.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the Hmac content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'latin1'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

This can be called many times with new data as it is streamed.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ] }, "desc": "

The Sign Class is a utility for generating signatures. It can be used in one\nof two ways:

\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 objects as streams:

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('SHA256');\n\nsign.write('some data to sign');\nsign.end();\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature using the specified private key and\n// SHA-256. For RSA keys, the algorithm is RSASSA-PKCS1-v1_5 (see padding\n// parameter below for RSASSA-PSS). For EC keys, the algorithm is ECDSA.\n
\n

Example: Using the sign.update() and sign.sign() methods:

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('SHA256');\n\nsign.update('some data to sign');\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n
\n

In some cases, a Sign instance can also be created by passing in a signature\nalgorithm name, such as 'RSA-SHA256'. This will use the corresponding digest\nalgorithm. This does not work for all signature algorithms, such as\n'ecdsa-with-SHA256'. Use digest names instead.

\n

Example: signing using legacy signature algorithm name

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.update('some data to sign');\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n
\n", "methods": [ { "textRaw": "sign.sign(private_key[, output_format])", "type": "method", "name": "sign", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.12.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "desc": "

Calculates the signature on all the data passed through using either\nsign.update() or sign.write().

\n

The private_key argument can be an object or a string. If private_key is a\nstring, it is treated as a raw key with no passphrase. If private_key is an\nobject, it must contain one or more of the following properties:

\n\n

The output_format can specify one of 'latin1', 'hex' or 'base64'. If\noutput_format is provided a string is returned; otherwise a Buffer is\nreturned.

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

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] }, { "textRaw": "sign.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the Sign content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'latin1'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

This can be called many times with new data as it is streamed.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ] }, "desc": "

The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:

\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

Example: Using Verify objects as streams:

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('SHA256');\n\nverify.write('some data to sign');\nverify.end();\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n
\n

Example: Using the verify.update() and verify.verify() methods:

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('SHA256');\n\nverify.update('some data to sign');\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n
\n", "methods": [ { "textRaw": "verifier.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the Verify content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'latin1'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

This can be called many times with new data as it is streamed.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "verifier.verify(object, signature[, signature_format])", "type": "method", "name": "verify", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.12.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "params": [ { "textRaw": "`object` {string | Object} ", "name": "object", "type": "string | Object" }, { "textRaw": "`signature` {string | Buffer | Uint8Array} ", "name": "signature", "type": "string | Buffer | Uint8Array" }, { "textRaw": "`signature_format` {string} ", "name": "signature_format", "type": "string", "optional": true } ] }, { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ], "desc": "

Verifies the provided data using the given object and signature.\nThe object argument can be either a string containing a PEM encoded object,\nwhich can be an RSA public key, a DSA public key, or an X.509 certificate,\nor an object with one or more of the following properties:

\n\n

The signature argument is the previously calculated signature for the data, in\nthe signature_format which can be 'latin1', 'hex' or 'base64'.\nIf a signature_format is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer.

\n

Returns true or false depending on the validity of the signature for\nthe data and public key.

\n

The verifier 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" } ] } ], "type": "module", "displayName": "Crypto" }, { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The dgram module provides an implementation of UDP Datagram sockets.

\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// server listening 0.0.0.0:41234\n
\n", "classes": [ { "textRaw": "Class: dgram.Socket", "type": "class", "name": "dgram.Socket", "meta": { "added": [ "v0.1.99" ] }, "desc": "

The dgram.Socket object is an EventEmitter that encapsulates the\ndatagram 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.

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.99" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.1.99" ] }, "params": [], "desc": "

The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.

\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.1.99" ] }, "desc": "

The 'listening' event is emitted whenever a socket begins listening for\ndatagram messages. This occurs as soon as UDP sockets are created.

\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.1.99" ] }, "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", "params": [] } ], "methods": [ { "textRaw": "socket.addMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "addMembership", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {string} ", "name": "multicastAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string} ", "name": "multicastInterface", "type": "string", "optional": true } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "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 sharing a UDP socket across multiple cluster workers, the\nsocket.addMembership() function must be called only once or an\nEADDRINUSE error will occur:

\n
const cluster = require('cluster');\nconst dgram = require('dgram');\nif (cluster.isMaster) {\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" }, { "textRaw": "socket.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.1.99" ] }, "desc": "

Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.bind([port][, address][, callback])", "type": "method", "name": "bind", "meta": { "added": [ "v0.1.99" ] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Integer. ", "name": "port", "type": "number", "desc": "Integer.", "optional": true }, { "textRaw": "`address` {string} ", "name": "address", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} with no parameters. Called when binding is complete. ", "name": "callback", "type": "Function", "desc": "with no parameters. Called when binding is complete.", "optional": true } ] }, { "params": [ { "name": "port", "optional": true }, { "name": "address", "optional": true }, { "name": "callback", "optional": true } ] } ], "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

Note that 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
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// server listening 0.0.0.0:41234\n
\n" }, { "textRaw": "socket.bind(options[, callback])", "type": "method", "name": "bind", "meta": { "added": [ "v0.11.14" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} 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" } ], "name": "options", "type": "Object", "desc": "Required. Supports the following properties:" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "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

Note that 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\nuse 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
\n" }, { "textRaw": "socket.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.1.99" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.dropMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "dropMembership", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {string} ", "name": "multicastAddress", "type": "string" }, { "textRaw": "`multicastInterface` {string} ", "name": "multicastInterface", "type": "string", "optional": true } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "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.

\n" }, { "textRaw": "socket.send(msg, [offset, length,] port, address[, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.1.99" ] }, "signatures": [ { "params": [ { "textRaw": "`msg` {Buffer|string|array} Message to be sent. ", "name": "msg", "type": "Buffer|string|array", "desc": "Message to be sent." }, { "textRaw": "`offset` {number} Integer. Offset in the buffer where the message starts. ", "name": "offset", "type": "number", "desc": "Integer. Offset in the buffer where the message starts.", "optional": true }, { "textRaw": "`length` {number} Integer. Number of bytes in the message. ", "name": "length", "type": "number", "desc": "Integer. Number of bytes in the message.", "optional": true }, { "textRaw": "`port` {number} Integer. Destination port. ", "name": "port", "type": "number", "desc": "Integer. Destination port." }, { "textRaw": "`address` {string} Destination hostname or IP address. ", "name": "address", "type": "string", "desc": "Destination hostname 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.", "optional": true } ] }, { "params": [ { "name": "msg" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

Broadcasts a datagram on the socket. The destination port and address must\nbe specified.

\n

The msg argument contains the message to be sent.\nDepending on its type, different behavior can apply. If msg is a Buffer,\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 the address is not\nspecified or is an empty string, '127.0.0.1' or '::1' will be used instead.

\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.\nNote that DNS 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 if you specify one you would need to\nspecify the other. Also, they are supported only when the first\nargument is a Buffer.

\n

Example of sending a UDP packet to a random port on localhost;

\n
const dgram = require('dgram');\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 random port on localhost;

\n
const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, 'localhost', (err) => {\n  client.close();\n});\n
\n

Sending multiple buffers might be faster or slower depending on your\napplication and operating system: benchmark it. Usually it is faster.

\n

A Note about UDP datagram size

\n

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

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.

\n" }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "meta": { "added": [ "v0.6.9" ] }, "signatures": [ { "params": [ { "textRaw": "`flag` {boolean} ", "name": "flag", "type": "boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "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" }, { "textRaw": "socket.setMulticastInterface(multicastInterface)", "type": "method", "name": "setMulticastInterface", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`multicastInterface` {String} ", "name": "multicastInterface", "type": "String" } ] }, { "params": [ { "name": "multicastInterface" } ] } ], "desc": "

Note: All references to scope in this section are refering 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 or\ninterface 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

Examples: 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
\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 omiting 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.

\n", "type": "module", "displayName": "Call Results" } ] }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "meta": { "added": [ "v0.3.8" ] }, "signatures": [ { "params": [ { "textRaw": "`flag` {boolean} ", "name": "flag", "type": "boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "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" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "meta": { "added": [ "v0.3.8" ] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {number} Integer. ", "name": "ttl", "type": "number", "desc": "Integer." } ] }, { "params": [ { "name": "ttl" } ] } ], "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 argument passed to to socket.setMulticastTTL() is a number of hops\nbetween 0 and 255. The default on most systems is 1 but can vary.

\n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "meta": { "added": [ "v0.1.101" ] }, "signatures": [ { "params": [ { "textRaw": "`ttl` {number} Integer. ", "name": "ttl", "type": "number", "desc": "Integer." } ] }, { "params": [ { "name": "ttl" } ] } ], "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 argument to socket.setTTL() is a number of hops between 1 and 255.\nThe default on most systems is 64 but can vary.

\n" }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ] }, "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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ] }, "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.

\n", "signatures": [ { "params": [] } ] } ], "modules": [ { "textRaw": "Change to asynchronous `socket.bind()` behavior", "name": "change_to_asynchronous_`socket.bind()`_behavior", "desc": "

As of Node.js v0.10, dgram.Socket#bind() changed to an asynchronous\nexecution model. Legacy code that assumes synchronous behavior, as in the\nfollowing example:

\n
const s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');\n
\n

Must be changed to pass a callback function to the dgram.Socket#bind()\nfunction:

\n
const s = dgram.createSocket('udp4');\ns.bind(1234, () => {\n  s.addMembership('224.0.0.114');\n});\n
\n", "type": "module", "displayName": "Change to asynchronous `socket.bind()` behavior" } ] } ], "modules": [ { "textRaw": "`dgram` module functions", "name": "`dgram`_module_functions", "methods": [ { "textRaw": "dgram.createSocket(options[, callback])", "type": "method", "name": "createSocket", "meta": { "added": [ "v0.11.13" ] }, "signatures": [ { "return": { "textRaw": "Returns: {dgram.Socket} ", "name": "return", "type": "dgram.Socket" }, "params": [ { "textRaw": "`options` {Object} ", "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} Attached as a listener to `'message'` events. ", "name": "callback", "type": "Function", "desc": "Attached as a listener to `'message'` events.", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

Creates a dgram.Socket object. The options argument is an object that\nshould contain a type field of either udp4 or udp6 and an optional\nboolean reuseAddr field.

\n

When reuseAddr is true socket.bind() will reuse the address, even if\nanother process has already bound a socket on it. reuseAddr defaults to\nfalse. The optional callback function is added as a listener for 'message'\nevents.

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

\n" }, { "textRaw": "dgram.createSocket(type[, callback])", "type": "method", "name": "createSocket", "meta": { "added": [ "v0.1.99" ] }, "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.", "optional": true } ] }, { "params": [ { "name": "type" }, { "name": "callback", "optional": true } ] } ], "desc": "

Creates a dgram.Socket object of the specified type. The type argument\ncan be either udp4 or udp6. An optional callback function can be passed\nwhich is added as a listener for 'message' events.

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

\n\n\n" } ], "type": "module", "displayName": "`dgram` module functions" } ], "type": "module", "displayName": "dgram" }, { "textRaw": "DNS", "name": "dns", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The dns module contains functions belonging to two different categories:

\n

1) Functions that use the underlying operating system facilities to perform\nname resolution, and that do not necessarily perform any network communication.\nThis category contains only one function: dns.lookup(). Developers\nlooking to perform name resolution in the same way that other applications on\nthe same operating system behave should use dns.lookup().

\n

For example, looking up iana.org.

\n
const dns = require('dns');\n\ndns.lookup('nodejs.org', (err, addresses, family) => {\n  console.log('addresses:', addresses);\n});\n// address: "192.0.43.8" family: IPv4\n
\n

2) Functions that connect to an actual DNS server to perform name resolution,\nand that always use the network to perform DNS queries. This category\ncontains all functions in the dns module except dns.lookup(). These\nfunctions do not use the same set of configuration files used by\ndns.lookup() (e.g. /etc/hosts). These functions should be used by\ndevelopers who do not want to use the underlying operating system's facilities\nfor name resolution, and instead want to always perform DNS queries.

\n

Below is an example that resolves 'archive.org' then reverse resolves the IP\naddresses that are returned.

\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

There are subtle consequences in choosing one over the other, please consult\nthe Implementation considerations section for more information.

\n", "methods": [ { "textRaw": "dns.getServers()", "type": "method", "name": "getServers", "meta": { "added": [ "v0.11.3" ] }, "desc": "

Returns an array of IP address strings that are being used for name\nresolution.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "dns.lookup(hostname[, options], callback)", "type": "method", "name": "lookup", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Resolves a hostname (e.g. 'nodejs.org') into the first found A (IPv4) or\nAAAA (IPv6) record. options can be an object or integer. If options is\nnot provided, then IPv4 and IPv6 addresses are both valid. If options is\nan integer, then it must be 4 or 6.

\n

Alternatively, options can be an object containing these properties:

\n\n

All properties are optional.

\n

The callback function has arguments (err, address, family). address is a\nstring representation of an IPv4 or IPv6 address. family is either the\ninteger 4 or 6 and denotes the family of address (not necessarily the\nvalue initially passed to lookup).

\n

With the all option set to true, the arguments 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 'ENOENT' not only when\nthe hostname 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", "modules": [ { "textRaw": "Supported getaddrinfo flags", "name": "supported_getaddrinfo_flags", "desc": "

The following flags can be passed as hints to dns.lookup().

\n\n", "type": "module", "displayName": "Supported getaddrinfo flags" } ], "signatures": [ { "params": [ { "name": "hostname" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.lookupService(address, port, callback)", "type": "method", "name": "lookupService", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Resolves the given address and port into a hostname 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

The callback has arguments (err, hostname, service). The hostname and\nservice arguments are strings (e.g. 'localhost' and 'http' respectively).

\n

On 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", "signatures": [ { "params": [ { "name": "address" }, { "name": "port" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve(hostname[, rrtype], callback)", "type": "method", "name": "resolve", "meta": { "added": [ "v0.1.27" ] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} Hostname to resolve. ", "name": "hostname", "type": "string", "desc": "Hostname to resolve." }, { "textRaw": "`rrtype` {string} Resource record type. Default: `'A'`. ", "name": "rrtype", "type": "string", "desc": "Resource record type. Default: `'A'`.", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`records` {string[] | Object[] | Object} ", "name": "records", "type": "string[] | Object[] | Object" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "hostname" }, { "name": "rrtype", "optional": true }, { "name": "callback" } ] } ], "desc": "

Uses the DNS protocol to resolve a hostname (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
rrtyperecords containsResult typeShorthand method
'A'IPv4 addresses (default){string}dns.resolve4()
'AAAA'IPv6 addresses{string}dns.resolve6()
'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.

\n" }, { "textRaw": "dns.resolve4(hostname[, options], callback)", "type": "method", "name": "resolve4", "meta": { "added": [ "v0.1.16" ] }, "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']).

\n\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve6(hostname[, options], callback)", "type": "method", "name": "resolve6", "meta": { "added": [ "v0.1.16" ] }, "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.

\n\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveCname(hostname, callback)", "type": "method", "name": "resolveCname", "meta": { "added": [ "v0.3.2" ] }, "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']).

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveMx(hostname, callback)", "type": "method", "name": "resolveMx", "meta": { "added": [ "v0.1.27" ] }, "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'}, ...]).

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNaptr(hostname, callback)", "type": "method", "name": "resolveNaptr", "meta": { "added": [ "v0.9.12" ] }, "desc": "

Uses the DNS protocol to resolve regular expression based records (NAPTR\nrecords) for the hostname. The callback function has arguments\n(err, addresses). The addresses argument passed to the callback function\nwill contain an array of objects with the following properties:

\n\n

For example:

\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
\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNs(hostname, callback)", "type": "method", "name": "resolveNs", "meta": { "added": [ "v0.1.90" ] }, "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']).

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSoa(hostname, callback)", "type": "method", "name": "resolveSoa", "meta": { "added": [ "v0.11.10" ] }, "desc": "

Uses the DNS protocol to resolve a start of authority record (SOA record) for\nthe hostname. The addresses argument passed to the callback function will\nbe an object with the following properties:

\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
\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSrv(hostname, callback)", "type": "method", "name": "resolveSrv", "meta": { "added": [ "v0.1.27" ] }, "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\n
{\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}\n
\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolvePtr(hostname, callback)", "type": "method", "name": "resolvePtr", "meta": { "added": [ "v6.0.0" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveTxt(hostname, callback)", "type": "method", "name": "resolveTxt", "meta": { "added": [ "v0.1.27" ] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} ", "name": "hostname", "type": "string" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`records` {string[]} ", "name": "records", "type": "string[]" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ], "desc": "

Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. The records argument passed to the callback function is a\ntwo-dimensional array of the text records available for hostname (e.g.,\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.

\n" }, { "textRaw": "dns.reverse(ip, callback)", "type": "method", "name": "reverse", "meta": { "added": [ "v0.1.16" ] }, "desc": "

Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of hostnames.

\n

The callback function has arguments (err, hostnames), where hostnames\nis an array of resolved hostnames for the given ip.

\n

On error, err is an Error object, where err.code is\none of the DNS error codes.

\n", "signatures": [ { "params": [ { "name": "ip" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.setServers(servers)", "type": "method", "name": "setServers", "meta": { "added": [ "v0.11.3" ] }, "desc": "

Sets the IP addresses of the servers to be used when resolving. The servers\nargument is an array of IPv4 or IPv6 addresses.

\n

If a port specified on the address it will be removed.

\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", "signatures": [ { "params": [ { "name": "servers" } ] } ] } ], "modules": [ { "textRaw": "Error codes", "name": "error_codes", "desc": "

Each DNS query can return one of the following error codes:

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

\n", "modules": [ { "textRaw": "`dns.lookup()`", "name": "`dns.lookup()`", "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 note that 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\nruns on libuv's threadpool. Because libuv's threadpool has a fixed size, it\nmeans that if for whatever reason the call to getaddrinfo(3) takes a long\ntime, other operations that could run on libuv's threadpool (such as filesystem\noperations) will experience degraded performance. In order to mitigate this\nissue, one potential solution is to increase the size of libuv's threadpool by\nsetting the 'UV_THREADPOOL_SIZE' environment variable to a value greater than\n4 (its current default value). For more information on libuv's threadpool, see\nthe official libuv documentation.

\n", "type": "module", "displayName": "`dns.lookup()`" }, { "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.

\n\n\n", "type": "module", "displayName": "`dns.resolve()`, `dns.resolve*()` and `dns.reverse()`" } ], "type": "module", "displayName": "Implementation considerations" } ], "type": "module", "displayName": "DNS" }, { "textRaw": "Domain", "name": "domain", "introduced_in": "v0.10.0", "stability": 0, "stabilityText": "Deprecated", "desc": "

This module is pending deprecation. Once a replacement API has been\nfinalized, this module will be fully deprecated. Most end users 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.

\n", "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 your\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 you 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, you might have many\nconnections open, 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 master 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  // resources like crazy 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.isMaster) {\n  // In real life, you'd probably use more than just 2 workers,\n  // and perhaps not put the master and worker in the same file.\n  //\n  // You can also of course get a bit fancier about logging, and\n  // implement whatever custom logic you need 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 master 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      // Note: 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 master know we're dead. This will trigger a\n        // 'disconnect' in the cluster master, 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// You'd put your 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
\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" }, { "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

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.

\n

Implicit binding routes thrown errors and 'error' events to the\nDomain's 'error' event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.

\n" }, { "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

For example:

\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
\n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "Returns: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

Returns a new Domain object.

\n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.

\n

Domain is a child class of EventEmitter. To handle the errors that it\ncatches, listen to its 'error' event.

\n", "methods": [ { "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", "optional": true } ] }, { "params": [ { "name": "fn" }, { "name": "...args", "optional": true } ] } ], "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

Example:

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

\n" }, { "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" } ] }, { "params": [ { "name": "emitter" } ] } ], "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.

\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" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.

\n" }, { "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" } ] }, { "params": [ { "name": "callback" } ] } ], "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

Example

\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.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
\n" }, { "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" } ] }, { "params": [ { "name": "callback" } ] } ], "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

Example

\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.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});\n
\n" }, { "textRaw": "domain.enter()", "type": "method", "name": "enter", "desc": "

The enter method is plumbing used by the run, bind, and intercept\nmethods to set the active domain. It sets domain.active and process.domain\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit() for details on the domain stack). The\ncall to enter delimits the beginning of a chain of asynchronous calls and I/O\noperations 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.

\n

If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.exit()", "type": "method", "name": "exit", "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.

\n

If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "domain.dispose()", "type": "method", "name": "dispose", "desc": "

Stability: 0 - Deprecated. Please recover from failed IO actions\nexplicitly via error event handlers set on the domain.

\n

Once dispose has been called, the domain will no longer be used by callbacks\nbound into the domain via run, bind, or intercept, and a 'dispose' event\nis emitted.

\n\n\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`members` {Array} ", "type": "Array", "name": "members", "desc": "

An array of timers and event emitters that have been explicitly added\nto the domain.

\n" } ] } ], "type": "module", "displayName": "Domain" }, { "textRaw": "Events", "name": "Events", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "type": "module", "desc": "

Much of the Node.js core API is built around an idiomatic asynchronous\nevent-driven architecture in which certain kinds of objects (called "emitters")\nperiodically emit named events that cause Function objects ("listeners") to be\ncalled.

\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 will be 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
\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. It is important to keep in mind that when an\nordinary listener function is called by the EventEmitter, the standard this\nkeyword is intentionally set to reference the EventEmitter to which the\nlistener is attached.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', function(a, b) {\n  console.log(a, b, this);\n  // Prints:\n  //   a b MyEmitter {\n  //     domain: null,\n  //     _events: { event: [Function] },\n  //     _eventsCount: 1,\n  //     _maxListeners: undefined }\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
\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 is important to ensure the proper sequencing of\nevents and to avoid race conditions or 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
\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 will be 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
\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, a listener can be registered\non the process object's uncaughtException event or the domain module\ncan be used. (Note, however, that the domain module has been deprecated)

\n
const myEmitter = new MyEmitter();\n\nprocess.on('uncaughtException', (err) => {\n  console.error('whoops! there was an error');\n});\n\nmyEmitter.emit('error', new Error('whoops!'));\n// Prints: whoops! there was an error\n
\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", "type": "module", "displayName": "Error events" } ], "classes": [ { "textRaw": "Class: EventEmitter", "type": "class", "name": "EventEmitter", "meta": { "added": [ "v0.1.26" ] }, "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", "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "meta": { "added": [ "v0.1.26" ] }, "params": [], "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 will be 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 will be inserted before the\nlistener that is in the process of being added.

\n
const 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
\n" }, { "textRaw": "Event: 'removeListener'", "type": "event", "name": "removeListener", "meta": { "added": [ "v0.9.3" ] }, "params": [], "desc": "

The 'removeListener' event is emitted after the listener is removed.

\n" } ], "methods": [ { "textRaw": "EventEmitter.listenerCount(emitter, eventName)", "type": "method", "name": "listenerCount", "meta": { "added": [ "v0.9.12" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`emitter.listenerCount()`][] instead.", "desc": "

A class method that returns the number of listeners for the given eventName\nregistered on the given emitter.

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n// Prints: 2\n
\n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "eventName" } ] } ] }, { "textRaw": "emitter.addListener(eventName, listener)", "type": "method", "name": "addListener", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Alias for emitter.on(eventName, listener).

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.emit(eventName[, ...args])", "type": "method", "name": "emit", "meta": { "added": [ "v0.1.26" ] }, "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", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "...args", "optional": true } ] } ] }, { "textRaw": "emitter.eventNames()", "type": "method", "name": "eventNames", "meta": { "added": [ "v6.0.0" ] }, "desc": "

Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array will be 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
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "emitter.getMaxListeners()", "type": "method", "name": "getMaxListeners", "meta": { "added": [ "v1.0.0" ] }, "desc": "

Returns the current max listener value for the EventEmitter which is either\nset by emitter.setMaxListeners(n) or defaults to\nEventEmitter.defaultMaxListeners.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "emitter.listenerCount(eventName)", "type": "method", "name": "listenerCount", "meta": { "added": [ "v3.2.0" ] }, "signatures": [ { "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" } ] }, { "params": [ { "name": "eventName" } ] } ], "desc": "

Returns the number of listeners listening to the event named eventName.

\n" }, { "textRaw": "emitter.listeners(eventName)", "type": "method", "name": "listeners", "meta": { "added": [ "v0.1.26" ] }, "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
\n", "signatures": [ { "params": [ { "name": "eventName" } ] } ] }, { "textRaw": "emitter.on(eventName, listener)", "type": "method", "name": "on", "meta": { "added": [ "v0.1.101" ] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event. ", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function ", "name": "listener", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ], "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
\n" }, { "textRaw": "emitter.once(eventName, listener)", "type": "method", "name": "once", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event. ", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function ", "name": "listener", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ], "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
\n" }, { "textRaw": "emitter.prependListener(eventName, listener)", "type": "method", "name": "prependListener", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event. ", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function ", "name": "listener", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ], "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.

\n" }, { "textRaw": "emitter.prependOnceListener(eventName, listener)", "type": "method", "name": "prependOnceListener", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`eventName` {string|symbol} The name of the event. ", "name": "eventName", "type": "string|symbol", "desc": "The name of the event." }, { "textRaw": "`listener` {Function} The callback function ", "name": "listener", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ], "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.

\n" }, { "textRaw": "emitter.removeAllListeners([eventName])", "type": "method", "name": "removeAllListeners", "meta": { "added": [ "v0.1.26" ] }, "desc": "

Removes all listeners, or those of the specified eventName.

\n

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

\n", "signatures": [ { "params": [ { "name": "eventName", "optional": true } ] } ] }, { "textRaw": "emitter.removeListener(eventName, listener)", "type": "method", "name": "removeListener", "meta": { "added": [ "v0.1.26" ] }, "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

Note that once an event has been emitted, all listeners attached to it at the\ntime of emitting will be called in order. This implies that any removeListener()\nor removeAllListeners() calls after emitting and before the last listener\nfinishes execution will not remove them from emit() in progress. Subsequent\nevents will 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

Returns a reference to the EventEmitter, so that calls can be chained.

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "meta": { "added": [ "v0.3.5" ] }, "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. Obviously, not all events should be limited to just 10 listeners.\nThe emitter.setMaxListeners() method allows the limit to be modified for this\nspecific EventEmitter instance. The value can be set to Infinity (or 0)\nto indicate an unlimited number of listeners.

\n

Returns a reference to the EventEmitter, so that calls can be chained.

\n\n\n", "signatures": [ { "params": [ { "name": "n" } ] } ] } ], "properties": [ { "textRaw": "EventEmitter.defaultMaxListeners", "name": "defaultMaxListeners", "meta": { "added": [ "v0.11.2" ] }, "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 EventEmitter.defaultMaxListeners\nproperty can be used.

\n

Take caution when setting the EventEmitter.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 EventEmitter.defaultMaxListeners.

\n

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

\n" } ] } ] }, { "textRaw": "File System", "name": "fs", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.

\n

The asynchronous form always takes a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.

\n

When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.

\n

Here is an example of the asynchronous version:

\n
const fs = require('fs');\n\nfs.unlink('/tmp/hello', (err) => {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});\n
\n

Here is the synchronous version:

\n
const fs = require('fs');\n\nfs.unlinkSync('/tmp/hello');\nconsole.log('successfully deleted /tmp/hello');\n
\n

With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:

\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 could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.

\n
fs.rename('/tmp/hello', '/tmp/world', (err) => {\n  if (err) throw err;\n  fs.stat('/tmp/world', (err, stats) => {\n    if (err) throw err;\n    console.log(`stats: ${JSON.stringify(stats)}`);\n  });\n});\n
\n

In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete — halting all connections.

\n

The relative path to a filename can be used. Remember, however, that this path\nwill be relative to process.cwd().

\n

Most fs functions let you omit the callback argument. If you do, a default\ncallback is used that rethrows errors. To get a trace to the original call\nsite, set the NODE_DEBUG environment variable:

\n
$ cat script.js\nfunction bad() {\n  require('fs').readFile('/');\n}\nbad();\n\n$ env NODE_DEBUG=fs node script.js\nfs.js:88\n        throw backtrace;\n        ^\nError: EISDIR: illegal operation on a directory, read\n    <stack trace.>\n
\n", "modules": [ { "textRaw": "Buffer API", "name": "buffer_api", "meta": { "added": [ "v6.0.0" ] }, "desc": "

fs functions support passing and receiving paths as both strings\nand Buffers. The latter is intended to make it possible to work with\nfilesystems that allow for non-UTF-8 filenames. For most typical\nuses, working with paths as Buffers will be unnecessary, as the string\nAPI converts to and from UTF-8 automatically.

\n

Note that on certain file systems (such as NTFS and HFS+) filenames\nwill always be encoded as UTF-8. On such file systems, passing\nnon-UTF-8 encoded Buffers to fs functions will not work as expected.

\n", "type": "module", "displayName": "Buffer API" }, { "textRaw": "FS Constants", "name": "fs_constants", "desc": "

The following constants are exported by fs.constants. Note: Not every\nconstant will be available on every operating system.

\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.
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.
\n\n", "type": "module", "displayName": "File Access 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
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 the file.\n 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 synchronous I/O.
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.
\n\n", "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.
\n\n", "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.
\n\n\n\n", "type": "module", "displayName": "File Mode Constants" } ], "type": "module", "displayName": "FS Constants" } ], "classes": [ { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Objects returned from fs.watch() are of this type.

\n

The listener callback provided to fs.watch() receives the returned FSWatcher's\nchange events.

\n

The object itself emits these events:

\n", "events": [ { "textRaw": "Event: 'change'", "type": "event", "name": "change", "meta": { "added": [ "v0.5.8" ] }, "params": [], "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 string.

\n
// Example when handled through fs.watch listener\nfs.watch('./tmp', {encoding: 'buffer'}, (eventType, filename) => {\n  if (filename)\n    console.log(filename);\n  // Prints: <Buffer ...>\n});\n
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.5.8" ] }, "params": [], "desc": "

Emitted when an error occurs.

\n" } ], "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Stop watching for changes on the given fs.FSWatcher.

\n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: fs.ReadStream", "type": "class", "name": "fs.ReadStream", "meta": { "added": [ "v0.1.93" ] }, "desc": "

ReadStream is a Readable Stream.

\n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "meta": { "added": [ "v0.1.93" ] }, "params": [], "desc": "

Emitted when the ReadStream's file is opened.

\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ] }, "params": [], "desc": "

Emitted when the ReadStream's underlying file descriptor has been closed.

\n" } ], "properties": [ { "textRaw": "readStream.bytesRead", "name": "bytesRead", "meta": { "added": [ "6.4.0" ] }, "desc": "

The number of bytes read so far.

\n" }, { "textRaw": "readStream.path", "name": "path", "meta": { "added": [ "v0.1.93" ] }, "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.

\n" } ] }, { "textRaw": "Class: fs.Stats", "type": "class", "name": "fs.Stats", "meta": { "added": [ "v0.1.21" ] }, "desc": "

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.

\n\n

For a regular file util.inspect(stats) would return a string very\nsimilar to this:

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

Please note that atime, mtime, birthtime, and ctime are\ninstances of Date object and to compare the values of\nthese objects you should use appropriate methods. For most general\nuses getTime() will return the number of\nmilliseconds elapsed since 1 January 1970 00:00:00 UTC and this\ninteger should be sufficient for any comparison, however there are\nadditional methods which can be used for displaying fuzzy information.\nMore details can be found in the MDN JavaScript Reference\npage.

\n", "modules": [ { "textRaw": "Stat Time Values", "name": "stat_time_values", "desc": "

The times in the stat object have the following semantics:

\n\n

Prior to Node v0.12, the ctime held the birthtime on Windows\nsystems. Note that as of v0.12, ctime is not "creation time", and\non Unix systems, it never was.

\n", "type": "module", "displayName": "Stat Time Values" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "meta": { "added": [ "v0.1.93" ] }, "desc": "

WriteStream is a Writable Stream.

\n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "meta": { "added": [ "v0.1.93" ] }, "params": [], "desc": "

Emitted when the WriteStream's file is opened.

\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ] }, "params": [], "desc": "

Emitted when the WriteStream's underlying file descriptor has been closed.

\n" } ], "properties": [ { "textRaw": "writeStream.bytesWritten", "name": "bytesWritten", "meta": { "added": [ "v0.4.7" ] }, "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.

\n" }, { "textRaw": "writeStream.path", "name": "path", "meta": { "added": [ "v0.1.93" ] }, "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.

\n" } ] } ], "methods": [ { "textRaw": "fs.access(path[, mode], callback)", "type": "method", "name": "access", "meta": { "added": [ "v0.11.15" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ], "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. The following constants define the possible values of\nmode. It is possible to create a mask consisting of the bitwise OR of two or\nmore values.

\n\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 populated. The following example checks if the file\n/etc/passwd can be read and written by the current process.

\n
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {\n  console.log(err ? 'no access!' : 'can read/write');\n});\n
\n

Using fs.access() to check for the accessibility 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 is not accessible.

\n

For example:

\n

write (NOT RECOMMENDED)

\n
fs.access('myfile', (err) => {\n  if (!err) {\n    console.error('myfile already exists');\n    return;\n  }\n\n  fs.open('myfile', 'wx', (err, fd) => {\n    if (err) throw err;\n    writeMyData(fd);\n  });\n});\n
\n

write (RECOMMENDED)

\n
fs.open('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  writeMyData(fd);\n});\n
\n

read (NOT RECOMMENDED)

\n
fs.access('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  fs.open('myfile', 'r', (err, fd) => {\n    if (err) throw err;\n    readMyData(fd);\n  });\n});\n
\n

read (RECOMMENDED)

\n
fs.open('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  readMyData(fd);\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 won’t be\nused directly, for example when its accessibility is a signal from another\nprocess.

\n" }, { "textRaw": "fs.accessSync(path[, mode])", "type": "method", "name": "accessSync", "meta": { "added": [ "v0.11.15" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ], "desc": "

Synchronous version of fs.access(). This throws if any accessibility\nchecks fail, and does nothing otherwise.

\n" }, { "textRaw": "fs.appendFile(file, data[, options], callback)", "type": "method", "name": "appendFile", "meta": { "added": [ "v0.6.7" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string|Buffer|number} filename or file descriptor ", "name": "file", "type": "string|Buffer|number", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer" }, { "textRaw": "`options` {Object|string} ", "options": [ { "textRaw": "`encoding` {string|null} default = `'utf8'` ", "name": "encoding", "type": "string|null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {integer} default = `0o666` ", "name": "mode", "type": "integer", "desc": "default = `0o666`" }, { "textRaw": "`flag` {string} default = `'a'` ", "name": "flag", "type": "string", "desc": "default = `'a'`" } ], "name": "options", "type": "Object|string", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously append data to a file, creating the file if it does not yet exist.\ndata can be a string or a buffer.

\n

Example:

\n
fs.appendFile('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. Example:

\n
fs.appendFile('message.txt', 'data to append', 'utf8', callback);\n
\n

Any specified file descriptor has to have been opened for appending.

\n

Note: If a file descriptor is specified as the file, it will not be closed\nautomatically.

\n" }, { "textRaw": "fs.appendFileSync(file, data[, options])", "type": "method", "name": "appendFileSync", "meta": { "added": [ "v0.6.7" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string|Buffer|number} filename or file descriptor ", "name": "file", "type": "string|Buffer|number", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer" }, { "textRaw": "`options` {Object|string} ", "options": [ { "textRaw": "`encoding` {string|null} default = `'utf8'` ", "name": "encoding", "type": "string|null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {integer} default = `0o666` ", "name": "mode", "type": "integer", "desc": "default = `0o666`" }, { "textRaw": "`flag` {string} default = `'a'` ", "name": "flag", "type": "string", "desc": "default = `'a'`" } ], "name": "options", "type": "Object|string", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true } ] } ], "desc": "

The synchronous version of fs.appendFile(). Returns undefined.

\n" }, { "textRaw": "fs.chmod(path, mode, callback)", "type": "method", "name": "chmod", "meta": { "added": [ "v0.1.30" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ], "desc": "

Asynchronously changes the permissions of a file. No arguments other than a\npossible exception are given to the completion callback.

\n

See also: chmod(2)

\n" }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "meta": { "added": [ "v0.6.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" } ] }, { "params": [ { "name": "path" }, { "name": "mode" } ] } ], "desc": "

Synchronously changes the permissions of a file. Returns undefined.\nThis is the synchronous version of fs.chmod().

\n

See also: chmod(2)

\n" }, { "textRaw": "fs.chown(path, uid, gid, callback)", "type": "method", "name": "chown", "meta": { "added": [ "v0.1.97" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`uid` {integer} ", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer} ", "name": "gid", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ], "desc": "

Asynchronously changes owner and group of a file. No arguments other than a\npossible exception are given to the completion callback.

\n

See also: chown(2)

\n" }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "meta": { "added": [ "v0.1.97" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`uid` {integer} ", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer} ", "name": "gid", "type": "integer" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "

Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().

\n

See also: chown(2)

\n" }, { "textRaw": "fs.close(fd, callback)", "type": "method", "name": "close", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "callback" } ] } ], "desc": "

Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "

Synchronous close(2). Returns undefined.

\n" }, { "textRaw": "fs.createReadStream(path[, options])", "type": "method", "name": "createReadStream", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`flags` {string} ", "name": "flags", "type": "string" }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string" }, { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" }, { "textRaw": "`autoClose` {boolean} ", "name": "autoClose", "type": "boolean" }, { "textRaw": "`start` {integer} ", "name": "start", "type": "integer" }, { "textRaw": "`end` {integer} ", "name": "end", "type": "integer" }, { "textRaw": "`highWaterMark` {integer} ", "name": "highWaterMark", "type": "integer" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ], "desc": "

Returns a new ReadStream object. (See Readable Stream).

\n

Be aware that, unlike the default value set for highWaterMark on a\nreadable stream (16 kb), the stream returned by this method has a\ndefault value of 64 kb for the same parameter.

\n

options is an object or string with the following defaults:

\n
const defaults = {\n  flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0o666,\n  autoClose: true,\n  highWaterMark: 64 * 1024\n};\n
\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. If fd is specified and start is omitted or undefined,\nfs.createReadStream() reads sequentially from the current file position.\nThe encoding can be any one of those accepted by 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. Note that fd should be blocking; non-blocking fds should be passed\nto net.Socket.

\n

If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is your responsibility to close it and make sure\nthere'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
fs.createReadStream('sample.txt', {start: 90, end: 99});\n
\n

If options is a string, then it specifies the encoding.

\n" }, { "textRaw": "fs.createWriteStream(path[, options])", "type": "method", "name": "createWriteStream", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`flags` {string} ", "name": "flags", "type": "string" }, { "textRaw": "`defaultEncoding` {string} ", "name": "defaultEncoding", "type": "string" }, { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" }, { "textRaw": "`autoClose` {boolean} ", "name": "autoClose", "type": "boolean" }, { "textRaw": "`start` {integer} ", "name": "start", "type": "integer" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ], "desc": "

Returns a new WriteStream object. (See Writable Stream).

\n

options is an object or string with the following defaults:

\n
const defaults = {\n  flags: 'w',\n  defaultEncoding: 'utf8',\n  fd: null,\n  mode: 0o666,\n  autoClose: true\n};\n
\n

options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w. The defaultEncoding can be any one of those accepted by\nBuffer.

\n

If autoClose is set to true (default behavior) on error or end\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 your responsibility to close it and make sure\nthere's no file descriptor leak.

\n

Like ReadStream, if fd is specified, WriteStream will ignore the\npath argument and will use the specified file descriptor. This means that no\n'open' event will be emitted. Note that fd should be blocking; non-blocking\nfds should be passed to net.Socket.

\n

If options is a string, then it specifies the encoding.

\n" }, { "textRaw": "fs.exists(path, callback)", "type": "method", "name": "exists", "meta": { "added": [ "v0.0.2" ], "deprecated": [ "v1.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`exists` {Boolean} ", "name": "exists", "type": "Boolean" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "callback" } ] } ], "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. Example:

\n
fs.exists('/etc/passwd', (exists) => {\n  console.log(exists ? 'it\\'s there' : 'no passwd!');\n});\n
\n

Note that the parameter to this callback is not consistent with other\nNode.js callbacks. Normally, the first parameter to a Node.js callback is\nan err parameter, optionally followed by other parameters. The\nfs.exists() callback has only one boolean parameter. This is one reason\nfs.access() is recommended instead 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

For example:

\n

write (NOT RECOMMENDED)

\n
fs.exists('myfile', (exists) => {\n  if (exists) {\n    console.error('myfile already exists');\n  } else {\n    fs.open('myfile', 'wx', (err, fd) => {\n      if (err) throw err;\n      writeMyData(fd);\n    });\n  }\n});\n
\n

write (RECOMMENDED)

\n
fs.open('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  writeMyData(fd);\n});\n
\n

read (NOT RECOMMENDED)

\n
fs.exists('myfile', (exists) => {\n  if (exists) {\n    fs.open('myfile', 'r', (err, fd) => {\n      readMyData(fd);\n    });\n  } else {\n    console.error('myfile does not exist');\n  }\n});\n
\n

read (RECOMMENDED)

\n
fs.open('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  readMyData(fd);\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.

\n" }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "

Synchronous version of fs.exists().\nReturns true if the path exists, false otherwise.

\n

Note that fs.exists() is deprecated, but fs.existsSync() is not.\n(The callback parameter to fs.exists() accepts parameters that are\ninconsistent with other Node.js callbacks. fs.existsSync() does not use\na callback.)

\n" }, { "textRaw": "fs.fchmod(fd, mode, callback)", "type": "method", "name": "fchmod", "meta": { "added": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ], "desc": "

Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.

\n" }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "meta": { "added": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" } ] }, { "params": [ { "name": "fd" }, { "name": "mode" } ] } ], "desc": "

Synchronous fchmod(2). Returns undefined.

\n" }, { "textRaw": "fs.fchown(fd, uid, gid, callback)", "type": "method", "name": "fchown", "meta": { "added": [ "v0.4.7" ] }, "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} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ], "desc": "

Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "meta": { "added": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`uid` {integer} ", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer} ", "name": "gid", "type": "integer" } ] }, { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "

Synchronous fchown(2). Returns undefined.

\n" }, { "textRaw": "fs.fdatasync(fd, callback)", "type": "method", "name": "fdatasync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "callback" } ] } ], "desc": "

Asynchronous fdatasync(2). No arguments other than a possible exception are\ngiven to the completion callback.

\n" }, { "textRaw": "fs.fdatasyncSync(fd)", "type": "method", "name": "fdatasyncSync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "

Synchronous fdatasync(2). Returns undefined.

\n" }, { "textRaw": "fs.fstat(fd, callback)", "type": "method", "name": "fstat", "meta": { "added": [ "v0.1.95" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats} ", "name": "stats", "type": "fs.Stats" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "callback" } ] } ], "desc": "

Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is an fs.Stats object. fstat() is identical to stat(),\nexcept that the file to be stat-ed is specified by the file descriptor fd.

\n" }, { "textRaw": "fs.fstatSync(fd)", "type": "method", "name": "fstatSync", "meta": { "added": [ "v0.1.95" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "

Synchronous fstat(2). Returns an instance of fs.Stats.

\n" }, { "textRaw": "fs.fsync(fd, callback)", "type": "method", "name": "fsync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "callback" } ] } ], "desc": "

Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "

Synchronous fsync(2). Returns undefined.

\n" }, { "textRaw": "fs.ftruncate(fd, len, callback)", "type": "method", "name": "ftruncate", "meta": { "added": [ "v0.8.6" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`len` {integer} default = `0` ", "name": "len", "type": "integer", "desc": "default = `0`" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ], "desc": "

Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.

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

\n
console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// truncate the file to first four bytes\nfs.ftruncate(fd, 4, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt', 'utf8'));\n});\n// Prints: Node\n
\n

If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'). For example,

\n
console.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// truncate the file to 10 bytes, whereas the actual size is 7 bytes\nfs.ftruncate(fd, 10, (err) => {\n  assert.ifError(err);\n  console.log(fs.readFileSync('temp.txt'));\n});\n// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>\n// ('Node.js\\0\\0\\0' in UTF8)\n
\n

The last three bytes are null bytes ('\\0'), to compensate the over-truncation.

\n" }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "meta": { "added": [ "v0.8.6" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`len` {integer} default = `0` ", "name": "len", "type": "integer", "desc": "default = `0`" } ] }, { "params": [ { "name": "fd" }, { "name": "len" } ] } ], "desc": "

Synchronous ftruncate(2). Returns undefined.

\n" }, { "textRaw": "fs.futimes(fd, atime, mtime, callback)", "type": "method", "name": "futimes", "meta": { "added": [ "v0.4.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`atime` {integer} ", "name": "atime", "type": "integer" }, { "textRaw": "`mtime` {integer} ", "name": "mtime", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ], "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.

\n

Note: This function does not work on AIX versions before 7.1, it will return\nthe error UV_ENOSYS.

\n" }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "meta": { "added": [ "v0.4.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`atime` {integer} ", "name": "atime", "type": "integer" }, { "textRaw": "`mtime` {integer} ", "name": "mtime", "type": "integer" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ], "desc": "

Synchronous version of fs.futimes(). Returns undefined.

\n" }, { "textRaw": "fs.lchmod(path, mode, callback)", "type": "method", "name": "lchmod", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ], "desc": "

Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.

\n

Only available on macOS.

\n" }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer" } ] }, { "params": [ { "name": "path" }, { "name": "mode" } ] } ], "desc": "

Synchronous lchmod(2). Returns undefined.

\n" }, { "textRaw": "fs.lchown(path, uid, gid, callback)", "type": "method", "name": "lchown", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`uid` {integer} ", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer} ", "name": "gid", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ], "desc": "

Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`uid` {integer} ", "name": "uid", "type": "integer" }, { "textRaw": "`gid` {integer} ", "name": "gid", "type": "integer" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "

Synchronous lchown(2). Returns undefined.

\n" }, { "textRaw": "fs.link(existingPath, newPath, callback)", "type": "method", "name": "link", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`existingPath` {string|Buffer} ", "name": "existingPath", "type": "string|Buffer" }, { "textRaw": "`newPath` {string|Buffer} ", "name": "newPath", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "existingPath" }, { "name": "newPath" }, { "name": "callback" } ] } ], "desc": "

Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.

\n" }, { "textRaw": "fs.linkSync(existingPath, newPath)", "type": "method", "name": "linkSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`existingPath` {string|Buffer} ", "name": "existingPath", "type": "string|Buffer" }, { "textRaw": "`newPath` {string|Buffer} ", "name": "newPath", "type": "string|Buffer" } ] }, { "params": [ { "name": "existingPath" }, { "name": "newPath" } ] } ], "desc": "

Synchronous link(2). Returns undefined.

\n" }, { "textRaw": "fs.lstat(path, callback)", "type": "method", "name": "lstat", "meta": { "added": [ "v0.1.30" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats} ", "name": "stats", "type": "fs.Stats" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "callback" } ] } ], "desc": "

Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(),\nexcept that if path is a symbolic link, then the link itself is stat-ed,\nnot the file that it refers to.

\n" }, { "textRaw": "fs.lstatSync(path)", "type": "method", "name": "lstatSync", "meta": { "added": [ "v0.1.30" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "

Synchronous lstat(2). Returns an instance of fs.Stats.

\n" }, { "textRaw": "fs.mkdir(path[, mode], callback)", "type": "method", "name": "mkdir", "meta": { "added": [ "v0.1.8" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously creates a directory. No arguments other than a possible exception\nare given to the completion callback. mode defaults to 0o777.

\n

See also: mkdir(2)

\n" }, { "textRaw": "fs.mkdirSync(path[, mode])", "type": "method", "name": "mkdirSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ], "desc": "

Synchronously creates a directory. Returns undefined.\nThis is the synchronous version of fs.mkdir().

\n

See also: mkdir(2)

\n" }, { "textRaw": "fs.mkdtemp(prefix[, options], callback)", "type": "method", "name": "mkdtemp", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "params": [ { "textRaw": "`prefix` {string} ", "name": "prefix", "type": "string" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`folder` {string} ", "name": "folder", "type": "string" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "prefix" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Creates a unique temporary directory.

\n

Generates six random characters to be appended behind a required\nprefix to create a unique temporary directory.

\n

The created folder 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

Example:

\n
fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, folder) => {\n  if (err) throw err;\n  console.log(folder);\n  // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n
\n

Note: The fs.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,\nthe prefix must end with a trailing platform-specific path separator\n(require('path').sep).

\n
// The parent directory for the new temporary directory\nconst tmpDir = os.tmpdir();\n\n// This method is *INCORRECT*:\nfs.mkdtemp(tmpDir, (err, folder) => {\n  if (err) throw err;\n  console.log(folder);\n  // Will print something similar to `/tmpabc123`.\n  // Note that a new temporary directory is created\n  // at the file system root rather than *within*\n  // the /tmp directory.\n});\n\n// This method is *CORRECT*:\nconst { sep } = require('path');\nfs.mkdtemp(`${tmpDir}${sep}`, (err, folder) => {\n  if (err) throw err;\n  console.log(folder);\n  // Will print something similar to `/tmp/abc123`.\n  // A new temporary directory is created within\n  // the /tmp directory.\n});\n
\n" }, { "textRaw": "fs.mkdtempSync(prefix[, options])", "type": "method", "name": "mkdtempSync", "meta": { "added": [ "v5.10.0" ] }, "signatures": [ { "params": [ { "textRaw": "`prefix` {string} ", "name": "prefix", "type": "string" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "prefix" }, { "name": "options", "optional": true } ] } ], "desc": "

The synchronous version of fs.mkdtemp(). Returns the created\nfolder path.

\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" }, { "textRaw": "fs.open(path, flags[, mode], callback)", "type": "method", "name": "open", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`flags` {string|number} ", "name": "flags", "type": "string|number" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronous file open. See open(2). flags can be:

\n\n

mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0o666 (readable and writable).

\n

The callback gets two arguments (err, fd).

\n

The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly\ncreated. On POSIX systems, path is considered to exist even if it is a symlink\nto a non-existent file. The exclusive flag may or may not work with network file\nsystems.

\n

flags 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

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

Note: The behavior of fs.open() is platform-specific for some flags. As such,\nopening a directory on macOS and Linux with the 'a+' flag - see example\nbelow - will return an error. In contrast, on Windows and FreeBSD, a file\ndescriptor will 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

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. eg.\nfs.writeFile(), fs.readFile(), etc.

\n" }, { "textRaw": "fs.openSync(path, flags[, mode])", "type": "method", "name": "openSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`flags` {string|number} ", "name": "flags", "type": "string|number" }, { "textRaw": "`mode` {integer} ", "name": "mode", "type": "integer", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true } ] } ], "desc": "

Synchronous version of fs.open(). Returns an integer representing the file\ndescriptor.

\n" }, { "textRaw": "fs.read(fd, buffer, offset, length, position, callback)", "type": "method", "name": "read", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {string | Buffer} ", "name": "buffer", "type": "string | Buffer" }, { "textRaw": "`offset` {integer} ", "name": "offset", "type": "integer" }, { "textRaw": "`length` {integer} ", "name": "length", "type": "integer" }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`bytesRead` {integer} ", "name": "bytesRead", "type": "integer" }, { "textRaw": "`buffer` {Buffer} ", "name": "buffer", "type": "Buffer" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ], "desc": "

Read data from the file specified by fd.

\n

buffer is the buffer that the data will be written to.

\n

offset is the offset in the buffer to start writing at.

\n

length is an integer specifying the number of bytes to read.

\n

position is an argument specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position,\nand the file position will be updated.\nIf position is an integer, the file position will remain unchanged.

\n

The callback is given the three arguments, (err, bytesRead, buffer).

\n" }, { "textRaw": "fs.readdir(path[, options], callback)", "type": "method", "name": "readdir", "meta": { "added": [ "v0.1.8" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`files` {string[]|Buffer[]} ", "name": "files", "type": "string[]|Buffer[]" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.

\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" }, { "textRaw": "fs.readdirSync(path[, options])", "type": "method", "name": "readdirSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ], "desc": "

Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.

\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" }, { "textRaw": "fs.readFile(file[, options], callback)", "type": "method", "name": "readFile", "meta": { "added": [ "v0.1.29" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string|Buffer|integer} filename or file descriptor ", "name": "file", "type": "string|Buffer|integer", "desc": "filename or file descriptor" }, { "textRaw": "`options` {Object|string} ", "options": [ { "textRaw": "`encoding` {string|null} default = `null` ", "name": "encoding", "type": "string|null", "desc": "default = `null`" }, { "textRaw": "`flag` {string} default = `'r'` ", "name": "flag", "type": "string", "desc": "default = `'r'`" } ], "name": "options", "type": "Object|string", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "file" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously reads the entire contents of a file. Example:

\n
fs.readFile('/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. Example:

\n
fs.readFile('/etc/passwd', 'utf8', callback);\n
\n

Note: When the path is a directory, the behavior of\nfs.readFile() and [fs.readFileSync()][] is platform-specific. On macOS,\nLinux, and Windows, an error will be returned. On FreeBSD, a representation\nof the directory's contents will be returned.

\n
// macOS, Linux and Windows\nfs.readFile('<directory>', (err, data) => {\n  // => [Error: EISDIR: illegal operation on a directory, read <directory>]\n});\n\n//  FreeBSD\nfs.readFile('<directory>', (err, data) => {\n  // => null, <data>\n});\n
\n

Any specified file descriptor has to support reading.

\n

Note: If a file descriptor is specified as the path, it will not be closed\nautomatically.

\n" }, { "textRaw": "fs.readFileSync(file[, options])", "type": "method", "name": "readFileSync", "meta": { "added": [ "v0.1.8" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string|Buffer|integer} filename or file descriptor ", "name": "file", "type": "string|Buffer|integer", "desc": "filename or file descriptor" }, { "textRaw": "`options` {Object|string} ", "options": [ { "textRaw": "`encoding` {string|null} default = `null` ", "name": "encoding", "type": "string|null", "desc": "default = `null`" }, { "textRaw": "`flag` {string} default = `'r'` ", "name": "flag", "type": "string", "desc": "default = `'r'`" } ], "name": "options", "type": "Object|string", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "options", "optional": true } ] } ], "desc": "

Synchronous version of fs.readFile. Returns the contents of the file.

\n

If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.

\n

Note: Similar to [fs.readFile()][], when the path is a directory, the\nbehavior of fs.readFileSync() is platform-specific.

\n
// macOS, Linux and Windows\nfs.readFileSync('<directory>');\n// => [Error: EISDIR: illegal operation on a directory, read <directory>]\n\n//  FreeBSD\nfs.readFileSync('<directory>'); // => null, <data>\n
\n" }, { "textRaw": "fs.readlink(path[, options], callback)", "type": "method", "name": "readlink", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`linkString` {string|Buffer} ", "name": "linkString", "type": "string|Buffer" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).

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

\n" }, { "textRaw": "fs.readlinkSync(path[, options])", "type": "method", "name": "readlinkSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ], "desc": "

Synchronous readlink(2). Returns the symbolic link's string value.

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

\n" }, { "textRaw": "fs.readSync(fd, buffer, offset, length, position)", "type": "method", "name": "readSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {string | Buffer} ", "name": "buffer", "type": "string | Buffer" }, { "textRaw": "`offset` {integer} ", "name": "offset", "type": "integer" }, { "textRaw": "`length` {integer} ", "name": "length", "type": "integer" }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer" } ] }, { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ], "desc": "

Synchronous version of fs.read(). Returns the number of bytesRead.

\n" }, { "textRaw": "fs.realpath(path[, options], callback)", "type": "method", "name": "realpath", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`resolvedPath` {string|Buffer} ", "name": "resolvedPath", "type": "string|Buffer" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronous realpath(3). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to 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" }, { "textRaw": "fs.realpathSync(path[, options])", "type": "method", "name": "realpathSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer}; ", "name": "path", "type": "string|Buffer", "desc": ";" }, { "textRaw": "`options` {string|Object} ", "options": [ { "textRaw": "`encoding` {string} default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ], "desc": "

Synchronous realpath(3). Returns the resolved path.

\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 returned value. If the encoding is set to 'buffer', the path returned\nwill be passed as a Buffer object.

\n" }, { "textRaw": "fs.rename(oldPath, newPath, callback)", "type": "method", "name": "rename", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`oldPath` {string|Buffer} ", "name": "oldPath", "type": "string|Buffer" }, { "textRaw": "`newPath` {string|Buffer} ", "name": "newPath", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ], "desc": "

Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`oldPath` {string|Buffer} ", "name": "oldPath", "type": "string|Buffer" }, { "textRaw": "`newPath` {string|Buffer} ", "name": "newPath", "type": "string|Buffer" } ] }, { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ], "desc": "

Synchronous rename(2). Returns undefined.

\n" }, { "textRaw": "fs.rmdir(path, callback)", "type": "method", "name": "rmdir", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "callback" } ] } ], "desc": "

Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.

\n

Note: Using fs.rmdir() on a file (not a directory) results in an ENOENT\nerror on Windows and an ENOTDIR error on POSIX.

\n" }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "

Synchronous rmdir(2). Returns undefined.

\n

Note: Using fs.rmdirSync() on a file (not a directory) results in an ENOENT\nerror on Windows and an ENOTDIR error on POSIX.

\n" }, { "textRaw": "fs.stat(path, callback)", "type": "method", "name": "stat", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`stats` {fs.Stats} ", "name": "stats", "type": "fs.Stats" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "callback" } ] } ], "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" }, { "textRaw": "fs.statSync(path)", "type": "method", "name": "statSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "

Synchronous stat(2). Returns an instance of fs.Stats.

\n" }, { "textRaw": "fs.symlink(target, path[, type], callback)", "type": "method", "name": "symlink", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`target` {string|Buffer} ", "name": "target", "type": "string|Buffer" }, { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`type` {string} ", "name": "type", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "target" }, { "name": "path" }, { "name": "type", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback. The type argument can be set to 'dir',\n'file', or 'junction' (default is 'file') and is only available on\nWindows (ignored on other platforms). Note that Windows junction points require\nthe destination path to be absolute. When using 'junction', the target\nargument will automatically be normalized to absolute path.

\n

Here is an example below:

\n
fs.symlink('./foo', './new-port', callback);\n
\n

It creates a symbolic link named "new-port" that points to "foo".

\n" }, { "textRaw": "fs.symlinkSync(target, path[, type])", "type": "method", "name": "symlinkSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`target` {string|Buffer} ", "name": "target", "type": "string|Buffer" }, { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`type` {string} ", "name": "type", "type": "string", "optional": true } ] }, { "params": [ { "name": "target" }, { "name": "path" }, { "name": "type", "optional": true } ] } ], "desc": "

Synchronous symlink(2). Returns undefined.

\n" }, { "textRaw": "fs.truncate(path, len, callback)", "type": "method", "name": "truncate", "meta": { "added": [ "v0.8.6" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`len` {integer} default = `0` ", "name": "len", "type": "integer", "desc": "default = `0`" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "len" }, { "name": "callback" } ] } ], "desc": "

Asynchronous truncate(2). 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" }, { "textRaw": "fs.truncateSync(path, len)", "type": "method", "name": "truncateSync", "meta": { "added": [ "v0.8.6" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`len` {integer} default = `0` ", "name": "len", "type": "integer", "desc": "default = `0`" } ] }, { "params": [ { "name": "path" }, { "name": "len" } ] } ], "desc": "

Synchronous truncate(2). Returns undefined. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync() is called.

\n" }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "callback" } ] } ], "desc": "

Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.

\n" }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "

Synchronous unlink(2). Returns undefined.

\n" }, { "textRaw": "fs.unwatchFile(filename[, listener])", "type": "method", "name": "unwatchFile", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`filename` {string|Buffer} ", "name": "filename", "type": "string|Buffer" }, { "textRaw": "`listener` {Function} ", "options": [ { "textRaw": "`eventType` {string} ", "name": "eventType", "type": "string" }, { "textRaw": "`filename` {string|Buffer} ", "name": "filename", "type": "string|Buffer" } ], "name": "listener", "type": "Function", "optional": true } ] }, { "params": [ { "name": "filename" }, { "name": "listener", "optional": true } ] } ], "desc": "

Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.

\n

Note: fs.watch() is more efficient than fs.watchFile() and fs.unwatchFile().\nfs.watch() should be used instead of fs.watchFile() and fs.unwatchFile()\nwhen possible.

\n" }, { "textRaw": "fs.utimes(path, atime, mtime, callback)", "type": "method", "name": "utimes", "meta": { "added": [ "v0.4.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`atime` {integer} ", "name": "atime", "type": "integer" }, { "textRaw": "`mtime` {integer} ", "name": "mtime", "type": "integer" }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ], "desc": "

Change file timestamps of the file referenced by the supplied path.

\n

Note: the arguments atime and mtime of the following related functions\nfollow these rules:

\n\n" }, { "textRaw": "fs.utimesSync(path, atime, mtime)", "type": "method", "name": "utimesSync", "meta": { "added": [ "v0.4.2" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string|Buffer} ", "name": "path", "type": "string|Buffer" }, { "textRaw": "`atime` {integer} ", "name": "atime", "type": "integer" }, { "textRaw": "`mtime` {integer} ", "name": "mtime", "type": "integer" } ] }, { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] } ], "desc": "

Synchronous version of fs.utimes(). Returns undefined.

\n" }, { "textRaw": "fs.watch(filename[, options][, listener])", "type": "method", "name": "watch", "meta": { "added": [ "v0.5.10" ] }, "signatures": [ { "params": [ { "textRaw": "`filename` {string|Buffer} ", "name": "filename", "type": "string|Buffer" }, { "textRaw": "`options` {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", "desc": "Indicates whether the process should continue to run as long as files are being watched. default = `true`" }, { "textRaw": "`recursive` {boolean} Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See [Caveats][]). default = `false` ", "name": "recursive", "type": "boolean", "desc": "Indicates whether all subdirectories should be watched, or only the current directory. The applies when a directory is specified, and only on supported platforms (See [Caveats][]). default = `false`" }, { "textRaw": "`encoding` {string} Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'` ", "name": "encoding", "type": "string", "desc": "Specifies the character encoding to be used for the filename passed to the listener. default = `'utf8'`" } ], "name": "options", "type": "string|Object", "optional": true }, { "textRaw": "`listener` {Function} ", "options": [ { "textRaw": "`eventType` {string} ", "name": "eventType", "type": "string" }, { "textRaw": "`filename` {string|Buffer} ", "name": "filename", "type": "string|Buffer" } ], "name": "listener", "type": "Function", "optional": true } ] }, { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener", "optional": true } ] } ], "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.

\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 is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.

\n

Note that on most platforms, 'rename' is emitted whenever a filename appears\nor disappears in the directory.

\n

Also note the listener callback is attached to the 'change' event fired by\nfs.FSWatcher, but it is not the same thing as the 'change' value of\neventType.

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

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

If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories can be unreliable, and in some cases impossible, on network file\nsystems (NFS, SMB, etc), or host file systems when using virtualization software\nsuch as Vagrant, Docker, etc.

\n

You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.

\n" }, { "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

On AIX, save and close of a file being watched causes two notifications -\none for adding new content, and one for truncation. Moreover, save and\nclose operations on some platforms cause inode changes that force watch\noperations to become invalid and ineffective. AIX retains inode for the\nlifetime of a file, that way though this is different from Linux / OS X,\nthis improves the usability of file watching. This is expected behavior.

\n" }, { "textRaw": "Filename Argument", "name": "Filename Argument", "type": "misc", "desc": "

Providing filename argument in the callback is only supported on Linux and\nWindows. Even on supported platforms, filename is not always guaranteed to\nbe provided. Therefore, don't assume that filename argument is always\nprovided in the callback, and have some fallback logic if it is null.

\n
fs.watch('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
\n" } ] } ] }, { "textRaw": "fs.watchFile(filename[, options], listener)", "type": "method", "name": "watchFile", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`filename` {string|Buffer} ", "name": "filename", "type": "string|Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`persistent` {boolean} ", "name": "persistent", "type": "boolean" }, { "textRaw": "`interval` {integer} ", "name": "interval", "type": "integer" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`listener` {Function} ", "options": [ { "textRaw": "`current` {fs.Stats} ", "name": "current", "type": "fs.Stats" }, { "textRaw": "`previous` {fs.Stats} ", "name": "previous", "type": "fs.Stats" } ], "name": "listener", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener" } ] } ], "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. The default is\n{ persistent: true, interval: 5007 }.

\n

The listener gets two arguments the current stat object and the previous\nstat object:

\n
fs.watchFile('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.

\n

If you want to be notified when the file was modified, not just accessed,\nyou need to compare curr.mtime and prev.mtime.

\n

Note: when an fs.watchFile operation results in an ENOENT error, it will\n invoke the listener once, with all the fields zeroed (or, for dates, the Unix\n Epoch). In Windows, blksize and blocks fields will be undefined, instead\n of zero. If the file is created later on, the listener will be called again,\n with the latest stat objects. This is a change in functionality since v0.10.

\n

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

Note: When a file being watched by fs.watchFile() disappears and reappears,\nthen the previousStat reported in the second callback event (the file's\nreappearance) will be the same as the previousStat of the first callback\nevent (its disappearance).

\n

This happens when:

\n\n" }, { "textRaw": "fs.write(fd, buffer[, offset[, length[, position]]], callback)", "type": "method", "name": "write", "meta": { "added": [ "v0.0.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer} ", "name": "buffer", "type": "Buffer" }, { "textRaw": "`offset` {integer} ", "name": "offset", "type": "integer", "optional": true }, { "textRaw": "`length` {integer} ", "name": "length", "type": "integer", "optional": true }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`bytesWritten` {integer} ", "name": "bytesWritten", "type": "integer" }, { "textRaw": "`buffer` {Buffer|Uint8Array} ", "name": "buffer", "type": "Buffer|Uint8Array" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "position", "optional": true }, { "name": "callback" } ] } ], "desc": "

Write buffer to the file specified by fd.

\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, written, buffer) where\nwritten specifies how many bytes were written from buffer.

\n

Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.

\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" }, { "textRaw": "fs.write(fd, string[, position[, encoding]], callback)", "type": "method", "name": "write", "meta": { "added": [ "v0.11.5" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`string` {string} ", "name": "string", "type": "string" }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer", "optional": true }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`written` {integer} ", "name": "written", "type": "integer" }, { "textRaw": "`string` {string} ", "name": "string", "type": "string" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "string" }, { "name": "position", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback" } ] } ], "desc": "

Write string to the file specified by fd. If string is not a string, then\nthe value will be coerced to one.

\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. Note that\nbytes written is not the same as string characters. See Buffer.byteLength.

\n

Unlike when writing buffer, the entire string must be written. No substring\nmay be specified. This is because the byte offset of the resulting data may not\nbe the same as the string offset.

\n

Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.

\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" }, { "textRaw": "fs.writeFile(file, data[, options], callback)", "type": "method", "name": "writeFile", "meta": { "added": [ "v0.1.29" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string | Buffer | integer} filename or file descriptor ", "name": "file", "type": "string | Buffer | integer", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string | Buffer} ", "name": "data", "type": "string | Buffer" }, { "textRaw": "`options` {Object | string} ", "options": [ { "textRaw": "`encoding` {string | Null} default = `'utf8'` ", "name": "encoding", "type": "string | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {integer} default = `0o666` ", "name": "mode", "type": "integer", "desc": "default = `0o666`" }, { "textRaw": "`flag` {string} default = `'w'` ", "name": "flag", "type": "string", "desc": "default = `'w'`" } ], "name": "options", "type": "Object | string", "optional": true }, { "textRaw": "`callback` {Function} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" } ], "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer.

\n

The encoding option is ignored if data is a buffer. It defaults\nto 'utf8'.

\n

Example:

\n
fs.writeFile('message.txt', 'Hello Node.js', (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. Example:

\n
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
\n

Any specified file descriptor has to support writing.

\n

Note that it is unsafe to use fs.writeFile multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.

\n

Note: If a file descriptor is specified as the file, it will not be closed\nautomatically.

\n" }, { "textRaw": "fs.writeFileSync(file, data[, options])", "type": "method", "name": "writeFileSync", "meta": { "added": [ "v0.1.29" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {string | Buffer | integer} filename or file descriptor ", "name": "file", "type": "string | Buffer | integer", "desc": "filename or file descriptor" }, { "textRaw": "`data` {string | Buffer} ", "name": "data", "type": "string | Buffer" }, { "textRaw": "`options` {Object | string} ", "options": [ { "textRaw": "`encoding` {string | Null} default = `'utf8'` ", "name": "encoding", "type": "string | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {integer} default = `0o666` ", "name": "mode", "type": "integer", "desc": "default = `0o666`" }, { "textRaw": "`flag` {string} default = `'w'` ", "name": "flag", "type": "string", "desc": "default = `'w'`" } ], "name": "options", "type": "Object | string", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true } ] } ], "desc": "

The synchronous version of fs.writeFile(). Returns undefined.

\n" }, { "textRaw": "fs.writeSync(fd, buffer[, offset[, length[, position]]])", "type": "method", "name": "writeSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`buffer` {Buffer} ", "name": "buffer", "type": "Buffer" }, { "textRaw": "`offset` {integer} ", "name": "offset", "type": "integer", "optional": true }, { "textRaw": "`length` {integer} ", "name": "length", "type": "integer", "optional": true }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer", "optional": true } ] }, { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "position", "optional": true } ] } ], "desc": "

Synchronous versions of fs.write(). Returns the number of bytes written.

\n" }, { "textRaw": "fs.writeSync(fd, string[, position[, encoding]])", "type": "method", "name": "writeSync", "meta": { "added": [ "v0.11.5" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {integer} ", "name": "fd", "type": "integer" }, { "textRaw": "`string` {string} ", "name": "string", "type": "string" }, { "textRaw": "`position` {integer} ", "name": "position", "type": "integer", "optional": true }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true } ] }, { "params": [ { "name": "fd" }, { "name": "string" }, { "name": "position", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Synchronous versions of fs.write(). Returns the number of bytes written.

\n" } ], "properties": [ { "textRaw": "fs.constants", "name": "constants", "desc": "

Returns an object containing commonly used constants for file system\noperations. The specific constants currently defined are described in\nFS Constants.

\n" } ], "type": "module", "displayName": "fs" }, { "textRaw": "HTTP", "name": "http", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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 — 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, Node.js's\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
\n", "classes": [ { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "meta": { "added": [ "v0.3.4" ] }, "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's pool when the socket emits either\na 'close' event or an 'agentRemove' event. This means that if\nyou intend to keep one HTTP request open for a long time and don't\nwant it to stay in the pool you can do something along the lines of:

\n
http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});\n
\n

You may also use an agent 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
\n", "methods": [ { "textRaw": "agent.createConnection(options[, callback])", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.11.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} ", "name": "return", "type": "net.Socket" }, "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", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "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

callback has a signature of (err, stream).

\n" }, { "textRaw": "agent.keepSocketAlive(socket)", "type": "method", "name": "keepSocketAlive", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`socket` {net.Socket} ", "name": "socket", "type": "net.Socket" } ] }, { "params": [ { "name": "socket" } ] } ], "desc": "

Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:

\n
socket.unref();\nsocket.setKeepAlive(agent.keepAliveMsecs);\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" }, { "textRaw": "agent.reuseSocket(socket, request)", "type": "method", "name": "reuseSocket", "meta": { "added": [ "v6.13.0" ] }, "signatures": [ { "params": [ { "textRaw": "`socket` {net.Socket} ", "name": "socket", "type": "net.Socket" }, { "textRaw": "`request` {http.ClientRequest} ", "name": "request", "type": "http.ClientRequest" } ] }, { "params": [ { "name": "socket" }, { "name": "request" } ] } ], "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" }, { "textRaw": "agent.destroy()", "type": "method", "name": "destroy", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Destroy any sockets that are currently in use by the agent.

\n

It is usually not necessary to do this. However, if you are using an\nagent with keepAlive enabled, then it is best to explicitly shut down\nthe agent when you know that it will no longer be used. Otherwise,\nsockets may hang open for quite a long time before the server\nterminates them.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "agent.getName(options)", "type": "method", "name": "getName", "meta": { "added": [ "v0.11.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {String} ", "name": "return", "type": "String" }, "params": [ { "textRaw": "`options` {Object} 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" } ], "name": "options", "type": "Object", "desc": "A set of options providing information for name generation" } ] }, { "params": [ { "name": "options" } ] } ], "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. For an HTTPS agent, the name includes the\nCA, cert, ciphers, and other HTTPS/TLS-specific options that determine\nsocket reusability.

\n" } ], "properties": [ { "textRaw": "`freeSockets` {Object} ", "type": "Object", "name": "freeSockets", "meta": { "added": [ "v0.11.4" ] }, "desc": "

An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive is enabled. Do not modify.

\n" }, { "textRaw": "`maxFreeSockets` {Number} ", "type": "Number", "name": "maxFreeSockets", "meta": { "added": [ "v0.11.7" ] }, "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.

\n" }, { "textRaw": "`maxSockets` {Number} ", "type": "Number", "name": "maxSockets", "meta": { "added": [ "v0.3.6" ] }, "desc": "

By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is either a 'host:port' or\n'host:port:localAddress' combination.

\n" }, { "textRaw": "`requests` {Object} ", "type": "Object", "name": "requests", "meta": { "added": [ "v0.5.9" ] }, "desc": "

An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.

\n" }, { "textRaw": "`sockets` {Object} ", "type": "Object", "name": "sockets", "meta": { "added": [ "v0.3.6" ] }, "desc": "

An object which contains arrays of sockets currently in use by the\nagent. Do not modify.

\n" } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object} 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. Default = `false` ", "name": "keepAlive", "type": "boolean", "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. Default = `false`" }, { "textRaw": "`keepAliveMsecs` {Integer} When using the `keepAlive` option, specifies the [initial delay](#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Default = `1000`. ", "name": "keepAliveMsecs", "type": "Integer", "desc": "When using the `keepAlive` option, specifies the [initial delay](#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Default = `1000`." }, { "textRaw": "`maxSockets` {number} Maximum number of sockets to allow per host. Default = `Infinity`. ", "name": "maxSockets", "type": "number", "desc": "Maximum number of sockets to allow per host. Default = `Infinity`." }, { "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", "desc": "Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `256`." } ], "name": "options", "type": "Object", "desc": "Set of configurable options to set on the agent. Can have the following fields:", "optional": true } ], "desc": "

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, you must create your own http.Agent instance.

\n
const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n" }, { "params": [ { "name": "options", "optional": true } ], "desc": "

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, you must create your own http.Agent instance.

\n
const http = require('http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "meta": { "added": [ "v0.1.17" ] }, "desc": "

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), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.

\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 you add a 'response' event handler,\nthen you must consume the data from the response object, 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

Note: Node.js does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.

\n

The request implements the Writable Stream interface. This is an\nEventEmitter with the following events:

\n", "events": [ { "textRaw": "Event: 'abort'", "type": "event", "name": "abort", "meta": { "added": [ "v1.4.1" ] }, "desc": "

Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "

Emitted each time a server responds to a request with a CONNECT method. If this\nevent is not being listened for, clients receiving a CONNECT method will have\ntheir connections closed.

\n

A client and server pair that shows you 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, cltSocket, head) => {\n  // connect to an origin server\n  const srvUrl = url.parse(`http://${req.url}`);\n  const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node.js-Proxy\\r\\n' +\n                    '\\r\\n');\n    srvSocket.write(head);\n    srvSocket.pipe(cltSocket);\n    cltSocket.pipe(srvSocket);\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    hostname: '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
\n" }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "meta": { "added": [ "v0.3.2" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "meta": { "added": [ "v0.1.0" ] }, "params": [], "desc": "

Emitted when a response is received to this request. This event is emitted only\nonce.

\n" }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "meta": { "added": [ "v0.5.3" ] }, "params": [], "desc": "

Emitted after a socket is assigned to this request.

\n" }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "params": [], "desc": "

Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for, clients receiving an upgrade header will have\ntheir connections closed.

\n

A client server pair that show you how to listen for the 'upgrade' event.

\n
const http = require('http');\n\n// Create an HTTP server\nconst srv = http.createServer((req, res) => {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.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\nsrv.listen(1337, '127.0.0.1', () => {\n\n  // make a request\n  const options = {\n    port: 1337,\n    hostname: '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
\n" } ], "methods": [ { "textRaw": "request.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.3.8" ] }, "desc": "

Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.end([data][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer", "optional": true }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "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.

\n" }, { "textRaw": "request.flushHeaders()", "type": "method", "name": "flushHeaders", "meta": { "added": [ "v1.6.0" ] }, "desc": "

Flush the request headers.

\n

For efficiency reasons, Node.js normally buffers the request headers until you\ncall request.end() or write the first chunk of request data. It then tries\nhard to pack the request headers and data into a single TCP packet.

\n

That's usually what you want (it saves a TCP round-trip) but not when the first\ndata is not sent until possibly much later. request.flushHeaders() lets you bypass\nthe optimization and kickstart the request.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "params": [ { "textRaw": "`noDelay` {boolean} ", "name": "noDelay", "type": "boolean", "optional": true } ] }, { "params": [ { "name": "noDelay", "optional": true } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.

\n" }, { "textRaw": "request.setSocketKeepAlive([enable][, initialDelay])", "type": "method", "name": "setSocketKeepAlive", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "params": [ { "textRaw": "`enable` {boolean} ", "name": "enable", "type": "boolean", "optional": true }, { "textRaw": "`initialDelay` {number} ", "name": "initialDelay", "type": "number", "optional": true } ] }, { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.

\n" }, { "textRaw": "request.setTimeout(timeout[, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "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.", "optional": true } ] }, { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ], "desc": "

Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.

\n

Returns request.

\n" }, { "textRaw": "request.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {string|Buffer} ", "name": "chunk", "type": "string|Buffer" }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver — in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating 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.

\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" } ], "properties": [ { "textRaw": "request.aborted", "name": "aborted", "meta": { "added": [ "v0.11.14" ] }, "desc": "

If a request has been aborted, this value is the time when the request was\naborted, in milliseconds since 1 January 1970 00:00:00 UTC.

\n" } ] }, { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "meta": { "added": [ "v0.1.17" ] }, "desc": "

This class inherits from net.Server and has the following additional events:

\n", "events": [ { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "meta": { "added": [ "v0.3.0" ] }, "params": [], "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 client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g. 400 Bad Request) if the client should not continue to send the\nrequest body.

\n

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.

\n" }, { "textRaw": "Event: 'checkExpectation'", "type": "event", "name": "checkExpectation", "meta": { "added": [ "v5.5.0" ] }, "params": [], "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

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.

\n" }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "meta": { "added": [ "v0.1.94" ] }, "params": [], "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 an\nHTTP '400 Bad Request' response instead of abruptly severing the connection.

\n

Default behavior is to destroy the socket immediately on malformed request.

\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" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.4" ] }, "desc": "

Emitted when the server closes.

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "params": [], "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

After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.

\n" }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.0" ] }, "params": [], "desc": "

When a new TCP stream is established. socket is an object of type\nnet.Socket. Usually users will not want to access this event. In\nparticular, the socket will not emit 'readable' events because of how\nthe protocol parser attaches to the socket. The socket can also be\naccessed at request.connection.

\n" }, { "textRaw": "Event: 'request'", "type": "event", "name": "request", "meta": { "added": [ "v0.1.0" ] }, "params": [], "desc": "

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).

\n" }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "params": [], "desc": "

Emitted each time a client requests an HTTP upgrade. If this event is not\nlistened for, then clients requesting an upgrade will have their connections\nclosed.

\n

After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.

\n" } ], "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

Stops the server from accepting new connections. See net.Server.close().

\n" }, { "textRaw": "server.listen(handle[, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.5.10" ] }, "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.

\n

Listening on a file descriptor is not supported on Windows.

\n

This function is asynchronous. callback will be added as a listener for the\n'listening' event. See also net.Server.listen().

\n

Returns server.

\n

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.listen(path[, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ], "desc": "

Start a UNIX socket server listening for connections on the given path.

\n

This function is asynchronous. callback will be added as a listener for the\n'listening' event. See also net.Server.listen(path).

\n

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.listen([port][, hostname][, backlog][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} ", "name": "port", "type": "number", "optional": true }, { "textRaw": "`hostname` {string} ", "name": "hostname", "type": "string", "optional": true }, { "textRaw": "`backlog` {number} ", "name": "backlog", "type": "number", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "port", "optional": true }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections on any IPv6 address\n(::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise.\nOmit the port argument, or use a port value of 0, to have the operating system\nassign a random port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.

\n

To listen to a unix socket, supply a filename instead of port and hostname.

\n

backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).

\n

This function is asynchronous. callback will be added as a listener for the\n'listening' event. See also net.Server.listen(port).

\n

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} ", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "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's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.

\n

Returns server.

\n" } ], "properties": [ { "textRaw": "`listening` {Boolean} ", "type": "Boolean", "name": "listening", "meta": { "added": [ "v5.7.0" ] }, "desc": "

A Boolean indicating whether or not the server is listening for\nconnections.

\n" }, { "textRaw": "`maxHeadersCount` {Number} ", "type": "Number", "name": "maxHeadersCount", "meta": { "added": [ "v0.7.0" ] }, "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.

\n" }, { "textRaw": "`headersTimeout` {number} **Default:** `40000` ", "type": "number", "name": "headersTimeout", "meta": { "added": [ "v6.15.0" ] }, "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 behaviour can be\ncustomised.

\n", "shortDesc": "**Default:** `40000`" }, { "textRaw": "`timeout` {number} Timeout in milliseconds. Defaults to 120000 (2 minutes). ", "type": "number", "name": "timeout", "meta": { "added": [ "v0.9.12" ] }, "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

Note: The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

\n", "shortDesc": "Timeout in milliseconds. Defaults to 120000 (2 minutes)." }, { "textRaw": "`keepAliveTimeout` {number} Timeout in milliseconds. Defaults to 5000 (5 seconds). ", "type": "number", "name": "keepAliveTimeout", "meta": { "added": [ "v6.17.0" ] }, "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 connections.

\n

Note: The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

\n", "shortDesc": "Timeout in milliseconds. Defaults to 5000 (5 seconds)." } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "meta": { "added": [ "v0.1.17" ] }, "desc": "

This object is created internally by an HTTP server — not by the user. It is\npassed as the second parameter to the 'request' event.

\n

The response implements, but does not inherit from, the Writable Stream\ninterface. This is an EventEmitter with the following events:

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.6.7" ] }, "desc": "

Indicates that the underlying connection was terminated before\nresponse.end() was called or able to flush.

\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v0.3.6" ] }, "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.

\n

After this event, no more events will be emitted on the response object.

\n", "params": [] } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object} ", "name": "headers", "type": "Object" } ] }, { "params": [ { "name": "headers" } ] } ], "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

Note that HTTP requires the Trailer header to be sent if you intend 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.

\n" }, { "textRaw": "response.end([data][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer} ", "name": "data", "type": "string|Buffer", "optional": true }, { "textRaw": "`encoding` {string} ", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "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.

\n" }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "meta": { "added": [ "v0.4.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {String} ", "name": "return", "type": "String" }, "params": [ { "textRaw": "`name` {string} ", "name": "name", "type": "string" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Reads out a header that's already been queued but not sent to the client.\nNote that the name is case insensitive.

\n

Example:

\n
const contentType = response.getHeader('content-type');\n
\n" }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "meta": { "added": [ "v0.4.0" ] }, "signatures": [ { "params": [ { "textRaw": "`name` {string} ", "name": "name", "type": "string" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Removes a header that's queued for implicit sending.

\n

Example:

\n
response.removeHeader('Content-Encoding');\n
\n" }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "meta": { "added": [ "v0.4.0" ] }, "signatures": [ { "params": [ { "textRaw": "`name` {string} ", "name": "name", "type": "string" }, { "textRaw": "`value` {string} ", "name": "value", "type": "string" } ] }, { "params": [ { "name": "name" }, { "name": "value" } ] } ], "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 if you need to send multiple headers with the same name.

\n

Example:

\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 with\nany headers passed to response.writeHead(), with the headers passed to\nresponse.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" }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.9.12" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} ", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "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 you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.

\n

Returns response.

\n" }, { "textRaw": "response.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.29" ] }, "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", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "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

Note that 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

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.

\n

The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node.js assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of 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.

\n" }, { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "meta": { "added": [ "v0.3.0" ] }, "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 Server.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode[, statusMessage][, headers])", "type": "method", "name": "writeHead", "meta": { "added": [ "v0.1.30" ] }, "signatures": [ { "params": [ { "textRaw": "`statusCode` {number} ", "name": "statusCode", "type": "number" }, { "textRaw": "`statusMessage` {string} ", "name": "statusMessage", "type": "string", "optional": true }, { "textRaw": "`headers` {Object} ", "name": "headers", "type": "Object", "optional": true } ] }, { "params": [ { "name": "statusCode" }, { "name": "statusMessage", "optional": true }, { "name": "headers", "optional": true } ] } ], "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

Example:

\n
const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain' });\n
\n

This method must only be called once on a message and it must\nbe called before response.end() is called.

\n

If you call response.write() or response.end() before calling this,\nthe implicit/mutable headers will be calculated and call this function for you.

\n

When headers have been set with response.setHeader(), they will be merged with\nany headers passed to response.writeHead(), with the headers passed to\nresponse.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

Note that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node.js does not check whether Content-Length and the length of the body\nwhich has been 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.

\n" } ], "properties": [ { "textRaw": "`finished` {Boolean} ", "type": "Boolean", "name": "finished", "meta": { "added": [ "v0.0.2" ] }, "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

\n" }, { "textRaw": "`headersSent` {Boolean} ", "type": "Boolean", "name": "headersSent", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Boolean (read-only). True if headers were sent, false otherwise.

\n" }, { "textRaw": "`sendDate` {Boolean} ", "type": "Boolean", "name": "sendDate", "meta": { "added": [ "v0.7.5" ] }, "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.

\n" }, { "textRaw": "`statusCode` {Number} ", "type": "Number", "name": "statusCode", "meta": { "added": [ "v0.4.0" ] }, "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

Example:

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

\n" }, { "textRaw": "`statusMessage` {String} ", "type": "String", "name": "statusMessage", "meta": { "added": [ "v0.11.8" ] }, "desc": "

When using implicit headers (not calling response.writeHead() explicitly), this property\ncontrols the status message that will be sent to the client when the headers get\nflushed. If this is left as undefined then the standard message for the status\ncode will be used.

\n

Example:

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

\n" } ] }, { "textRaw": "Class: http.IncomingMessage", "type": "class", "name": "http.IncomingMessage", "meta": { "added": [ "v0.1.17" ] }, "desc": "

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 status,\nheaders and data.

\n

It implements the Readable Stream interface, as well as the\nfollowing additional events, methods, and properties.

\n", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v0.3.8" ] }, "desc": "

Emitted when the request has been aborted and the network socket has closed.

\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.4.2" ] }, "desc": "

Indicates that the underlying connection was closed.\nJust like 'end', this event occurs only once per response.

\n", "params": [] } ], "methods": [ { "textRaw": "message.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error} ", "name": "error", "type": "Error", "optional": true } ] }, { "params": [ { "name": "error", "optional": true } ] } ], "desc": "

Calls destroy() on the socket that received the IncomingMessage. If error\nis provided, an 'error' event is emitted and error is passed as an argument\nto any listeners on the event.

\n" }, { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} ", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Calls message.connection.setTimeout(msecs, callback).

\n

Returns message.

\n" } ], "properties": [ { "textRaw": "`headers` {Object} ", "type": "Object", "name": "headers", "meta": { "added": [ "v0.1.5" ] }, "desc": "

The request/response headers object.

\n

Key-value pairs of header names and values. Header names are lower-cased.\nExample:

\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" }, { "textRaw": "`httpVersion` {String} ", "type": "String", "name": "httpVersion", "meta": { "added": [ "v0.1.1" ] }, "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.

\n" }, { "textRaw": "`method` {String} ", "type": "String", "name": "method", "meta": { "added": [ "v0.1.1" ] }, "desc": "

Only valid for request obtained from http.Server.

\n

The request method as a string. Read only. Example:\n'GET', 'DELETE'.

\n" }, { "textRaw": "`rawHeaders` {Array} ", "type": "Array", "name": "rawHeaders", "meta": { "added": [ "v0.11.6" ] }, "desc": "

The raw request/response headers list exactly as they were received.

\n

Note that 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
\n" }, { "textRaw": "`rawTrailers` {Array} ", "type": "Array", "name": "rawTrailers", "meta": { "added": [ "v0.11.6" ] }, "desc": "

The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

\n" }, { "textRaw": "`statusCode` {Number} ", "type": "Number", "name": "statusCode", "meta": { "added": [ "v0.1.1" ] }, "desc": "

Only valid for response obtained from http.ClientRequest.

\n

The 3-digit HTTP response status code. E.G. 404.

\n" }, { "textRaw": "`statusMessage` {String} ", "type": "String", "name": "statusMessage", "meta": { "added": [ "v0.11.10" ] }, "desc": "

Only valid for response obtained from http.ClientRequest.

\n

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.

\n" }, { "textRaw": "`socket` {net.Socket} ", "type": "net.Socket", "name": "socket", "meta": { "added": [ "v0.3.0" ] }, "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" }, { "textRaw": "`trailers` {Object} ", "type": "Object", "name": "trailers", "meta": { "added": [ "v0.3.0" ] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

\n" }, { "textRaw": "`url` {String} ", "type": "String", "name": "url", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Only valid for request obtained from http.Server.

\n

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n
\n

Then request.url will be:

\n\n
'/status?name=ryan'\n
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:

\n
$ node\n> require('url').parse('/status?name=ryan')\n{\n  href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status'\n}\n
\n

If you would like to extract the parameters from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:

\n
$ node\n> require('url').parse('/status?name=ryan', true)\n{\n  href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: {name: 'ryan'},\n  pathname: '/status'\n}\n
\n" } ] } ], "properties": [ { "textRaw": "`METHODS` {Array} ", "type": "Array", "name": "METHODS", "meta": { "added": [ "v0.11.8" ] }, "desc": "

A list of the HTTP methods that are supported by the parser.

\n" }, { "textRaw": "`STATUS_CODES` {Object} ", "type": "Object", "name": "STATUS_CODES", "meta": { "added": [ "v0.1.22" ] }, "desc": "

A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.

\n" }, { "textRaw": "`globalAgent` {http.Agent} ", "type": "http.Agent", "name": "globalAgent", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Global instance of Agent which is used as the default for all HTTP client\nrequests.

\n" }, { "textRaw": "`maxHeaderSize` {number} ", "type": "number", "name": "maxHeaderSize", "meta": { "added": [ "v6.16.0" ] }, "desc": "

Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 8KB. Configurable using the --max-http-header-size CLI option.

\n" } ], "methods": [ { "textRaw": "http.createClient([port][, host])", "type": "method", "name": "createClient", "meta": { "added": [ "v0.1.13" ], "deprecated": [ "v0.3.6" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`http.request()`][] instead.", "desc": "

Constructs a new HTTP client. port and host refer to the server to be\nconnected to.

\n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.1.13" ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.Server} ", "name": "return", "type": "http.Server" }, "params": [ { "name": "requestListener", "optional": true } ] }, { "params": [ { "name": "requestListener", "optional": true } ] } ], "desc": "

Returns a new instance of http.Server.

\n

The requestListener is a function which is automatically\nadded to the 'request' event.

\n" }, { "textRaw": "http.get(options[, callback])", "type": "method", "name": "get", "meta": { "added": [ "v0.3.6" ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.ClientRequest} ", "name": "return", "type": "http.ClientRequest" }, "params": [ { "textRaw": "`options` {Object} ", "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "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. Note that 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://nodejs.org/dist/index.json', (res) => {\n  const statusCode = res.statusCode;\n  const contentType = res.headers['content-type'];\n\n  let error;\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.log(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.log(e.message);\n    }\n  });\n}).on('error', (e) => {\n  console.log(`Got error: ${e.message}`);\n});\n
\n" }, { "textRaw": "http.request(options[, callback])", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ] }, "signatures": [ { "return": { "textRaw": "Returns: {http.ClientRequest} ", "name": "return", "type": "http.ClientRequest" }, "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`protocol` {string} Protocol to use. Defaults to `'http:'`. ", "name": "protocol", "type": "string", "desc": "Protocol to use. Defaults to `'http:'`." }, { "textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`. ", "name": "host", "type": "string", "desc": "A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`." }, { "textRaw": "`hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`. ", "name": "hostname", "type": "string", "desc": "Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`." }, { "textRaw": "`family` {number} IP address family to use when resolving `host` and `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` and `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used." }, { "textRaw": "`port` {number} Port of remote server. Defaults to 80. ", "name": "port", "type": "number", "desc": "Port of remote server. Defaults to 80." }, { "textRaw": "`localAddress` {string} Local interface to bind for network connections. ", "name": "localAddress", "type": "string", "desc": "Local interface to bind for network connections." }, { "textRaw": "`socketPath` {string} Unix Domain Socket (use one of host:port or socketPath). ", "name": "socketPath", "type": "string", "desc": "Unix Domain Socket (use one of host:port or socketPath)." }, { "textRaw": "`method` {string} A string specifying the HTTP request method. Defaults to `'GET'`. ", "name": "method", "type": "string", "desc": "A string specifying the HTTP request method. Defaults to `'GET'`." }, { "textRaw": "`path` {string} Request path. Defaults to `'/'`. 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. Defaults to `'/'`. 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": "`headers` {Object} An object containing request headers. ", "name": "headers", "type": "Object", "desc": "An object containing request headers." }, { "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": "`agent` {http.Agent|boolean} Controls [`Agent`][] behavior. Possible values: ", "options": [ { "textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port. ", "name": "undefined", "default": "", "desc": ": 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." } ], "name": "agent", "type": "http.Agent|boolean", "desc": "Controls [`Agent`][] behavior. Possible values:" }, { "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. ", "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." }, { "textRaw": "`timeout` {Integer}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected. ", "name": "timeout", "type": "Integer", "desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected." } ], "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().

\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

Example:

\n
const postData = querystring.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/x-www-form-urlencoded',\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.log(`problem with request: ${e.message}`);\n});\n\n// write data to request body\nreq.write(postData);\nreq.end();\n
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with 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\n" } ], "type": "module", "displayName": "HTTP" }, { "textRaw": "HTTPS", "name": "https", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.

\n", "classes": [ { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "meta": { "added": [ "v0.4.5" ] }, "desc": "

An Agent object for HTTPS similar to http.Agent. See https.request()\nfor more information.

\n" }, { "textRaw": "Class: https.Server", "type": "class", "name": "https.Server", "meta": { "added": [ "v0.3.4" ] }, "desc": "

This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.

\n", "properties": [ { "textRaw": "`headersTimeout` {number} **Default:** `40000` ", "type": "number", "name": "headersTimeout", "desc": "

See http.Server#headersTimeout.

\n", "shortDesc": "**Default:** `40000`" }, { "textRaw": "`keepAliveTimeout` {number} Defaults to 5000 (5 seconds). ", "type": "number", "name": "keepAliveTimeout", "meta": { "added": [ "v6.17.0" ] }, "desc": "

See http.Server#keepAliveTimeout.

\n", "shortDesc": "Defaults to 5000 (5 seconds)." } ], "methods": [ { "textRaw": "server.setTimeout([msecs][, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.11.2" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} Defaults to 120000 (2 minutes). ", "name": "msecs", "type": "number", "desc": "Defaults to 120000 (2 minutes).", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "msecs", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

See http.Server#setTimeout().

\n" }, { "textRaw": "server.timeout([msecs])", "type": "method", "name": "timeout", "meta": { "added": [ "v0.11.2" ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} Defaults to 120000 (2 minutes). ", "name": "msecs", "type": "number", "desc": "Defaults to 120000 (2 minutes).", "optional": true } ] }, { "params": [ { "name": "msecs", "optional": true } ] } ], "desc": "

See http.Server#timeout.

\n" } ] } ], "methods": [ { "textRaw": "https.createServer(options[, requestListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.4" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Accepts `options` from [`tls.createServer()`][] and [`tls.createSecureContext()`][]. ", "name": "options", "type": "Object", "desc": "Accepts `options` from [`tls.createServer()`][] and [`tls.createSecureContext()`][]." }, { "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.", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "requestListener", "optional": true } ] } ], "desc": "

Example:

\n
// 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
\n", "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

See http.close() for details.

\n" }, { "textRaw": "server.listen(path[, callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ], "desc": "

See http.listen() for details.

\n" }, { "textRaw": "server.listen([port][, host][, backlog][, callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`port` {number} ", "name": "port", "type": "number", "optional": true }, { "textRaw": "`hostname` {string} ", "name": "hostname", "type": "string", "optional": true }, { "textRaw": "`backlog` {number} ", "name": "backlog", "type": "number", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

See http.listen() for details.

\n" } ] }, { "textRaw": "https.get(options[, callback])", "type": "method", "name": "get", "meta": { "added": [ "v0.3.6" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object | string} Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`. ", "name": "options", "type": "Object | string", "desc": "Accepts the same `options` as [`https.request()`][], with the `method` always set to `GET`." }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

Like http.get() but for HTTPS.

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().

\n

Example:

\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
\n" }, { "textRaw": "https.request(options[, callback])", "type": "method", "name": "request", "meta": { "added": [ "v0.3.6" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object | string} Accepts all `options` from [`http.request()`][], with some differences in default values: ", "options": [ { "textRaw": "`protocol` Defaults to `https:` ", "name": "protocol", "desc": "Defaults to `https:`" }, { "textRaw": "`port` Defaults to `443`. ", "name": "port", "desc": "Defaults to `443`." }, { "textRaw": "`agent` Defaults to `https.globalAgent`. ", "name": "agent", "desc": "Defaults to `https.globalAgent`." } ], "name": "options", "type": "Object | string", "desc": "Accepts all `options` from [`http.request()`][], with some differences in default values:" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

Makes a request to a secure web server.

\n

The following additional options from tls.connect() are also accepted when using a\n custom Agent:\n pfx, key, passphrase, cert, ca, ciphers, rejectUnauthorized, secureProtocol, servername

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().

\n

Example:

\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

Example:

\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\n\n" } ], "properties": [ { "textRaw": "https.globalAgent", "name": "globalAgent", "meta": { "added": [ "v0.5.9" ] }, "desc": "

Global instance of https.Agent for all HTTPS client requests.

\n" } ], "type": "module", "displayName": "HTTPS" }, { "textRaw": "Internationalization Support", "name": "internationalization_support", "desc": "

Node.js has many features that make it easier to write internationalized\nprograms. Some of them are:

\n\n

Node.js (and its underlying V8 engine) uses ICU to implement these features\nin native C/C++ code. However, some of them require a very large ICU data file\nin order to support all locales of the world. Because it is expected that most\nNode.js users will make use of only a small portion of ICU functionality, only\na subset of the full ICU data set is provided by Node.js by default. Several\noptions are provided for customizing and expanding the ICU data set either when\nbuilding or running Node.js.

\n", "properties": [ { "textRaw": "Options for building Node.js", "name": "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

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

Note: The "(not locale-aware)" designation denotes that the function carries\nout its operation 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().

\n", "modules": [ { "textRaw": "Disable all internationalization features (`none`)", "name": "disable_all_internationalization_features_(`none`)", "desc": "

If this option is chosen, most internationalization features mentioned above\nwill be unavailable in the resulting node binary.

\n", "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(), are fully supported under system-icu.\nFeatures that require ICU locale data in addition, such as\nIntl.DateTimeFormat may be fully or partially supported, depending on\nthe completeness of the ICU data installed on the system.

\n", "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(), are fully supported under small-icu.\nFeatures that require ICU locale data in addition, such as\nIntl.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 "January" or "M01" on small-icu\n// Should print "enero"\n
\n

This mode provides a good balance between features and binary size, and it is\nthe default behavior if no --with-intl flag is passed. The official binaries\nare also built in this mode.

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

(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 icudt5X[bl].dat, where 5X 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.

\n", "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. See\nBUILDING.md on how to compile a binary using this mode.

\n", "type": "module", "displayName": "Embed the entire ICU (`full-icu`)" } ] } ], "modules": [ { "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\n\n", "type": "module", "displayName": "Detecting internationalization support" } ], "type": "module", "displayName": "Internationalization Support" }, { "textRaw": "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 * r;\n\nexports.circumference = (r) => 2 * PI * r;\n
\n

The module circle.js has exported the functions area() and\ncircumference(). To add functions and objects to the root of your module,\nyou can add them to 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

If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports\ninstead of exports.

\n

Below, bar.js makes use of the square module, which exports a constructor:

\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 = (width) => {\n  return {\n    area: () => width * width\n  };\n};\n
\n

The module system is implemented in the require('module') module.

\n", "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 you can determine whether a file has been run\ndirectly 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.

\n" }, { "textRaw": "Addenda: Package Manager Tips", "name": "Addenda: Package Manager Tips", "type": "misc", "desc": "

The semantics of Node.js's require() function were designed to be general\nenough to support a number of reasonable directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native 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, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.

\n

Since Node.js looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the node_modules\nfolders as described here, this\nsituation is very simple to resolve with the following architecture:

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

\n" }, { "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.resolve() does:

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with '/'\n   a. set Y to 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)\n4. LOAD_NODE_MODULES(X, dirname(Y))\n5. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  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. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n   d. LOAD_INDEX(M)\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_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = []\n4. while I >= 0,\n   a. if PARTS[I] = "node_modules" 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
\n" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.

\n

Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.

\n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "

Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould 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.

\n" } ] }, { "textRaw": "Core Modules", "name": "Core Modules", "type": "misc", "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 Node.js's 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" }, { "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

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.

\n" }, { "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 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'.

\n" }, { "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 that library.\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 Node.js's awareness of package.json files.

\n

Note: If the file specified by the 'main' entry of package.json is missing\nand can not be resolved, Node.js will report the entire module as missing with\nthe default error:

\n
Error: Cannot find module 'some-library'\n
\n

If there is no package.json file present in the directory, 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 above\nexample, then require('./some-library') would attempt to load:

\n\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. Node\nwill not append node_modules to a path already ending in node_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

This allows programs to localize their dependencies, so that they do not\nclash.

\n

You can require specific files or sub modules distributed with a module by\nincluding 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.

\n" }, { "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. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)

\n

NODE_PATH was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was frozen.

\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 locations:

\n\n

Where $HOME is the user's home directory, and $PREFIX is Node.js's\nconfigured node_prefix.

\n

These are mostly for historic reasons. You are highly encouraged\nto place your dependencies locally in node_modules folders. They\nwill be loaded faster, and more reliably.

\n" }, { "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// Your module code actually lives in here\n});\n
\n

By doing this, Node.js achieves a few things:

\n\n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "meta": { "added": [ "v0.1.16" ] }, "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.

\n", "properties": [ { "textRaw": "`children` {Array} ", "type": "Array", "name": "children", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The module objects required by this one.

\n" }, { "textRaw": "`exports` {Object} ", "type": "Object", "name": "exports", "meta": { "added": [ "v0.1.16" ] }, "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. Note that assigning\nthe desired object to exports will simply rebind the local exports variable,\nwhich is probably not what you want to do.

\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

Note that 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
\n", "modules": [ { "textRaw": "exports shortcut", "name": "exports_shortcut", "meta": { "added": [ "v0.1.16" ] }, "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, for example:

\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    // Your 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
\n", "type": "module", "displayName": "exports shortcut" } ] }, { "textRaw": "`filename` {string} ", "type": "string", "name": "filename", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The fully resolved filename to the module.

\n" }, { "textRaw": "`id` {string} ", "type": "string", "name": "id", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.

\n" }, { "textRaw": "`loaded` {boolean} ", "type": "boolean", "name": "loaded", "meta": { "added": [ "v0.1.16" ] }, "desc": "

Whether or not the module is done loading, or is in the process of\nloading.

\n" }, { "textRaw": "`parent` {Object} Module object ", "type": "Object", "name": "parent", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The module that first required this one.

\n", "shortDesc": "Module object" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {string} ", "name": "id", "type": "string" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "

The module.require method provides a way to load a module as if\nrequire() was called from the original module.

\n

Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the module.exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.

\n" } ] } ], "modules": [ { "textRaw": "The `Module` Object", "name": "the_`module`_object", "meta": { "added": [ "v0.3.7" ] }, "desc": "\n

Provides general utility methods when interacting with instances of\nModule — the module variable often seen in file modules. Accessed\nvia require('module').

\n", "properties": [ { "textRaw": "`builtinModules` {string[]} ", "type": "string[]", "name": "builtinModules", "meta": { "added": [ "v6.13.0" ] }, "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 module or not.

\n\n\n" } ], "type": "module", "displayName": "The `Module` Object" } ], "type": "module", "displayName": "module" }, { "textRaw": "Net", "name": "net", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The net module provides you with an asynchronous network wrapper. It contains\nfunctions for creating both servers and clients (called streams). You can include\nthis module with require('net');.

\n", "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "meta": { "added": [ "v0.1.90" ] }, "desc": "

This class is used to create a TCP or local server.

\n

net.Server is an EventEmitter with the following events:

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.90" ] }, "params": [], "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.

\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.1.90" ] }, "params": [], "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().

\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Emitted when the server has been bound after calling server.listen.

\n", "params": [] } ], "methods": [ { "textRaw": "server.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.1.90" ] }, "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.\nUseful to find which port was assigned when getting an OS-assigned address.\nReturns an object with port, family, and address properties:\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

Example:

\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 a random port.\nserver.listen(() => {\n  console.log('opened server on', server.address());\n});\n
\n

Don't call server.address() until the 'listening' event has been emitted.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "name": "callback", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when 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.

\n

Returns server.

\n" }, { "textRaw": "server.getConnections(callback)", "type": "method", "name": "getConnections", "meta": { "added": [ "v0.9.7" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "name": "callback" } ] }, { "params": [ { "name": "callback" } ] } ], "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.

\n" }, { "textRaw": "server.listen(handle[, backlog][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.5.10" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`backlog` {number} ", "name": "backlog", "type": "number", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.

\n

Listening on a file descriptor is not supported on Windows.

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nThe last parameter callback will be added as a listener for the\n'listening' event.

\n

The parameter backlog behaves the same as in\nserver.listen([port][, hostname][, backlog][, callback]).

\n" }, { "textRaw": "server.listen(options[, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.11.14" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`options` {Object} - Required. Supports the following properties: ", "options": [ { "textRaw": "`port` {number} - Optional. ", "name": "port", "type": "number", "desc": "Optional." }, { "textRaw": "`host` {string} - Optional. ", "name": "host", "type": "string", "desc": "Optional." }, { "textRaw": "`backlog` {number} - Optional. ", "name": "backlog", "type": "number", "desc": "Optional." }, { "textRaw": "`path` {string} - Optional. ", "name": "path", "type": "string", "desc": "Optional." }, { "textRaw": "`exclusive` {boolean} - Optional. ", "name": "exclusive", "type": "boolean", "desc": "Optional." } ], "name": "options", "type": "Object", "desc": "Required. Supports the following properties:" }, { "textRaw": "`callback` {Function} - Optional. ", "name": "callback", "type": "Function", "desc": "Optional.", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "

The port, host, and backlog properties of options, as well as the\noptional callback function, behave as they do on a call to\nserver.listen([port][, hostname][, backlog][, callback]).\nAlternatively, the path option can be used to specify a UNIX socket.

\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

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.listen(path[, backlog][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" }, { "textRaw": "`backlog` {number} ", "name": "backlog", "type": "number", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Start a local socket server listening for connections on the given path.

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.

\n

On UNIX, the local domain is usually known as the UNIX domain. The path is a\nfilesystem path name. It gets truncated to sizeof(sockaddr_un.sun_path)\nbytes, decreased by 1. It varies on different operating system between 91 and\n107 bytes. The typical values are 107 on Linux and 103 on OS X. The path is\nsubject to the same naming conventions and permissions checks as would be done\non file creation, will be visible in the filesystem, and will persist until\nunlinked.

\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 appearances, the pipe name space is flat. Pipes will not\npersist, they are removed when the last reference to them is closed. Do not\nforget JavaScript string escaping requires paths to be specified with\ndouble-backslashes, such as:

\n
net.createServer().listen(\n  path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'));\n
\n

The parameter backlog behaves the same as in\nserver.listen([port][, hostname][, backlog][, callback]).

\n

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.listen([port][, hostname][, backlog][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [ { "name": "port", "optional": true }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "port", "optional": true }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections on any IPv6 address\n(::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise.\nOmit the port argument, or use a port value of 0, to have the operating system\nassign a random port, which can be retrieved by using server.address().port\nafter the 'listening' event has been emitted.

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by the OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on Linux. The default value of this\nparameter is 511 (not 512).

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted. The last parameter callback\nwill be added as a listener for the 'listening' event.

\n

One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again:

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

(Note: All sockets in Node.js are set SO_REUSEADDR.)

\n

Note: The server.listen() method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.

\n" }, { "textRaw": "server.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [] }, { "params": [] } ], "desc": "

Opposite of unref, calling ref on a previously unrefd server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is refd calling ref again will have no effect.

\n" }, { "textRaw": "server.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Server} ", "name": "return", "type": "net.Server" }, "params": [] }, { "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 unrefd calling\nunref again will have no effect.

\n" } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "meta": { "added": [ "v0.2.0" ], "deprecated": [ "v0.9.7" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", "desc": "

The number of concurrent connections on the server.

\n

This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections use asynchronous server.getConnections instead.

\n" }, { "textRaw": "server.listening", "name": "listening", "meta": { "added": [ "v5.7.0" ] }, "desc": "

A Boolean indicating whether or not the server is listening for\nconnections.

\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "meta": { "added": [ "v0.2.0" ] }, "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().

\n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "meta": { "added": [ "v0.3.4" ] }, "desc": "

This object is an abstraction of a TCP or local socket. net.Socket\ninstances implement a duplex Stream interface. They can be created by the\nuser and used as a client (with connect()) or they can be created by Node.js\nand passed to the user through the 'connection' event of a server.

\n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "meta": { "added": [ "v0.3.4" ] }, "desc": "

Construct a new socket object.

\n

options is an object with the following defaults:

\n\n
{\n  fd: null,\n  allowHalfOpen: false,\n  readable: false,\n  writable: false\n}\n
\n

fd allows you to specify the existing file descriptor of socket.\nSet readable and/or writable to true to allow reads and/or writes on this\nsocket (NOTE: Works only when fd is passed).\nAbout allowHalfOpen, refer to net.createServer() and 'end' event.

\n

net.Socket instances are EventEmitter with the following events:

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.connect(options[, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Opens the connection for a given socket.

\n

For TCP sockets, options argument should be an object which specifies:

\n\n

For local domain sockets, options argument should be an object which\nspecifies:

\n\n

For either case:

\n\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.

\n

This function is asynchronous. When the 'connect' event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.

\n

The connectListener parameter will be added as a listener for the\n'connect' event.

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path[, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

As socket.connect(options[, connectListener]),\nwith options as either {port: port, host: host} or {path: path}.

\n\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(port[, host][, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

As socket.connect(options[, connectListener]),\nwith options as either {port: port, host: host} or {path: path}.

\n\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.destroy([exception])", "type": "method", "name": "destroy", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).

\n

If exception is specified, an 'error' event will be emitted and any\nlisteners for that event will receive exception as an argument.

\n", "signatures": [ { "params": [ { "name": "exception", "optional": true } ] } ] }, { "textRaw": "socket.end([data][, encoding])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] }, { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().

\n

Returns socket.

\n" }, { "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": [] }, { "params": [] } ], "desc": "

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.

\n" }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] }, { "params": [] } ], "desc": "

Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.

\n" }, { "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": [] }, { "params": [] } ], "desc": "

Resumes reading after a call to pause().

\n" }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "name": "encoding", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true } ] } ], "desc": "

Set the encoding for the socket as a Readable Stream. See\nstream.setEncoding() for more information.

\n" }, { "textRaw": "socket.setKeepAlive([enable][, initialDelay])", "type": "method", "name": "setKeepAlive", "meta": { "added": [ "v0.1.92" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] }, { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ], "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.

\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. Defaults to 0.

\n" }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "name": "noDelay", "optional": true } ] }, { "params": [ { "name": "noDelay", "optional": true } ] } ], "desc": "

Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.

\n" }, { "textRaw": "socket.setTimeout(timeout[, callback])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ], "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 end()\nor destroy() the socket.

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

\n" }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {net.Socket} The socket itself. ", "name": "return", "type": "net.Socket", "desc": "The socket itself." }, "params": [] }, { "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 unrefd calling\nunref again will have no effect.

\n" }, { "textRaw": "socket.write(data[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.90" ] }, "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 - this may not be immediately.

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] } ], "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.90" ] }, "params": [], "desc": "

Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.

\n" }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Emitted when a socket connection is successfully established.\nSee connect().

\n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "meta": { "added": [ "v0.1.90" ] }, "params": [], "desc": "

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the Readable Stream section for more information.)

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.

\n" }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.

\n

See also: the return values of socket.write()

\n", "params": [] }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "desc": "

Emitted when the other end of the socket sends a FIN packet.

\n

By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.1.90" ] }, "params": [], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.

\n" }, { "textRaw": "Event: 'lookup'", "type": "event", "name": "lookup", "meta": { "added": [ "v0.11.3" ] }, "desc": "

Emitted after resolving the hostname but before connecting.\nNot applicable to UNIX sockets.

\n\n", "params": [] }, { "textRaw": "Event: 'timeout'", "type": "event", "name": "timeout", "meta": { "added": [ "v0.1.90" ] }, "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()

\n", "params": [] } ], "properties": [ { "textRaw": "socket.bufferSize", "name": "bufferSize", "meta": { "added": [ "v0.3.8" ] }, "desc": "

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. (Internally it is\npolling on the socket's file descriptor for being writable).

\n

The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().

\n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "meta": { "added": [ "v0.5.3" ] }, "desc": "

The amount of received bytes.

\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "meta": { "added": [ "v0.5.3" ] }, "desc": "

The amount of bytes sent.

\n" }, { "textRaw": "socket.connecting", "name": "connecting", "meta": { "added": [ "v6.1.0" ] }, "desc": "

If true - socket.connect(options[, connectListener]) was called and\nhaven't yet finished. Will be set to false before emitting connect event\nand/or calling socket.connect(options[, connectListener])'s callback.

\n" }, { "textRaw": "socket.destroyed", "name": "destroyed", "desc": "

A Boolean value that indicates if the connection is destroyed or not. Once a\nconnection is destroyed no further data can be transferred using it.

\n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "meta": { "added": [ "v0.9.6" ] }, "desc": "

The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0' and the\nclient connects on '192.168.1.1', the value would be '192.168.1.1'.

\n" }, { "textRaw": "socket.localPort", "name": "localPort", "meta": { "added": [ "v0.9.6" ] }, "desc": "

The numeric representation of the local port. For example,\n80 or 21.

\n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "meta": { "added": [ "v0.5.10" ] }, "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).

\n" }, { "textRaw": "socket.remoteFamily", "name": "remoteFamily", "meta": { "added": [ "v0.11.14" ] }, "desc": "

The string representation of the remote IP family. 'IPv4' or 'IPv6'.

\n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "meta": { "added": [ "v0.5.10" ] }, "desc": "

The numeric representation of the remote port. For example,\n80 or 21.

\n" } ] } ], "methods": [ { "textRaw": "net.connect(options[, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "desc": "

A factory function, which returns a new net.Socket and automatically\nconnects with the supplied options.

\n

The options are passed to both the net.Socket constructor and the\nsocket.connect method.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\n

Here is an example of a client of the previously described echo server:

\n
const net = require('net');\nconst client = net.connect({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 the second line would just be\nchanged to

\n
const client = net.connect({path: '/tmp/echo.sock'});\n
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path[, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A factory function, which returns a new unix net.Socket and automatically\nconnects to the supplied path.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port[, host][, connectListener])", "type": "method", "name": "connect", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A factory function, which returns a new net.Socket and automatically\nconnects to the supplied port and host.

\n

If host is omitted, 'localhost' will be assumed.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options[, connectListener])", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A factory function, which returns a new net.Socket and automatically\nconnects with the supplied options.

\n

The options are passed to both the net.Socket constructor and the\nsocket.connect method.

\n

Passing timeout as an option will call socket.setTimeout() after the socket is created, but before it is connecting.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\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 the second line would just be\nchanged to

\n
const client = net.connect({path: '/tmp/echo.sock'});\n
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path[, connectListener])", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A factory function, which returns a new unix net.Socket and automatically\nconnects to the supplied path.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port[, host][, connectListener])", "type": "method", "name": "createConnection", "meta": { "added": [ "v0.1.90" ] }, "desc": "

A factory function, which returns a new net.Socket and automatically\nconnects to the supplied port and host.

\n

If host is omitted, 'localhost' will be assumed.

\n

The connectListener parameter will be added as a listener for the\n'connect' event once.

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createServer([options][, connectionListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Creates a new server. The connectionListener argument is\nautomatically set as a listener for the 'connection' event.

\n

options is an object with the following defaults:

\n\n
{\n  allowHalfOpen: false,\n  pauseOnConnect: false\n}\n
\n\n

If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee 'end' event for more information.

\n

If pauseOnConnect is true, then the socket associated with each incoming\nconnection will be paused, and no data will be read from its handle. This allows\nconnections to be passed between processes without any data being read by the\noriginal process. To begin reading data from a paused socket, call resume().

\n

Here is an example of an 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 the third line from the last would\njust be changed to

\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
\n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "meta": { "added": [ "v0.3.0" ] }, "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 addresses.

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "meta": { "added": [ "v0.3.0" ] }, "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "meta": { "added": [ "v0.3.0" ] }, "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.

\n\n\n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "type": "module", "displayName": "Net" }, { "textRaw": "OS", "name": "os", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The os module provides a number of operating system-related utility methods.\nIt can be accessed using:

\n
const os = require('os');\n
\n", "properties": [ { "textRaw": "`EOL` {string} ", "type": "string", "name": "EOL", "meta": { "added": [ "v0.7.8" ] }, "desc": "

A string constant defining the operating system-specific end-of-line marker:

\n\n" }, { "textRaw": "`constants` {Object} ", "type": "Object", "name": "constants", "meta": { "added": [ "v6.3.0" ] }, "desc": "

Returns an object containing commonly used operating system specific constants\nfor error codes, process signals, and so on. The specific constants currently\ndefined are described in OS Constants.

\n" } ], "methods": [ { "textRaw": "os.arch()", "type": "method", "name": "arch", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.arch() method returns a string identifying the operating system CPU\narchitecture for which the Node.js binary was compiled.

\n

The current possible values are: 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n

Equivalent to process.arch.

\n" }, { "textRaw": "os.cpus()", "type": "method", "name": "cpus", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "params": [] } ], "desc": "

The os.cpus() method returns an array of objects containing information about\neach logical CPU core.

\n

The properties included on each object include:

\n\n

For example:

\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    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 511580,\n      nice: 20,\n      sys: 40900,\n      idle: 1070842510,\n      irq: 0\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 291660,\n      nice: 0,\n      sys: 34360,\n      idle: 1070888000,\n      irq: 10\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 308260,\n      nice: 0,\n      sys: 55410,\n      idle: 1071129970,\n      irq: 880\n    }\n  },\n  {\n    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times: {\n      user: 266450,\n      nice: 1480,\n      sys: 34920,\n      idle: 1072572010,\n      irq: 30\n    }\n  }\n]\n
\n

Note: Because nice values are UNIX-specific, on Windows the nice values of\nall processors are always 0.

\n" }, { "textRaw": "os.endianness()", "type": "method", "name": "endianness", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.endianness() method returns a string identifying the endianness of the\nCPU for which the Node.js binary was compiled.

\n

Possible values are:

\n\n" }, { "textRaw": "os.freemem()", "type": "method", "name": "freemem", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [] }, { "params": [] } ], "desc": "

The os.freemem() method returns the amount of free system memory in bytes as\nan integer.

\n" }, { "textRaw": "os.homedir()", "type": "method", "name": "homedir", "meta": { "added": [ "v2.3.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.homedir() method returns the home directory of the current user as a\nstring.

\n" }, { "textRaw": "os.hostname()", "type": "method", "name": "hostname", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.hostname() method returns the hostname of the operating system as a\nstring.

\n" }, { "textRaw": "os.loadavg()", "type": "method", "name": "loadavg", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "params": [] } ], "desc": "

The os.loadavg() method returns an array containing the 1, 5, and 15 minute\nload averages.

\n

The load average is a measure of system activity, calculated by the operating\nsystem and expressed as a fractional number. As a rule of thumb, the load\naverage should ideally be less than the number of logical CPUs in the system.

\n

The load average is a UNIX-specific concept with no real equivalent on\nWindows platforms. On Windows, the return value is always [0, 0, 0].

\n" }, { "textRaw": "os.networkInterfaces()", "type": "method", "name": "networkInterfaces", "meta": { "added": [ "v0.6.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The os.networkInterfaces() method returns an object containing only network\ninterfaces that have been assigned a network 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\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    },\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      internal: true\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    },\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      internal: false\n    }\n  ]\n}\n
\n" }, { "textRaw": "os.platform()", "type": "method", "name": "platform", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.platform() method returns a string identifying the operating system\nplatform as set during compile time of Node.js.

\n

Currently possible values are:

\n\n

Equivalent to process.platform.

\n

Note: The value 'android' may also be returned if the Node.js is built on\nthe Android operating system. However, Android support in Node.js is considered\nto be experimental at this time.

\n" }, { "textRaw": "os.release()", "type": "method", "name": "release", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.release() method returns a string identifying the operating system\nrelease.

\n

Note: On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, GetVersionExW() is used. Please see\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.

\n" }, { "textRaw": "os.tmpdir()", "type": "method", "name": "tmpdir", "meta": { "added": [ "v0.9.9" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.tmpdir() method returns a string specifying the operating system's\ndefault directory for temporary files.

\n" }, { "textRaw": "os.totalmem()", "type": "method", "name": "totalmem", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [] }, { "params": [] } ], "desc": "

The os.totalmem() method returns the total amount of system memory in bytes\nas an integer.

\n" }, { "textRaw": "os.type()", "type": "method", "name": "type", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The os.type() method returns a string identifying the operating system name\nas returned by uname(3). For example 'Linux' on Linux, 'Darwin' on macOS\nand 'Windows_NT' on Windows.

\n

Please see https://en.wikipedia.org/wiki/Uname#Examples for additional\ninformation about the output of running uname(3) on various operating\nsystems.

\n" }, { "textRaw": "os.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [] }, { "params": [] } ], "desc": "

The os.uptime() method returns the system uptime in number of seconds.

\n

Note: On Windows the returned value includes fractions of a second.\nUse Math.floor() to get whole seconds.

\n" }, { "textRaw": "os.userInfo([options])", "type": "method", "name": "userInfo", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`options` {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", "default": "utf8", "type": "string", "desc": "Character encoding used to interpret resulting strings. If `encoding` is set to `'buffer'`, the `username`, `shell`, and `homedir` values will be `Buffer` instances." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

The os.userInfo() method returns information about the currently effective\nuser — on POSIX platforms, this is typically a subset of the password file. The\nreturned object includes the username, uid, gid, shell, and homedir.\nOn Windows, the uid and gid 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 several\nenvironment variables for the home directory before falling back to the\noperating system response.

\n" } ], "modules": [ { "textRaw": "OS Constants", "name": "os_constants", "desc": "

The following constants are exported by os.constants. Note: Not all\nconstants will be available on every operating system.

\n", "modules": [ { "textRaw": "Signal Constants", "name": "signal_constants", "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
\n\n", "type": "module", "displayName": "Signal Constants" }, { "textRaw": "Error Constants", "name": "error_constants", "desc": "

The following error constants are exported by os.constants.errno:

\n", "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 currently 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.\n Note that while ENOTSUP and EOPNOTSUPP have the same value on Linux,\n 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
\n\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 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.
\n\n", "type": "module", "displayName": "Windows Specific Error Constants" } ], "type": "module", "displayName": "Error Constants" }, { "textRaw": "libuv Constants", "name": "libuv_constants", "desc": "\n \n \n \n \n \n \n \n \n
ConstantDescription
UV_UDP_REUSEADDR
\n\n\n\n", "type": "module", "displayName": "libuv Constants" } ], "type": "module", "displayName": "OS Constants" } ], "type": "module", "displayName": "OS" }, { "textRaw": "Path", "name": "path", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The path module provides utilities for working with file and directory paths.\nIt can be accessed using:

\n
const path = require('path');\n
\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

For example, using the path.basename() function with the Windows file path\nC:\\temp\\myfile.html, will yield different results when running on POSIX than\nwhen run on 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", "type": "module", "displayName": "Windows vs. POSIX" } ], "methods": [ { "textRaw": "path.basename(path[, ext])", "type": "method", "name": "basename", "meta": { "added": [ "v0.1.25" ] }, "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", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "ext", "optional": true } ] } ], "desc": "

The path.basename() methods returns the last portion of a path, similar to\nthe Unix basename command. Trailing directory separators are ignored, see\npath.sep.

\n

For example:

\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

A TypeError is thrown if path is not a string or if ext is given\nand is not a string.

\n" }, { "textRaw": "path.dirname(path)", "type": "method", "name": "dirname", "meta": { "added": [ "v0.1.16" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" } ] }, { "params": [ { "name": "path" } ] } ], "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

For example:

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

\n" }, { "textRaw": "path.extname(path)", "type": "method", "name": "extname", "meta": { "added": [ "v0.1.25" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" } ] }, { "params": [ { "name": "path" } ] } ], "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 the\nfirst character of the basename of path (see path.basename()) is ., then\nan empty string is returned.

\n

For example:

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

A TypeError is thrown if path is not a string.

\n" }, { "textRaw": "path.format(pathObject)", "type": "method", "name": "format", "meta": { "added": [ "v0.11.15" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`pathObject` {Object} ", "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" } ], "name": "pathObject", "type": "Object" } ] }, { "params": [ { "name": "pathObject" } ] } ], "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

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
\n" }, { "textRaw": "path.isAbsolute(path)", "type": "method", "name": "isAbsolute", "meta": { "added": [ "v0.11.2" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" } ] }, { "params": [ { "name": "path" } ] } ], "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.

\n" }, { "textRaw": "path.join([...paths])", "type": "method", "name": "join", "meta": { "added": [ "v0.1.16" ] }, "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", "optional": true } ] }, { "params": [ { "name": "...paths", "optional": true } ] } ], "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

For example:

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

\n" }, { "textRaw": "path.normalize(path)", "type": "method", "name": "normalize", "meta": { "added": [ "v0.1.23" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" } ] }, { "params": [ { "name": "path" } ] } ], "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.

\n" }, { "textRaw": "path.parse(path)", "type": "method", "name": "parse", "meta": { "added": [ "v0.11.15" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [ { "textRaw": "`path` {string} ", "name": "path", "type": "string" } ] }, { "params": [ { "name": "path" } ] } ], "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// {\n//    root : "/",\n//    dir : "/home/user/dir",\n//    base : "file.txt",\n//    ext : ".txt",\n//    name : "file"\n// }\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// {\n//    root : "C:\\\\",\n//    dir : "C:\\\\path\\\\dir",\n//    base : "file.txt",\n//    ext : ".txt",\n//    name : "file"\n// }\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.

\n" }, { "textRaw": "path.relative(from, to)", "type": "method", "name": "relative", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`from` {string} ", "name": "from", "type": "string" }, { "textRaw": "`to` {string} ", "name": "to", "type": "string" } ] }, { "params": [ { "name": "from" }, { "name": "to" } ] } ], "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.

\n" }, { "textRaw": "path.resolve([...paths])", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.4" ] }, "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", "optional": true } ] }, { "params": [ { "name": "...paths", "optional": true } ] } ], "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.

\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

For example:

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

\n" } ], "properties": [ { "textRaw": "`delimiter` {string} ", "type": "string", "name": "delimiter", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Provides the platform-specific path delimiter:

\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
\n" }, { "textRaw": "`posix` {Object} ", "type": "Object", "name": "posix", "meta": { "added": [ "v0.11.15" ] }, "desc": "

The path.posix property provides access to POSIX specific implementations\nof the path methods.

\n" }, { "textRaw": "`sep` {string} ", "type": "string", "name": "sep", "meta": { "added": [ "v0.7.9" ] }, "desc": "

Provides the platform-specific path segment separator:

\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

Note: On Windows, both the forward slash (/) and backward slash (\\) are\naccepted as path segment separators; however, the path methods only add\nbackward slashes (\\).

\n" }, { "textRaw": "`win32` {Object} ", "type": "Object", "name": "win32", "meta": { "added": [ "v0.11.15" ] }, "desc": "

The path.win32 property provides access to Windows-specific implementations\nof the path methods.

\n\n\n" } ], "type": "module", "displayName": "Path" }, { "textRaw": "Punycode", "name": "punycode", "introduced_in": "v0.10.0", "stability": 0, "stabilityText": "Deprecated", "desc": "

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.

\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

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

\n", "methods": [ { "textRaw": "punycode.decode(string)", "type": "method", "name": "decode", "meta": { "added": [ "v0.5.1" ] }, "signatures": [ { "params": [ { "textRaw": "`string` {string} ", "name": "string", "type": "string" } ] }, { "params": [ { "name": "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
\n" }, { "textRaw": "punycode.encode(string)", "type": "method", "name": "encode", "meta": { "added": [ "v0.5.1" ] }, "signatures": [ { "params": [ { "textRaw": "`string` {string} ", "name": "string", "type": "string" } ] }, { "params": [ { "name": "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
\n" }, { "textRaw": "punycode.toASCII(domain)", "type": "method", "name": "toASCII", "meta": { "added": [ "v0.6.1" ] }, "signatures": [ { "params": [ { "textRaw": "`domain` {string} ", "name": "domain", "type": "string" } ] }, { "params": [ { "name": "domain" } ] } ], "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
\n" }, { "textRaw": "punycode.toUnicode(domain)", "type": "method", "name": "toUnicode", "meta": { "added": [ "v0.6.1" ] }, "signatures": [ { "params": [ { "textRaw": "`domain` {string} ", "name": "domain", "type": "string" } ] }, { "params": [ { "name": "domain" } ] } ], "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
\n" } ], "properties": [ { "textRaw": "punycode.ucs2", "name": "ucs2", "meta": { "added": [ "v0.7.0" ] }, "modules": [ { "textRaw": "punycode.ucs2.decode(string)", "name": "punycode.ucs2.decode(string)", "meta": { "added": [ "v0.7.0" ] }, "desc": "\n

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
\n", "type": "module", "displayName": "punycode.ucs2.decode(string)" }, { "textRaw": "punycode.ucs2.encode(codePoints)", "name": "punycode.ucs2.encode(codepoints)", "meta": { "added": [ "v0.7.0" ] }, "desc": "\n

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
\n", "type": "module", "displayName": "punycode.ucs2.encode(codePoints)" } ] }, { "textRaw": "punycode.version", "name": "version", "meta": { "added": [ "v0.6.1" ] }, "desc": "

Returns a string identifying the current Punycode.js version number.

\n\n\n" } ], "type": "module", "displayName": "Punycode" }, { "textRaw": "Query String", "name": "querystring", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The querystring module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:

\n
const querystring = require('querystring');\n
\n", "methods": [ { "textRaw": "querystring.escape(str)", "type": "method", "name": "escape", "meta": { "added": [ "v0.1.25" ] }, "signatures": [ { "params": [ { "textRaw": "`str` {string} ", "name": "str", "type": "string" } ] }, { "params": [ { "name": "str" } ] } ], "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.

\n" }, { "textRaw": "querystring.parse(str[, sep[, eq[, options]]])", "type": "method", "name": "parse", "meta": { "added": [ "v0.1.25" ] }, "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. Defaults to `'&'`. ", "name": "sep", "type": "string", "desc": "The substring used to delimit key and value pairs in the query string. Defaults to `'&'`.", "optional": true }, { "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. Defaults to `'='`. ", "name": "eq", "type": "string", "desc": ". The substring used to delimit keys and values in the query string. Defaults to `'='`.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`decodeURIComponent` {Function} The function to use when decoding percent-encoded characters in the query string. Defaults to `querystring.unescape()`. ", "name": "decodeURIComponent", "type": "Function", "desc": "The function to use when decoding percent-encoded characters in the query string. Defaults to `querystring.unescape()`." }, { "textRaw": "`maxKeys` {number} Specifies the maximum number of keys to parse. Defaults to `1000`. Specify `0` to remove key counting limitations. ", "name": "maxKeys", "type": "number", "desc": "Specifies the maximum number of keys to parse. Defaults to `1000`. Specify `0` to remove key counting limitations." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "str" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ], "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

Note: The object returned by the querystring.parse() method does not\nprototypically extend from the JavaScript Object. This means that the\ntypical Object methods such as obj.toString(), obj.hasOwnProperty(),\nand others are 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 as illustrated\nin the following example:

\n
// Assuming gbkDecodeURIComponent function already exists...\n\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n                  { decodeURIComponent: gbkDecodeURIComponent });\n
\n" }, { "textRaw": "querystring.stringify(obj[, sep[, eq[, options]]])", "type": "method", "name": "stringify", "meta": { "added": [ "v0.1.25" ] }, "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. Defaults to `'&'`. ", "name": "sep", "type": "string", "desc": "The substring used to delimit key and value pairs in the query string. Defaults to `'&'`.", "optional": true }, { "textRaw": "`eq` {string}. The substring used to delimit keys and values in the query string. Defaults to `'='`. ", "name": "eq", "type": "string", "desc": ". The substring used to delimit keys and values in the query string. Defaults to `'='`.", "optional": true }, { "textRaw": "`options` ", "options": [ { "textRaw": "`encodeURIComponent` {Function} The function to use when converting URL-unsafe characters to percent-encoding in the query string. Defaults to `querystring.escape()`. ", "name": "encodeURIComponent", "type": "Function", "desc": "The function to use when converting URL-unsafe characters to percent-encoding in the query string. Defaults to `querystring.escape()`." } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "obj" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ], "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|boolean|string[]|number[]|boolean[]}\nAny other input values will be coerced to empty strings.

\n

For example:

\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 as illustrated in the\nfollowing example:

\n
// Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n                      { encodeURIComponent: gbkEncodeURIComponent });\n
\n" }, { "textRaw": "querystring.unescape(str)", "type": "method", "name": "unescape", "meta": { "added": [ "v0.1.25" ] }, "signatures": [ { "params": [ { "textRaw": "`str` {string} ", "name": "str", "type": "string" } ] }, { "params": [ { "name": "str" } ] } ], "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.

\n\n\n" } ], "type": "module", "displayName": "querystring" }, { "textRaw": "Readline", "name": "readline", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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

\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

Note Once this code is invoked, the Node.js application will not\nterminate until the readline.Interface is closed because the interface\nwaits for data to be received on the input stream.

\n", "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "meta": { "added": [ "v0.1.104" ] }, "desc": "

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.

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.98" ] }, "desc": "

The 'close' event is emitted when one of the following occur:

\n\n

The listener function is called without passing any arguments.

\n

The readline.Interface instance is finished once the 'close' event is\nemitted.

\n", "params": [] }, { "textRaw": "Event: 'line'", "type": "event", "name": "line", "meta": { "added": [ "v0.1.98" ] }, "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 the <Enter>, or <Return> keys.

\n

The listener function is called with a string containing the single line of\nreceived input.

\n

For example:

\n
rl.on('line', (input) => {\n  console.log(`Received: ${input}`);\n});\n
\n", "params": [] }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "meta": { "added": [ "v0.7.5" ] }, "desc": "

The 'pause' event is emitted when one of the following occur:

\n\n

The listener function is called without passing any arguments.

\n

For example:

\n
rl.on('pause', () => {\n  console.log('Readline paused.');\n});\n
\n", "params": [] }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "meta": { "added": [ "v0.7.5" ] }, "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
\n", "params": [] }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "meta": { "added": [ "v0.7.5" ] }, "desc": "

The 'SIGCONT' event is emitted when a Node.js process previously moved into\nthe background using <ctrl>-Z (i.e. SIGTSTP) is then brought back to the\nforeground using fg(1).

\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

For example:

\n
rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});\n
\n

Note: The 'SIGCONT' event is not supported on Windows.

\n", "params": [] }, { "textRaw": "Event: 'SIGINT'", "type": "event", "name": "SIGINT", "meta": { "added": [ "v0.3.0" ] }, "desc": "

The 'SIGINT' event is emitted whenever the input stream receives a\n<ctrl>-C input, known typically as SIGINT. If there are no 'SIGINT' event\nlisteners registered when the input stream receives a SIGINT, the 'pause'\nevent will be emitted.

\n

The listener function is invoked without passing any arguments.

\n

For example:

\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
\n", "params": [] }, { "textRaw": "Event: 'SIGTSTP'", "type": "event", "name": "SIGTSTP", "meta": { "added": [ "v0.7.5" ] }, "desc": "

The 'SIGTSTP' event is emitted when the input stream receives a <ctrl>-Z\ninput, typically known as SIGTSTP. If there are no SIGTSTP event listeners\nregistered when the input stream receives a SIGTSTP, the Node.js process\nwill be sent to the background.

\n

When the program is resumed using fg(1), 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

For example:

\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

Note: The 'SIGTSTP' event is not supported on Windows.

\n", "params": [] } ], "methods": [ { "textRaw": "rl.close()", "type": "method", "name": "close", "meta": { "added": [ "v0.1.98" ] }, "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", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "meta": { "added": [ "v0.3.4" ] }, "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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "meta": { "added": [ "v0.1.98" ] }, "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`.", "optional": true } ] }, { "params": [ { "name": "preserveCursor", "optional": true } ] } ], "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.

\n" }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "meta": { "added": [ "v0.3.3" ] }, "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": "`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`." } ] }, { "params": [ { "name": "query" }, { "name": "callback" } ] } ], "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

Example usage:

\n
rl.question('What is your favorite food? ', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});\n
\n

Note: The callback function passed to rl.question() does not follow the\ntypical pattern of accepting an Error object or null as the first argument.\nThe callback is called with the provided answer as the only argument.

\n" }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "meta": { "added": [ "v0.3.4" ] }, "desc": "

The rl.resume() method resumes the input stream if it has been paused.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.setPrompt(prompt)", "type": "method", "name": "setPrompt", "meta": { "added": [ "v0.1.98" ] }, "signatures": [ { "params": [ { "textRaw": "`prompt` {string} ", "name": "prompt", "type": "string" } ] }, { "params": [ { "name": "prompt" } ] } ], "desc": "

The rl.setPrompt() method sets the prompt that will be written to output\nwhenever rl.prompt() is called.

\n" }, { "textRaw": "rl.write(data[, key])", "type": "method", "name": "write", "meta": { "added": [ "v0.1.98" ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string} ", "name": "data", "type": "string" }, { "textRaw": "`key` {Object} ", "options": [ { "textRaw": "`ctrl` {boolean} `true` to indicate the `` key. ", "name": "ctrl", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`meta` {boolean} `true` to indicate the `` key. ", "name": "meta", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`shift` {boolean} `true` to indicate the `` key. ", "name": "shift", "type": "boolean", "desc": "`true` to indicate the `` key." }, { "textRaw": "`name` {string} The name of the a key. ", "name": "name", "type": "string", "desc": "The name of the a key." } ], "name": "key", "type": "Object", "optional": true } ] }, { "params": [ { "name": "data" }, { "name": "key", "optional": true } ] } ], "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.

\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

For example:

\n
rl.write('Delete this!');\n// Simulate Ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});\n
\n

Note: The rl.write() method will write the data to the readline\nInterface's input as if it were provided by the user.

\n" } ] } ], "methods": [ { "textRaw": "readline.clearLine(stream, dir)", "type": "method", "name": "clearLine", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable} ", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`dir` {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" } ], "name": "dir", "type": "number" } ] }, { "params": [ { "name": "stream" }, { "name": "dir" } ] } ], "desc": "

The readline.clearLine() method clears current line of given TTY stream\nin a specified direction identified by dir.

\n" }, { "textRaw": "readline.clearScreenDown(stream)", "type": "method", "name": "clearScreenDown", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable} ", "name": "stream", "type": "stream.Writable" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

The readline.clearScreenDown() method clears the given TTY stream from\nthe current position of the cursor down.

\n" }, { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "meta": { "added": [ "v0.1.98" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {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. Defaults to checking `isTTY` on the `output` stream upon instantiation. ", "name": "terminal", "type": "boolean", "desc": "`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. Defaults to checking `isTTY` on the `output` stream upon instantiation." }, { "textRaw": "`historySize` {number} maximum number of history lines retained. To disable the history set this value to `0`. Defaults to `30`. 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. ", "name": "historySize", "type": "number", "desc": "maximum number of history lines retained. To disable the history set this value to `0`. Defaults to `30`. 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": "`prompt` - the prompt string to use. Default: `'> '` ", "name": "prompt", "desc": "the prompt string to use. Default: `'> '`" }, { "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. Default to `100` milliseconds. `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. ", "name": "crlfDelay", "type": "number", "desc": "If the delay between `\\r` and `\\n` exceeds `crlfDelay` milliseconds, both `\\r` and `\\n` will be treated as separate end-of-line input. Default to `100` milliseconds. `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." }, { "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. Defaults to `false`. ", "name": "removeHistoryDuplicates", "type": "boolean", "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. Defaults to `false`." } ], "name": "options", "type": "Object" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

The readline.createInterface() method creates a new readline.Interface\ninstance.

\n

For example:

\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", "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
\n", "type": "module", "displayName": "Use of the `completer` Function" } ] }, { "textRaw": "readline.cursorTo(stream, x, y)", "type": "method", "name": "cursorTo", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable} ", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`x` {number} ", "name": "x", "type": "number" }, { "textRaw": "`y` {number} ", "name": "y", "type": "number" } ] }, { "params": [ { "name": "stream" }, { "name": "x" }, { "name": "y" } ] } ], "desc": "

The readline.cursorTo() method moves cursor to the specified position in a\ngiven TTY stream.

\n" }, { "textRaw": "readline.emitKeypressEvents(stream[, interface])", "type": "method", "name": "emitKeypressEvents", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Readable} ", "name": "stream", "type": "stream.Readable" }, { "textRaw": "`interface` {readline.Interface} ", "name": "interface", "type": "readline.Interface", "optional": true } ] }, { "params": [ { "name": "stream" }, { "name": "interface", "optional": true } ] } ], "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

Note: This is automatically called by any readline instance on its input\nif the input 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
\n" }, { "textRaw": "readline.moveCursor(stream, dx, dy)", "type": "method", "name": "moveCursor", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {stream.Writable} ", "name": "stream", "type": "stream.Writable" }, { "textRaw": "`dx` {number} ", "name": "dx", "type": "number" }, { "textRaw": "`dy` {number} ", "name": "dy", "type": "number" } ] }, { "params": [ { "name": "stream" }, { "name": "dx" }, { "name": "dy" } ] } ], "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 input from a filesystem\nReadable stream one line at a time, as illustrated in the following\nexample:

\n
const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n  input: fs.createReadStream('sample.txt')\n});\n\nrl.on('line', (line) => {\n  console.log(`Line from file: ${line}`);\n});\n
\n\n\n" } ], "type": "module", "displayName": "Readline" }, { "textRaw": "REPL", "name": "repl", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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
\n", "modules": [ { "textRaw": "Design and Features", "name": "design_and_features", "desc": "

The repl module exports the repl.REPLServer class. While running, instances\nof repl.REPLServer will accept individual lines of user input, evaluate those\naccording to a user-defined evaluation function, then output the result. Input\nand output may be from stdin and stdout, respectively, or may be connected\nto any Node.js stream.

\n

Instances of repl.REPLServer support automatic completion of inputs,\nsimplistic Emacs-style line editing, multi-line inputs, ANSI-styled output,\nsaving and restoring current REPL session state, error recovery, and\ncustomizable evaluation functions.

\n", "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, entering\nthe .break command (or pressing the <ctrl>-C key combination) will abort\nfurther input or processing of that expression.
  • \n
  • .clear - Resets the REPL context to an empty object and clears any\nmulti-line expression currently 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, <ctrl>-C to cancel)
  • \n
\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 .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", "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 that\nevaluates 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.

\n", "modules": [ { "textRaw": "JavaScript Expressions", "name": "javascript_expressions", "desc": "

The default evaluator supports direct evaluation of JavaScript expressions:

\n\n
> 1 + 1\n2\n> var m = 2\nundefined\n> m + 1\n3\n
\n

Unless otherwise scoped within blocks (e.g. { ... }) or functions, variables\ndeclared either implicitly or using the var keyword are declared at the\nglobal scope.

\n", "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. For example:

\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\n
$ node repl_test.js\n> m\n'message'\n
\n

It is important to note that context properties are not read-only by default.\nTo specify read-only globals, context properties must be defined using\nObject.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
\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\n
> fs.createReadStream('./some/file');\n
\n", "type": "module", "displayName": "Accessing Core Node.js Modules" }, { "textRaw": "Assignment of the `_` (underscore) variable", "name": "assignment_of_the_`_`_(underscore)_variable", "desc": "

The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _ (underscore).

\n\n
> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4\n
\n

Explicitly setting _ to a value will disable this behavior.

\n", "type": "module", "displayName": "Assignment of the `_` (underscore) variable" } ], "type": "module", "displayName": "Default Evaluation" }, { "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').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
\n", "modules": [ { "textRaw": "Recoverable Errors", "name": "recoverable_errors", "desc": "

As a user is typing input into the REPL prompt, pressing the <enter> key will\nsend the current line of input to the eval function. In order to support\nmulti-line input, the eval function can return an instance of repl.Recoverable\nto the provided callback function:

\n
function eval(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
\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 useColors boolean option can be\nspecified at construction to instruct the default writer to use ANSI style\ncodes to colorize the output from the util.inspect() method.

\n

It is possible to fully customize the output of a repl.REPLServer instance\nby passing a new function in using the writer option on construction. The\nfollowing example, for instance, 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
\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\n
$ node\n> a = [1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3\n
\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 '' will disable persistent\nREPL history. Whitespace will be trimmed from the value.
  • \n
  • NODE_REPL_HISTORY_SIZE - Defaults to 1000. Controls how many lines of\nhistory will be persisted if history is available. Must be a positive number.
  • \n
  • NODE_REPL_MODE - May be any of sloppy, strict, or magic. Defaults\nto magic, which will automatically run "strict mode only" statements in\nstrict mode.
  • \n
\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=''.

\n", "modules": [ { "textRaw": "NODE_REPL_HISTORY_FILE", "name": "node_repl_history_file", "meta": { "added": [ "v2.0.0" ], "deprecated": [ "v3.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use `NODE_REPL_HISTORY` instead.", "desc": "

Previously in Node.js/io.js v2.x, REPL history was controlled by using a\nNODE_REPL_HISTORY_FILE environment variable, and the history was saved in JSON\nformat. This variable has now been deprecated, and the old JSON REPL history\nfile will be automatically converted to a simplified plain text format. This new\nfile will be saved to either the user's home directory, or a directory defined\nby the NODE_REPL_HISTORY variable, as documented in the\nEnvironment Variable Options.

\n", "type": "module", "displayName": "NODE_REPL_HISTORY_FILE" } ], "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 you to use with rlwrap.

\n

For example, you could add this to your bashrc file:

\n
alias node="env NODE_NO_READLINE=1 rlwrap node"\n
\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: https://gist.github.com/2209310

\n

For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342

\n\n\n", "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" ] }, "desc": "

The repl.REPLServer class inherits from the readline.Interface class.\nInstances of repl.REPLServer are created using the repl.start() method and\nshould not be created directly using the JavaScript new keyword.

\n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.7.7" ] }, "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 to signal SIGINT,\nor by pressing <ctrl>-D to signal 'end' on the input stream. 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
\n", "params": [] }, { "textRaw": "Event: 'reset'", "type": "event", "name": "reset", "meta": { "added": [ "v0.11.0" ] }, "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 as illustrated in the following simple example:

\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\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
\n", "params": [] } ], "methods": [ { "textRaw": "replServer.defineCommand(keyword, cmd)", "type": "method", "name": "defineCommand", "meta": { "added": [ "v0.3.0" ] }, "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." } ] }, { "params": [ { "name": "keyword" }, { "name": "cmd" } ] } ], "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: function(name) {\n    this.lineParser.reset();\n    this.bufferedCommand = '';\n    console.log(`Hello, ${name}!`);\n    this.displayPrompt();\n  }\n});\nreplServer.defineCommand('saybye', function() {\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
\n" }, { "textRaw": "replServer.displayPrompt([preserveCursor])", "type": "method", "name": "displayPrompt", "meta": { "added": [ "v0.1.91" ] }, "signatures": [ { "params": [ { "textRaw": "`preserveCursor` {boolean} ", "name": "preserveCursor", "type": "boolean", "optional": true } ] }, { "params": [ { "name": "preserveCursor", "optional": true } ] } ], "desc": "

The replServer.displayPrompt() method readies the REPL instance for input\nfrom the user, printing the configured prompt to a new line in the output\nand resuming the input to accept new input.

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

\n" } ] } ], "methods": [ { "textRaw": "repl.start([options])", "type": "method", "name": "start", "meta": { "added": [ "v0.1.91" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object | string} ", "options": [ { "textRaw": "`prompt` {string} The input prompt to display. Defaults to `> `. ", "name": "prompt", "type": "string", "desc": "The input prompt to display. Defaults to `> `." }, { "textRaw": "`input` {stream.Readable} The Readable stream from which REPL input will be read. Defaults to `process.stdin`. ", "name": "input", "type": "stream.Readable", "desc": "The Readable stream from which REPL input will be read. Defaults to `process.stdin`." }, { "textRaw": "`output` {stream.Writable} The Writable stream to which REPL output will be written. Defaults to `process.stdout`. ", "name": "output", "type": "stream.Writable", "desc": "The Writable stream to which REPL output will be written. Defaults to `process.stdout`." }, { "textRaw": "`terminal` {boolean} If `true`, specifies that the `output` should be treated as a TTY terminal, and have ANSI/VT100 escape codes written to it. Defaults to checking the value of the `isTTY` property on the `output` stream upon instantiation. ", "name": "terminal", "type": "boolean", "desc": "If `true`, specifies that the `output` should be treated as a TTY terminal, and have ANSI/VT100 escape codes written to it. Defaults to checking the value of the `isTTY` property on the `output` stream upon instantiation." }, { "textRaw": "`eval` {Function} The function to be used when evaluating each given line of input. Defaults to 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", "desc": "The function to be used when evaluating each given line of input. Defaults to 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." }, { "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. Defaults to the REPL instances `terminal` value. ", "name": "useColors", "type": "boolean", "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. Defaults to the REPL instances `terminal` value." }, { "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. Defaults to `false`. ", "name": "useGlobal", "type": "boolean", "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. Defaults to `false`." }, { "textRaw": "`ignoreUndefined` {boolean} If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. Defaults to `false`. ", "name": "ignoreUndefined", "type": "boolean", "desc": "If `true`, specifies that the default writer will not output the return value of a command if it evaluates to `undefined`. Defaults to `false`." }, { "textRaw": "`writer` {Function} The function to invoke to format the output of each command before writing to `output`. Defaults to [`util.inspect()`][]. ", "name": "writer", "type": "Function", "desc": "The function to invoke to format the output of each command before writing to `output`. Defaults to [`util.inspect()`][]." }, { "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` - A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode, default mode, or a hybrid mode (\"magic\" mode.) Acceptable values are: ", "options": [ { "textRaw": "`repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. ", "name": "repl.REPL_MODE_SLOPPY", "desc": "evaluates expressions in sloppy mode." }, { "textRaw": "`repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`. ", "name": "repl.REPL_MODE_STRICT", "desc": "evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with `'use strict'`." }, { "textRaw": "`repl.REPL_MODE_MAGIC` - attempt to evaluates expressions in default mode. If expressions fail to parse, re-try in strict mode. ", "name": "repl.REPL_MODE_MAGIC", "desc": "attempt to evaluates expressions in default mode. If expressions fail to parse, re-try in strict mode." } ], "name": "replMode", "desc": "A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode, default mode, or a hybrid mode (\"magic\" mode.) Acceptable values are:" }, { "textRaw": "`breakEvalOnSigint` - Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function. Defaults to `false`. ", "name": "breakEvalOnSigint", "desc": "Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is pressed. This cannot be used together with a custom `eval` function. Defaults to `false`." } ], "name": "options", "type": "Object | string", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "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
\n" } ], "type": "module", "displayName": "REPL" }, { "textRaw": "Stream", "name": "stream", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

A stream is an abstract interface for working with streaming data in Node.js.\nThe stream module provides a base API that makes it easy to build objects\nthat implement 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

The stream module can be accessed using:

\n
const stream = require('stream');\n
\n

While it is important for all Node.js users to understand how streams work,\nthe stream module itself is most useful for developers that are creating new\ntypes of stream instances. Developers who are primarily consuming stream\nobjects will rarely (if ever) have need to use the stream module directly.

\n", "modules": [ { "textRaw": "Organization of this Document", "name": "organization_of_this_document", "desc": "

This document is divided into two primary sections with a third section for\nadditional notes. The first section explains the elements of the stream API that\nare required to use streams within an application. The second section explains\nthe elements of the API that are required to implement new types of streams.

\n", "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", "modules": [ { "textRaw": "Object Mode", "name": "object_mode", "desc": "

All streams created by Node.js APIs operate exclusively on strings and Buffer\nobjects. It is possible, however, for stream implementations to work with other\ntypes of JavaScript values (with the exception of null, which serves a special\npurpose within streams). Such streams are considered to operate in "object\nmode".

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

\n", "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 that can be retrieved using writable._writableState.getBuffer() or\nreadable._readableState.buffer, respectively.

\n

The amount of data potentially buffered depends on the highWaterMark option\npassed into the streams 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

Because Duplex and Transform streams are both Readable and Writable,\neach maintain two separate internal buffers used for reading and writing,\nallowing each side to operate independently of the other while maintaining an\nappropriate and efficient flow of data. For example, net.Socket instances\nare Duplex streams whose Readable side allows consumption of data received\nfrom the socket and whose Writable side allows writing data to the socket.\nBecause data may be written to the socket at a faster or slower rate than data\nis received, it is important for each side to operate (and buffer) independently\nof the other.

\n" } ], "type": "module", "displayName": "Types of Streams" } ], "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 Readable.

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

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

Note: Some of these examples are actually Duplex streams that implement\nthe Writable 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
\n", "classes": [ { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "meta": { "added": [ "v0.9.4" ] }, "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.9.4" ] }, "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

Not all Writable streams will emit the 'close' event.

\n", "params": [] }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "meta": { "added": [ "v0.9.4" ] }, "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
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ] }, "params": [], "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

Note: The stream is not closed when the 'error' event is emitted.

\n" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v0.9.4" ] }, "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.end('This is the end\\n');\nwriter.on('finish', () => {\n  console.error('All writes are now complete.');\n});\n
\n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "meta": { "added": [ "v0.9.4" ] }, "params": [], "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.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\n
\n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "meta": { "added": [ "v0.9.4" ] }, "params": [], "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
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n  console.error('Something has stopped piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
\n" } ], "methods": [ { "textRaw": "writable.cork()", "type": "method", "name": "cork", "meta": { "added": [ "v0.11.2" ] }, "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 avoid a situation where writing\nmany small chunks of data to a stream do not cause a backup in the internal\nbuffer that would have an adverse impact on performance. In such situations,\nimplementations that implement the writable._writev() method can perform\nbuffered writes in a more optimized manner.

\n

See also: writable.uncork().

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.end([chunk][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {string|Buffer|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string or a `Buffer`. For object mode streams, `chunk` may be any JavaScript value other than `null`. ", "name": "chunk", "type": "string|Buffer|any", "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string or a `Buffer`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "optional": true }, { "textRaw": "`encoding` {string} The encoding, if `chunk` is a String ", "name": "encoding", "type": "string", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "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. If provided, the optional callback function is attached as a listener\nfor the 'finish' event.

\n

Calling the stream.write() method after calling\nstream.end() will raise an error.

\n
// write 'hello, ' and then end with 'world!'\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!\n
\n" }, { "textRaw": "writable.setDefaultEncoding(encoding)", "type": "method", "name": "setDefaultEncoding", "meta": { "added": [ "v0.11.15" ] }, "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" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.

\n" }, { "textRaw": "writable.uncork()", "type": "method", "name": "uncork", "meta": { "added": [ "v0.11.2" ] }, "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 same\nnumber 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().

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.9.4" ] }, "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} The data to write ", "name": "chunk", "type": "string|Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {string} The encoding, if `chunk` is a String ", "name": "encoding", "type": "string", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "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", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "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 may or may not be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n'error' event.

\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 an '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.

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

\n", "modules": [ { "textRaw": "Two Modes", "name": "two_modes", "desc": "

Readable streams effectively operate in one of two modes: flowing and paused.

\n

When 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

In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.

\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 any 'data' event\nhandlers, and removing all pipe destinations 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

Note: For backwards compatibility reasons, removing 'data' event\nhandlers will not automatically pause the stream. Also, if there are piped\ndestinations, then calling stream.pause() will not guarantee\nthat the stream will remain paused once those destinations drain and ask for\nmore data.

\n

Note: If a Readable is switched into flowing mode and there are no\nconsumers available to handle the data, that data will be lost. This can occur,\nfor instance, 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", "type": "module", "displayName": "Two Modes" }, { "textRaw": "Three States", "name": "three_states", "desc": "

The "two modes" of operation for a Readable stream are a simplified abstraction\nfor the more complicated internal state management that is happening within the\nReadable stream implementation.

\n

Specifically, at any given point in time, every Readable is in one of three\npossible states:

\n
    \n
  • readable._readableState.flowing = null
  • \n
  • readable._readableState.flowing = false
  • \n
  • readable._readableState.flowing = true
  • \n
\n

When readable._readableState.flowing is null, no mechanism for consuming the\nstreams data is provided so the stream will not generate its data. While in this\nstate, attaching a listener for the 'data' event, calling the readable.pipe()\nmethod, or calling the readable.resume() method will switch\nreadable._readableState.flowing to true, causing the Readable to begin\nactively emitting events as data is generated.

\n

Calling readable.pause(), readable.unpipe(), or receiving "back pressure"\nwill cause the readable._readableState.flowing 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\nwould not cause readable._readableState.flowing to switch to true.

\n
const { PassThrough, Writable } = require('stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// flowing 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 'data' being emitted\n
\n

While readable._readableState.flowing is false, data may be accumulating\nwithin the streams internal buffer.

\n", "type": "module", "displayName": "Three States" }, { "textRaw": "Choose One", "name": "choose_one", "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.

\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.pause()/readable.resume() APIs.

\n", "type": "module", "displayName": "Choose One" } ], "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "meta": { "added": [ "v0.9.4" ] }, "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.9.4" ] }, "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

Not all Readable streams will emit the 'close' event.

\n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "meta": { "added": [ "v0.9.4" ] }, "params": [], "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
\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "meta": { "added": [ "v0.9.4" ] }, "desc": "

The 'end' event is emitted when there is no more data to be consumed from\nthe stream.

\n

Note: The 'end' event will not be emitted unless the data is\ncompletely consumed. This can be accomplished by switching the stream into\nflowing mode, or by calling stream.read() repeatedly until\nall data has been consumed.

\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
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ] }, "params": [], "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.

\n" }, { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "meta": { "added": [ "v0.9.4" ] }, "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', () => {\n  // there is some data to read now\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

Note: In general, the readable.pipe() and 'data' event mechanisms are\neasier to understand than the 'readable' event.\nHowever, handling 'readable' might result in increased throughput.

\n", "params": [] } ], "methods": [ { "textRaw": "readable.isPaused()", "type": "method", "name": "isPaused", "meta": { "added": [ "v0.11.14" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [] }, { "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
\n" }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {this} ", "name": "return", "type": "this" }, "params": [] }, { "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" }, { "textRaw": "readable.pipe(destination[, options])", "type": "method", "name": "pipe", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "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 ", "options": [ { "textRaw": "`end` {boolean} End the writer when the reader ends. Defaults to `true`. ", "name": "end", "type": "boolean", "desc": "End the writer when the reader ends. Defaults to `true`." } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "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 so\nthat the destination Writable stream is not overwhelmed by a faster Readable\nstream.

\n

The following example pipes all of the data from the readable into a file\nnamed file.txt:

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

\n

The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:

\n
const 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,\nas illustrated in the following example:

\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

Note: The process.stderr and process.stdout Writable streams are\nnever closed until the Node.js process exits, regardless of the specified\noptions.

\n" }, { "textRaw": "readable.read([size])", "type": "method", "name": "read", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer|null} ", "name": "return", "type": "string|Buffer|null" }, "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.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "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 readable.read() method should only be called on Readable streams operating\nin paused mode. In flowing mode, readable.read() is called automatically until\nthe internal buffer is fully drained.

\n
const readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log(`Received ${chunk.length} bytes of data.`);\n  }\n});\n
\n

In general, it is recommended that developers avoid the use of the 'readable'\nevent and the readable.read() method in favor of using either\nreadable.pipe() or the 'data' event.

\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

Note: If the readable.read() method returns a chunk of data, a 'data'\nevent will also be emitted.

\n

Note: Calling stream.read([size]) after the 'end'\nevent has been emitted will return null. No runtime error will be raised.

\n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {this} ", "name": "return", "type": "this" }, "params": [] }, { "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 as illustrated in the\nfollowing example:

\n
getReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });\n
\n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "meta": { "added": [ "v0.9.4" ] }, "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." } ] }, { "params": [ { "name": "encoding" } ] } ], "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 through\nthe stream that would otherwise become improperly decoded if simply pulled from\nthe 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
\n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe ", "name": "destination", "type": "stream.Writable", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "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 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
\n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "meta": { "added": [ "v0.9.11" ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer|string", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

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

Note: The stream.unshift(chunk) method cannot be called after the\n'end' event has 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').StringDecoder;\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

Note: Unlike stream.push(chunk), stream.unshift(chunk)\nwill not end the reading process by resetting the internal reading state of the\nstream. This can cause unexpected results if readable.unshift() is called\nduring a read (i.e. from within a stream._read()\nimplementation on a custom stream). Following the call to readable.unshift()\nwith an immediate stream.push('') will reset the reading state\nappropriately, however it is best to simply avoid calling readable.unshift()\nwhile in the process of performing a read.

\n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

Versions of Node.js prior to v0.10 had streams that did not implement the\nentire stream module API as it is currently defined. (See Compatibility\nfor 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

For example:

\n
const OldReader = require('./old-api-module.js').OldReader;\nconst Readable = require('stream').Readable;\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});\n
\n" } ] } ], "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" ] }, "desc": "

Duplex streams are streams that implement both the Readable and\nWritable interfaces.

\n

Examples of Duplex streams include:

\n\n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "meta": { "added": [ "v0.9.4" ] }, "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\n" } ], "type": "misc", "displayName": "Duplex and Transform Streams" } ] }, { "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
const Writable = require('stream').Writable;\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\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

Use-case

\n
\n

Class

\n
\n

Method(s) to implement

\n
\n

Reading only

\n
\n

Readable

\n
\n

_read

\n
\n

Writing only

\n
\n

Writable

\n
\n

_write, _writev

\n
\n

Reading and writing

\n
\n

Duplex

\n
\n

_read, _write, _writev

\n
\n

Operate on written data, then read the result

\n
\n

Transform

\n
\n

_transform, _flush

\n
\n\n

Note: The implementation code for a stream should never call the "public"\nmethods of a stream that are intended for use by consumers (as described in\nthe API for Stream Consumers section). Doing so may lead to adverse\nside effects in application code consuming the stream.

\n", "miscs": [ { "textRaw": "Simplified Construction", "name": "simplified_construction", "desc": "

For many simple cases, it is possible to construct 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

For example:

\n
const Writable = require('stream').Writable;\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  }\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() method. The\nwritable._writev() method may also be implemented.

\n", "methods": [ { "textRaw": "Constructor: new stream.Writable([options])", "type": "method", "name": "Writable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. Defaults to `16384` (16kb), or `16` for `objectMode` streams. ", "name": "highWaterMark", "type": "number", "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`. Defaults to `16384` (16kb), or `16` for `objectMode` streams." }, { "textRaw": "`decodeStrings` {boolean} Whether or not to decode strings into Buffers before passing them to [`stream._write()`][stream-_write]. Defaults to `true` ", "name": "decodeStrings", "type": "boolean", "desc": "Whether or not to decode strings into Buffers before passing them to [`stream._write()`][stream-_write]. Defaults to `true`" }, { "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 or `Buffer` if supported by the stream implementation. Defaults to `false` ", "name": "objectMode", "type": "boolean", "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 or `Buffer` if supported by the stream implementation. Defaults to `false`" }, { "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." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

For example:

\n
const Writable = require('stream').Writable;\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').Writable;\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').Writable;\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  }\n});\n
\n" }, { "textRaw": "writable.\\_write(chunk, encoding, callback)", "type": "method", "name": "\\_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string} The chunk to be written. Will **always** be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer|string", "desc": "The chunk to be written. Will **always** be a buffer unless the `decodeStrings` option was set to `false`." }, { "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." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

All Writable stream implementations must provide a\nwritable._write() method to send data to the underlying\nresource.

\n

Note: Transform streams provide their own implementation of the\nwritable._write().

\n

Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Writable\nclass methods only.

\n

The callback method must be called to signal either that the write completed\nsuccessfully or failed with an error. The first argument passed to the\ncallback must be the Error object if the call failed or null if the\nwrite succeeded.

\n

It is important to note that all calls to writable.write() that occur between\nthe time writable._write() is called and the callback is called will cause\nthe written data to be buffered. Once the callback is invoked, the stream will\nemit a 'drain' event. If a stream implementation is capable of processing\nmultiple chunks of data at once, the writable._writev() method should be\nimplemented.

\n

If the decodeStrings property is set in the constructor options, then\nchunk may be a string rather than a Buffer, and encoding will\nindicate the character encoding of the string. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If the decodeStrings property is explicitly set to false,\nthe encoding argument can be safely ignored, and chunk will remain the same\nobject that is passed to .write().

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

\n" }, { "textRaw": "writable.\\_writev(chunks, callback)", "type": "method", "name": "\\_writev", "signatures": [ { "params": [ { "textRaw": "`chunks` {Array} The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`. ", "name": "chunks", "type": "Array", "desc": "The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`." }, { "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." } ] }, { "params": [ { "name": "chunks" }, { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Writable\nclass methods only.

\n

The writable._writev() method may be implemented in addition to\nwritable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented, the method will be called with\nall chunks of data currently buffered in the write queue.

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

\n" } ], "modules": [ { "textRaw": "Errors While Writing", "name": "errors_while_writing", "desc": "

It is recommended that errors occurring during the processing of the\nwritable._write() and writable._writev() methods are reported by invoking\nthe callback and passing the error as the first argument. This will cause an\n'error' event to be emitted by the Writable. Throwing an Error from within\nwritable._write() can result in unexpected and inconsistent behavior depending\non how the stream is being used. Using the callback ensures consistent and\npredictable handling of errors.

\n
const Writable = require('stream').Writable;\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
\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').Writable;\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n\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
\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    const state = this._writableState;\n    this._decoder = new StringDecoder(state.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
\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.

\n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {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. Defaults to `16384` (16kb), or `16` for `objectMode` streams ", "name": "highWaterMark", "type": "number", "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. Defaults to `16384` (16kb), or `16` for `objectMode` streams" }, { "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. Defaults to `null` ", "name": "encoding", "type": "string", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Defaults to `null`" }, { "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. Defaults to `false` ", "name": "objectMode", "type": "boolean", "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. Defaults to `false`" }, { "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method. ", "name": "read", "type": "Function", "desc": "Implementation for the [`stream._read()`][stream-_read] method." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

For example:

\n
const Readable = require('stream').Readable;\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').Readable;\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').Readable;\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  }\n});\n
\n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {number} Number of bytes to read asynchronously ", "name": "size", "type": "number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods 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, the\nimplementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() should continue reading\nfrom the resource and pushing data until readable.push() returns false. Only\nwhen _read() is called again after it has stopped should it resume pushing\nadditional data onto the queue.

\n

Note: Once the readable._read() method has been called, it will not be\ncalled again until the readable.push() method is 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.

\n" }, { "textRaw": "readable.push(chunk[, encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if additional chunks of data may continued to be pushed; `false` otherwise. ", "name": "return", "type": "boolean", "desc": "`true` if additional chunks of data may continued to be pushed; `false` otherwise." }, "params": [ { "textRaw": "`chunk` {Buffer|null|string} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer|null|string", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {string} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "string", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

When chunk is a Buffer or string, the chunk of data will be added to the\ninternal queue for users of the stream to consume. Passing chunk as null\nsignals the end of the stream (EOF), after which no more 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 as illustrated in the following example:

\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

Note: The readable.push() method is intended be called only by Readable\nImplementers, and only from within the readable._read() method.

\n" } ], "modules": [ { "textRaw": "Errors While Reading", "name": "errors_while_reading", "desc": "

It is recommended that errors occurring during the processing of the\nreadable._read() method are emitted using the 'error' event rather than\nbeing thrown. Throwing an Error from within readable._read() can result in\nunexpected and inconsistent behavior depending on whether the stream is\noperating in flowing or paused mode. Using the 'error' event ensures\nconsistent and predictable handling of errors.

\n\n
const Readable = require('stream').Readable;\n\nconst myReadable = new Readable({\n  read(size) {\n    if (checkSomeErrorCondition()) {\n      process.nextTick(() => this.emit('error', err));\n      return;\n    }\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').Readable;\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 = '' + i;\n      const buf = Buffer.from(str, 'ascii');\n      this.push(buf);\n    }\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 Writable,\nsuch 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

Note: The stream.Duplex class prototypically inherits from stream.Readable\nand parasitically from stream.Writable, but instanceof will work properly\nfor both base classes due to overriding Symbol.hasInstance\non stream.Writable.

\n

Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.

\n", "methods": [ { "textRaw": "new stream.Duplex(options)", "type": "method", "name": "Duplex", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: ", "options": [ { "textRaw": "`allowHalfOpen` {boolean} Defaults to `true`. If set to `false`, then the stream will automatically end the writable side when the readable side ends. ", "name": "allowHalfOpen", "type": "boolean", "desc": "Defaults to `true`. If set to `false`, then the stream will automatically end the writable side when the readable side ends." }, { "textRaw": "`readableObjectMode` {boolean} Defaults to `false`. Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. ", "name": "readableObjectMode", "type": "boolean", "desc": "Defaults to `false`. Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`writableObjectMode` {boolean} Defaults to `false`. Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. ", "name": "writableObjectMode", "type": "boolean", "desc": "Defaults to `false`. Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

For example:

\n
const Duplex = require('stream').Duplex;\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').Duplex;\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').Duplex;\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\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').Duplex;\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 Writable\nsides operate independently of one another despite co-existing within a single\nobject instance.

\n", "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 Readable\nor Writable side using the readableObjectMode and writableObjectMode options\nrespectively.

\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').Transform;\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
\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

Note: There is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will produce output\nthat is either much smaller or much larger 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 readable._read()\nmethods. Custom Transform implementations must implement the\ntransform._transform() method and may also implement\nthe transform._flush() method.

\n

Note: Care must be taken when using Transform streams in that data written\nto the stream can cause the Writable side of the stream to become paused if\nthe output on the Readable side is not consumed.

\n", "methods": [ { "textRaw": "new stream.Transform([options])", "type": "method", "name": "Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} 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." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

For example:

\n
const Transform = require('stream').Transform;\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').Transform;\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').Transform;\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  }\n});\n
\n" }, { "textRaw": "transform.\\_flush(callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be called when remaining data has been flushed. ", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument) to be called when remaining data has been flushed." } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods 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 readable.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.

\n" }, { "textRaw": "transform.\\_transform(chunk, encoding, callback)", "type": "method", "name": "\\_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string} The chunk to be transformed. Will **always** be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer|string", "desc": "The chunk to be transformed. Will **always** be a buffer unless the `decodeStrings` option was set to `false`." }, { "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 this 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 this 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." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods 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 readable.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\nreadable.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.

\n" } ], "modules": [ { "textRaw": "Events: 'finish' and 'end'", "name": "events:_'finish'_and_'end'", "desc": "

The 'finish' and 'end' events are from the stream.Writable\nand stream.Readable classes, respectively. The 'finish' event is emitted\nafter stream.end() is called and all chunks have been processed\nby stream._transform(). The 'end' event is emitted\nafter all data has been output, which occurs after the callback in\ntransform._flush() has been called.

\n", "type": "module", "displayName": "Events: 'finish' and 'end'" } ], "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.

\n" } ], "type": "misc", "displayName": "Implementing a Transform Stream" } ] }, { "textRaw": "Additional Notes", "name": "Additional Notes", "type": "misc", "miscs": [ { "textRaw": "Compatibility with Older Node.js Versions", "name": "Compatibility with Older Node.js Versions", "type": "misc", "desc": "

In versions of Node.js prior to v0.10, the Readable stream interface was\nsimpler, but also less powerful and less useful.

\n
    \n
  • Rather than waiting for calls 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 v0.10, the Readable class was added. For backwards compatibility\nwith older Node.js programs, Readable streams switch into "flowing mode" when a\n'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' method, 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

In versions of Node.js prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node.js v0.10 and beyond, the socket remains\npaused 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\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\n}).listen(1337);\n
\n

In addition to new Readable streams switching into flowing mode,\npre-v0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.

\n" }, { "textRaw": "`readable.read(0)`", "name": "`readable.read(0)`", "desc": "

There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

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

\n", "type": "misc", "displayName": "`readable.read(0)`" }, { "textRaw": "`readable.push('')`", "name": "`readable.push('')`", "desc": "

Use of readable.push('') is not recommended.

\n

Pushing a zero-byte string or Buffer to a stream that is not in object mode\nhas 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.

\n", "type": "misc", "displayName": "`readable.push('')`" }, { "textRaw": "`highWaterMark` discrepency after calling `readable.setEncoding()`", "name": "`highwatermark`_discrepency_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.

\n\n\n", "type": "misc", "displayName": "`highWaterMark` discrepency after calling `readable.setEncoding()`" } ] } ], "type": "module", "displayName": "Stream" }, { "textRaw": "String Decoder", "name": "string_decoder", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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').StringDecoder;\n
\n

The following example shows the basic use of the StringDecoder class.

\n
const StringDecoder = require('string_decoder').StringDecoder;\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').StringDecoder;\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC])));\n
\n", "classes": [ { "textRaw": "Class: new StringDecoder([encoding])", "type": "class", "name": "new", "meta": { "added": [ "v0.1.99" ] }, "desc": "
    \n
  • encoding {string} The character encoding the StringDecoder will use.\nDefaults to 'utf8'.
  • \n
\n

Creates a new StringDecoder instance.

\n", "methods": [ { "textRaw": "stringDecoder.end([buffer])", "type": "method", "name": "end", "meta": { "added": [ "v0.9.3" ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer} A `Buffer` containing the bytes to decode. ", "name": "buffer", "type": "Buffer", "desc": "A `Buffer` containing the bytes to decode.", "optional": true } ] }, { "params": [ { "name": "buffer", "optional": true } ] } ], "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.

\n" }, { "textRaw": "stringDecoder.write(buffer)", "type": "method", "name": "write", "meta": { "added": [ "v0.1.99" ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer} A `Buffer` containing the bytes to decode. ", "name": "buffer", "type": "Buffer", "desc": "A `Buffer` containing the bytes to decode." } ] }, { "params": [ { "name": "buffer" } ] } ], "desc": "

Returns a decoded string, ensuring that any incomplete multibyte characters at\nthe end of the Buffer are omitted from the returned string and stored in an\ninternal buffer for the next call to stringDecoder.write() or\nstringDecoder.end().

\n\n\n" } ] } ], "type": "module", "displayName": "String Decoder" }, { "textRaw": "Timers", "name": "timers", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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.

\n", "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" }, { "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 clearTimeout() or\nclearInterval() (respectively) 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.

\n", "methods": [ { "textRaw": "timeout.ref()", "type": "method", "name": "ref", "meta": { "added": [ "v0.9.1" ] }, "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

Note: By default, all Timeout objects are "ref'd", making it normally\nunnecessary to call timeout.ref() unless timeout.unref() had been called\npreviously.

\n

Returns a reference to the Timeout.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "timeout.unref()", "type": "method", "name": "unref", "meta": { "added": [ "v0.9.1" ] }, "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

Note: Calling timeout.unref() creates an internal timer that will wake the\nNode.js event loop. Creating too many of these can adversely impact performance\nof the Node.js application.

\n

Returns a reference to the Timeout.

\n", "signatures": [ { "params": [] } ] } ] } ], "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.

\n", "methods": [ { "textRaw": "setImmediate(callback[, ...args])", "type": "method", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "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.", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "...args", "optional": true } ] } ], "desc": "

Schedules the "immediate" execution of the callback after I/O events'\ncallbacks and before timers created using setTimeout() and\nsetInterval() are triggered. Returns an Immediate for use with\nclearImmediate().

\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" }, { "textRaw": "setInterval(callback, delay[, ...args])", "type": "method", "name": "setInterval", "meta": { "added": [ "v0.0.1" ] }, "signatures": [ { "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`. ", "name": "delay", "type": "number", "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.", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "...args", "optional": true } ] } ], "desc": "

Schedules repeated execution of callback every delay milliseconds.\nReturns a Timeout for use with clearInterval().

\n

When delay is larger than 2147483647 or less than 1, the delay will be\nset to 1.

\n

If callback is not a function, a TypeError will be thrown.

\n" }, { "textRaw": "setTimeout(callback, delay[, ...args])", "type": "method", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ] }, "signatures": [ { "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`. ", "name": "delay", "type": "number", "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.", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "...args", "optional": true } ] } ], "desc": "

Schedules execution of a one-time callback after delay milliseconds.\nReturns a Timeout for use with clearTimeout().

\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

Note: When delay is larger than 2147483647 or less than 1, the delay\nwill be set to 1.

\n

If callback is not a function, a TypeError will be thrown.

\n" } ], "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", "methods": [ { "textRaw": "clearImmediate(immediate)", "type": "method", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "params": [ { "textRaw": "`immediate` {Immediate} An `Immediate` object as returned by [`setImmediate()`][]. ", "name": "immediate", "type": "Immediate", "desc": "An `Immediate` object as returned by [`setImmediate()`][]." } ] }, { "params": [ { "name": "immediate" } ] } ], "desc": "

Cancels an Immediate object created by setImmediate().

\n" }, { "textRaw": "clearInterval(timeout)", "type": "method", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ] }, "signatures": [ { "params": [ { "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setInterval()`][]. ", "name": "timeout", "type": "Timeout", "desc": "A `Timeout` object as returned by [`setInterval()`][]." } ] }, { "params": [ { "name": "timeout" } ] } ], "desc": "

Cancels a Timeout object created by setInterval().

\n" }, { "textRaw": "clearTimeout(timeout)", "type": "method", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ] }, "signatures": [ { "params": [ { "textRaw": "`timeout` {Timeout} A `Timeout` object as returned by [`setTimeout()`][]. ", "name": "timeout", "type": "Timeout", "desc": "A `Timeout` object as returned by [`setTimeout()`][]." } ] }, { "params": [ { "name": "timeout" } ] } ], "desc": "

Cancels a Timeout object created by setTimeout().

\n\n\n" } ], "type": "module", "displayName": "Cancelling Timers" } ], "type": "module", "displayName": "Timers" }, { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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
\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\n a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
  • \n
\n", "miscs": [ { "textRaw": "Perfect Forward Secrecy", "name": "Perfect Forward Secrecy", "type": "misc", "desc": "

The term "Forward Secrecy" or "Perfect Forward Secrecy" describes a feature of\nkey-agreement (i.e., key-exchange) methods. That is, the server and client keys\nare used to negotiate new temporary keys that are used specifically and only for\nthe current communication session. Practically, this means that even if the\nserver's private key is compromised, communication can only be decrypted by\neavesdroppers 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 name of an alternative\ncurve to use, see tls.createServer() for more info.

\n" }, { "textRaw": "ALPN, NPN and SNI", "name": "ALPN, NPN and SNI", "type": "misc", "desc": "

ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next\nProtocol Negotiation) and, SNI (Server Name Indication) are TLS\nhandshake extensions:

\n
    \n
  • ALPN/NPN - Allows the use of one TLS server for multiple protocols (HTTP,\nSPDY, HTTP/2)
  • \n
  • SNI - Allows the use of one TLS server for multiple hostnames with different\nSSL certificates.
  • \n
\n

Note: Use of ALPN is recommended over NPN. The NPN extension has never been\nformally defined or documented and generally not recommended for use.

\n" }, { "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. Defaults to 3.
  • \n
  • tls.CLIENT_RENEG_WINDOW {number} Specifies the time renegotiation window\nin seconds. Defaults to 600 (10 minutes).
  • \n
\n

Note: The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.

\n

To test the renegotiation limits on a server, connect to it using the OpenSSL\ncommand-line client (openssl s_client -connect address:port) then input\nR<CR> (i.e., the letter R followed by a carriage return) multiple times.

\n" } ], "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.\nCurrently, the default cipher suite is:

\n
ECDHE-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 command\nline switch. For instance, the following makes\nECDHE-RSA-AES128-GCM-SHA256:!RC4 the default TLS cipher suite:

\n
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"\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

Consult OpenSSL cipher list format documentation for details on the format.

\n

Note: 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", "type": "module", "displayName": "Modifying the Default TLS Cipher suite" }, { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "classes": [ { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

The tls.CryptoStream class represents a stream of encrypted data. This class\nhas been deprecated and should no longer be used.

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ] }, "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.

\n" } ] }, { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

Returned by tls.createSecurePair().

\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ] }, "desc": "

The 'secure' event is emitted by the SecurePair object once a secure\nconnection has been established.

\n

As with checking for the server secureConnection\nevent, pair.cleartext.authorized should be inspected to confirm whether the\ncertificate used is properly authorized.

\n", "params": [] } ] } ], "methods": [ { "textRaw": "tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])", "type": "method", "name": "createSecurePair", "meta": { "added": [ "v0.3.2" ], "deprecated": [ "v0.11.3" ] }, "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()`", "optional": true }, { "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.", "optional": true }, { "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`.", "optional": true }, { "textRaw": "`rejectUnauthorized` {boolean} `true` to specify whether a server should automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "`true` to specify whether a server should automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.", "optional": true }, { "textRaw": "`options` ", "options": [ { "textRaw": "`secureContext`: An optional TLS context object from [`tls.createSecureContext()`][] ", "name": "secureContext", "desc": "An optional TLS context object from [`tls.createSecureContext()`][]" }, { "textRaw": "`isServer`: If `true` the TLS socket will be instantiated in server-mode. Defaults to `false`. ", "name": "isServer", "desc": "If `true` the TLS socket will be instantiated in server-mode. Defaults to `false`." }, { "textRaw": "`server` {net.Server} An optional [`net.Server`][] instance ", "name": "server", "type": "net.Server", "desc": "An optional [`net.Server`][] instance" }, { "textRaw": "`requestCert`: Optional, see [`tls.createServer()`][] ", "name": "requestCert", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`rejectUnauthorized`: Optional, see [`tls.createServer()`][] ", "name": "rejectUnauthorized", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`NPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "NPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "ALPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: Optional, see [`tls.createServer()`][] ", "name": "SNICallback", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} An optional `Buffer` instance containing a TLS session. ", "name": "session", "type": "Buffer", "desc": "An optional `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" } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "context", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true }, { "name": "options", "optional": true } ] } ], "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

Note: cleartext has the same API as tls.TLSSocket.

\n

Note: 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
secure_socket = tls.TLSSocket(socket, options);\n
\n

where secure_socket has the same API as pair.cleartext.

\n\n\n" } ], "type": "module", "displayName": "Deprecated APIs" } ], "classes": [ { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "meta": { "added": [ "v0.3.2" ] }, "desc": "

The tls.Server class is a subclass of net.Server that accepts encrypted\nconnections using TLS or SSL.

\n", "events": [ { "textRaw": "Event: 'tlsClientError'", "type": "event", "name": "tlsClientError", "meta": { "added": [ "v6.0.0" ] }, "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
\n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "meta": { "added": [ "v0.9.2" ] }, "desc": "

The 'newSession' event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The listener callback is passed\nthree arguments when called:

\n
    \n
  • sessionId - The TLS session identifier
  • \n
  • sessionData - 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

Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.

\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "meta": { "added": [ "v0.11.13" ] }, "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

Note: The issuer can be null if the certificate is either self-signed or\nthe issuer is not in the root certificates list. (An issuer may be provided\nvia the ca option when establishing the TLS connection.)

\n

Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.

\n

Note: An npm module like asn1.js may be used to parse the certificates.

\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "meta": { "added": [ "v0.9.2" ] }, "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 - The TLS/SSL session identifier
  • \n
  • callback {Function} A callback function to be called when the prior session\nhas been recovered.
  • \n
\n

When called, the event listener may perform a lookup in external storage using\nthe given sessionId and invoke callback(null, sessionData) once finished. If\nthe session cannot be resumed (i.e., doesn't exist in storage) the callback may\nbe invoked as callback(null, null). Calling callback(err) will terminate the\nincoming connection and destroy the socket.

\n

Note: Listening for this event will have an effect only on connections\nestablished after 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
\n", "params": [] }, { "textRaw": "Event: 'secureConnection'", "type": "event", "name": "secureConnection", "meta": { "added": [ "v0.3.2" ] }, "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
  • tlsSocket {tls.TLSSocket} The established TLS socket.
  • \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. Note that depending on the settings\nof the TLS server, unauthorized connections may still be accepted.

\n

The tlsSocket.npnProtocol and tlsSocket.alpnProtocol properties are strings\nthat contain the selected NPN and ALPN protocols, respectively. When both NPN\nand ALPN extensions are received, ALPN takes precedence over NPN and the next\nprotocol is selected by ALPN.

\n

When ALPN has no selected protocol, tlsSocket.alpnProtocol returns false.

\n

The tlsSocket.servername property is a string containing the server name\nrequested via SNI.

\n", "params": [] } ], "methods": [ { "textRaw": "server.addContext(hostname, context)", "type": "method", "name": "addContext", "meta": { "added": [ "v0.5.3" ] }, "signatures": [ { "params": [ { "textRaw": "`hostname` {string} A SNI hostname or wildcard (e.g. `'*'`) ", "name": "hostname", "type": "string", "desc": "A SNI hostname 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)." } ] }, { "params": [ { "name": "hostname" }, { "name": "context" } ] } ], "desc": "

The server.addContext() method adds a secure context that will be used if\nthe client request's SNI hostname matches the supplied hostname (or wildcard).

\n" }, { "textRaw": "server.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.6.0" ] }, "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.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.3.2" ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} An optional listener callback that will be registered to listen for the server instance's `'close'` event. ", "name": "callback", "type": "Function", "desc": "An optional listener callback that will be registered to listen for the server instance's `'close'` event.", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "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.

\n" }, { "textRaw": "server.getTicketKeys()", "type": "method", "name": "getTicketKeys", "meta": { "added": [ "v3.0.0" ] }, "desc": "

Returns a Buffer instance holding the keys currently used for\nencryption/decryption of the TLS Session Tickets

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.listen(port[, hostname][, callback])", "type": "method", "name": "listen", "meta": { "added": [ "v0.3.2" ] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} The TCP/IP port on which to begin listening for connections. A value of `0` (zero) will assign a random port. ", "name": "port", "type": "number", "desc": "The TCP/IP port on which to begin listening for connections. A value of `0` (zero) will assign a random port." }, { "textRaw": "`hostname` {string} The hostname, IPv4, or IPv6 address on which to begin listening for connections. If `undefined`, the server will accept connections on any IPv6 address (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. ", "name": "hostname", "type": "string", "desc": "The hostname, IPv4, or IPv6 address on which to begin listening for connections. If `undefined`, the server will accept connections on any IPv6 address (`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise.", "optional": true }, { "textRaw": "`callback` {Function} A callback function to be invoked when the server has begun listening on the `port` and `hostname`. ", "name": "callback", "type": "Function", "desc": "A callback function to be invoked when the server has begun listening on the `port` and `hostname`.", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

The server.listen() methods instructs the server to begin accepting\nconnections on the specified port and hostname.

\n

This function operates asynchronously. If the callback is given, it will be\ncalled when the server has started listening.

\n

See net.Server for more information.

\n" }, { "textRaw": "server.setTicketKeys(keys)", "type": "method", "name": "setTicketKeys", "meta": { "added": [ "v3.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`keys` {Buffer} The keys used for encryption/decryption of the [TLS Session Tickets][]. ", "name": "keys", "type": "Buffer", "desc": "The keys used for encryption/decryption of the [TLS Session Tickets][]." } ] }, { "params": [ { "name": "keys" } ] } ], "desc": "

Updates the keys for encryption/decryption of the TLS Session Tickets.

\n

Note: The key's Buffer should be 48 bytes long. See ticketKeys option in\ntls.createServer for\nmore information on how it is used.

\n

Note: Changes to the ticket keys are effective only for future server\nconnections. Existing or currently pending server connections will use the\nprevious keys.

\n" } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "meta": { "added": [ "v0.3.2" ] }, "desc": "

Returns the current number of concurrent connections on the server.

\n" } ] }, { "textRaw": "Class: tls.TLSSocket", "type": "class", "name": "tls.TLSSocket", "meta": { "added": [ "v0.11.4" ] }, "desc": "

The tls.TLSSocket is a subclass of net.Socket that performs transparent\nencryption of written data and all required TLS negotiation.

\n

Instances of tls.TLSSocket implement the duplex Stream interface.

\n

Note: Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate() will only return data while the\nconnection is open.

\n", "methods": [ { "textRaw": "new tls.TLSSocket(socket[, options])", "type": "method", "name": "TLSSocket", "meta": { "added": [ "v0.11.4" ] }, "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} ", "options": [ { "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. Defaults to `false`. ", "name": "isServer", "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. Defaults to `false`." }, { "textRaw": "`server` {net.Server} An optional [`net.Server`][] instance. ", "name": "server", "type": "net.Server", "desc": "An optional [`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 optionally 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 optionally set `requestCert` to true to request a client certificate." }, { "textRaw": "`rejectUnauthorized`: Optional, see [`tls.createServer()`][] ", "name": "rejectUnauthorized", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`NPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "NPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`ALPNProtocols`: Optional, see [`tls.createServer()`][] ", "name": "ALPNProtocols", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`SNICallback`: Optional, see [`tls.createServer()`][] ", "name": "SNICallback", "desc": "Optional, see [`tls.createServer()`][]" }, { "textRaw": "`session` {Buffer} An optional `Buffer` instance containing a TLS session. ", "name": "session", "type": "Buffer", "desc": "An optional `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`: Optional 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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing. ", "name": "secureContext", "desc": "Optional 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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing." }, { "textRaw": "...: Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information. ", "name": "...", "desc": "Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "socket" }, { "name": "options", "optional": true } ] } ], "desc": "

Construct a new tls.TLSSocket object from an existing TCP socket.

\n" }, { "textRaw": "tlsSocket.address()", "type": "method", "name": "address", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the bound address, the address family name, and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.,\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getCipher()", "type": "method", "name": "getCipher", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns an object representing the cipher name and the SSL/TLS protocol version\nthat first defined the cipher.

\n

For example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttps://www.openssl.org/docs/man1.0.2/ssl/SSL_CIPHER_get_name.html for more\ninformation.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getEphemeralKeyInfo()", "type": "method", "name": "getEphemeralKeyInfo", "meta": { "added": [ "v5.0.0" ] }, "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 }

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getPeerCertificate([ detailed ])", "type": "method", "name": "getPeerCertificate", "meta": { "added": [ "v0.11.4" ] }, "signatures": [ { "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.", "optional": true } ] }, { "params": [ { "name": "detailed", "optional": true } ] } ], "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate.

\n

If the full certificate chain was requested, each certificate will include a\nissuerCertificate property containing an object representing its issuer's\ncertificate.

\n

For example:

\n
{ subject:\n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuer:\n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  issuerCertificate:\n   { ... another certificate, possibly with a .issuerCertificate ... },\n  raw: < RAW DER buffer >,\n  valid_from: 'Nov 11 09:52:22 2009 GMT',\n  valid_to: 'Nov 6 09:52:22 2029 GMT',\n  fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',\n  serialNumber: 'B9B0D332A1AA5635' }\n
\n

If the peer does not provide a certificate, an empty object will be returned.

\n" }, { "textRaw": "tlsSocket.getProtocol()", "type": "method", "name": "getProtocol", "meta": { "added": [ "v5.7.0" ] }, "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

Example responses include:

\n
    \n
  • SSLv3
  • \n
  • TLSv1
  • \n
  • TLSv1.1
  • \n
  • TLSv1.2
  • \n
  • unknown
  • \n
\n

See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more\ninformation.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the ASN.1 encoded TLS session or undefined if no session was\nnegotiated. Can be used to speed up handshake establishment when reconnecting\nto the server.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getTLSTicket()", "type": "method", "name": "getTLSTicket", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the TLS session ticket or undefined if no session was negotiated.

\n

Note: This only works with client TLS sockets. Useful only for debugging, for\nsession reuse provide session option to tls.connect().

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.renegotiate(options, callback)", "type": "method", "name": "renegotiate", "meta": { "added": [ "v0.11.8" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`rejectUnauthorized` {boolean} ", "name": "rejectUnauthorized", "type": "boolean" }, { "textRaw": "`requestCert` ", "name": "requestCert" } ], "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} A function that will be called when the renegotiation request has been completed. ", "name": "callback", "type": "Function", "desc": "A function that will be called when the renegotiation request has been completed." } ] }, { "params": [ { "name": "options" }, { "name": "callback" } ] } ], "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

Note: This method can be used to request a peer's certificate after the\nsecure connection has been established.

\n

Note: When running as the server, the socket will be destroyed with an error\nafter handshakeTimeout timeout.

\n" }, { "textRaw": "tlsSocket.setMaxSendFragment(size)", "type": "method", "name": "setMaxSendFragment", "meta": { "added": [ "v0.11.11" ] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`. ", "name": "size", "type": "number", "desc": "The maximum TLS fragment size. Defaults to `16384`. The maximum value is `16384`." } ] }, { "params": [ { "name": "size" } ] } ], "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.

\n" } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "meta": { "added": [ "v0.11.13" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "meta": { "added": [ "v0.11.4" ] }, "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 either ALPN or NPN was used,\nthe tlsSocket.alpnProtocol or tlsSocket.npnProtocol properties can be\nchecked to determine the negotiated protocol.

\n", "params": [] } ], "properties": [ { "textRaw": "tlsSocket.authorized", "name": "authorized", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns true if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket instance, otherwise false.

\n" }, { "textRaw": "tlsSocket.authorizationError", "name": "authorizationError", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false.

\n" }, { "textRaw": "tlsSocket.encrypted", "name": "encrypted", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Always returns true. This may be used to distinguish TLS sockets from regular\nnet.Socket instances.

\n" }, { "textRaw": "tlsSocket.localAddress", "name": "localAddress", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the string representation of the local IP address.

\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the numeric representation of the local port.

\n" }, { "textRaw": "tlsSocket.remoteAddress", "name": "remoteAddress", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.

\n" }, { "textRaw": "tlsSocket.remoteFamily", "name": "remoteFamily", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the string representation of the remote IP family. 'IPv4' or 'IPv6'.

\n" }, { "textRaw": "tlsSocket.remotePort", "name": "remotePort", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Returns the numeric representation of the remote port. For example, 443.

\n" } ] } ], "methods": [ { "textRaw": "tls.connect(port[, host][, options][, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ] }, "signatures": [ { "params": [ { "textRaw": "`port` {number} Default value for `options.port`. ", "name": "port", "type": "number", "desc": "Default value for `options.port`." }, { "textRaw": "`host` {string} Optional default value for `options.host`. ", "name": "host", "type": "string", "desc": "Optional default value for `options.host`.", "optional": true }, { "textRaw": "`options` {Object} See [`tls.connect()`][]. ", "name": "options", "type": "Object", "desc": "See [`tls.connect()`][].", "optional": true }, { "textRaw": "`callback` {Function} See [`tls.connect()`][]. ", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][].", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Same as tls.connect() except that port and host can be provided\nas arguments instead of options.

\n

Note: A port or host option, if specified, will take precedence over any port\nor host argument.

\n" }, { "textRaw": "tls.connect(path[, options][, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ] }, "signatures": [ { "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()`][].", "optional": true }, { "textRaw": "`callback` {Function} See [`tls.connect()`][]. ", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][].", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Same as tls.connect() except that path can be provided\nas an argument instead of an option.

\n

Note: A path option, if specified, will take precedence over the path\nargument.

\n" }, { "textRaw": "tls.connect(options[, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ], "changes": [ { "version": "v6.13.0", "pr-url": "https://github.com/nodejs/node/pull/12839", "description": "The `lookup` option is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`host` {string} Host the client should connect to, defaults to 'localhost'. ", "name": "host", "type": "string", "desc": "Host the client should connect to, defaults to 'localhost'." }, { "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. Note that 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. Note that connection/disconnection/destruction of `socket` is the user's responsibility, calling `tls.connect()` will not cause `net.connect()` to be called." }, { "textRaw": "`rejectUnauthorized` {boolean} If `true`, 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. Defaults to `true`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If `true`, 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. Defaults to `true`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer[]} An array of strings or `Buffer`s containing supported NPN 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']`. ", "name": "NPNProtocols", "type": "string[]|Buffer[]", "desc": "An array of strings or `Buffer`s containing supported NPN 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']`." }, { "textRaw": "`ALPNProtocols`: {string[]|Buffer[]} An array of strings or `Buffer`s 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: `['hello', 'world']`.) ", "name": "ALPNProtocols", "type": "string[]|Buffer[]", "desc": "An array of strings or `Buffer`s 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: `['hello', 'world']`.)" }, { "textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. ", "name": "servername", "type": "string", "desc": "Server name for the SNI (Server Name Indication) TLS extension." }, { "textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used (instead of the builtin `tls.checkServerIdentity()` function) when checking the server's hostname 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 hostname 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. Defaults to `1024`. ", "name": "minDHSize", "type": "number", "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. Defaults to `1024`." }, { "textRaw": "`secureContext`: Optional 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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing. ", "name": "secureContext", "desc": "Optional 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()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing." }, { "textRaw": "`lookup`: {Function} Custom lookup function. Defaults to [`dns.lookup()`][]. ", "name": "lookup", "type": "Function", "desc": "Custom lookup function. Defaults to [`dns.lookup()`][]." }, { "textRaw": "...: Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information. ", "name": "...", "desc": "Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information." } ], "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "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

The following implements a simple "echo server" example:

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // Necessary only if using the 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 the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\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  server.close();\n});\n
\n

Or

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('client.pfx')\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  server.close();\n});\n
\n" }, { "textRaw": "tls.createSecureContext(options)", "type": "method", "name": "createSecureContext", "meta": { "added": [ "v0.11.13" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`pfx` {string|Buffer} Optional 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. ", "name": "pfx", "type": "string|Buffer", "desc": "Optional 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." }, { "textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Optional 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": "Optional 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": "`passphrase` {string} Optional shared passphrase used for a single private key and/or a PFX. ", "name": "passphrase", "type": "string", "desc": "Optional shared passphrase used for a single private key and/or a PFX." }, { "textRaw": "`cert` {string|string[]|Buffer|Buffer[]} Optional 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": "Optional 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": "`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 Buffers. 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. ", "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 Buffers. 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." }, { "textRaw": "`crl` {string|string[]|Buffer|Buffer[]} Optional PEM formatted CRLs (Certificate Revocation Lists). ", "name": "crl", "type": "string|string[]|Buffer|Buffer[]", "desc": "Optional PEM formatted CRLs (Certificate Revocation Lists)." }, { "textRaw": "`ciphers` {string} Optional cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. ", "name": "ciphers", "type": "string", "desc": "Optional cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]." }, { "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. *Note*: [`tls.createServer()`][] sets the default value to `true`, other APIs that create secure contexts leave it unset. ", "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. *Note*: [`tls.createServer()`][] sets the default value to `true`, other APIs that create secure contexts leave it unset." }, { "textRaw": "`ecdhCurve` {string} A string describing a named curve to use for ECDH key agreement or `false` to disable ECDH. Defaults to [`tls.DEFAULT_ECDH_CURVE`]. 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. ", "name": "ecdhCurve", "type": "string", "desc": "A string describing a named curve to use for ECDH key agreement or `false` to disable ECDH. Defaults to [`tls.DEFAULT_ECDH_CURVE`]. 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": "`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, otherwise an error will be thrown. It is strongly recommended to 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, otherwise an error will be thrown. It is strongly recommended to 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": "`secureProtocol` {string} Optional SSL method to use, default is `'SSLv23_method'`. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, `'SSLv3_method'` to force SSL version 3. ", "name": "secureProtocol", "type": "string", "desc": "Optional SSL method to use, default is `'SSLv23_method'`. The possible values are listed as [SSL_METHODS][], use the function names as strings. For example, `'SSLv3_method'` to force SSL version 3." }, { "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": "`sessionIdContext` {string} Optional opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients. *Note*: [`tls.createServer()`][] uses a 128 bit truncated SHA1 hash value generated from `process.argv`, other APIs that create secure contexts have no default value. ", "name": "sessionIdContext", "type": "string", "desc": "Optional opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients. *Note*: [`tls.createServer()`][] uses a 128 bit truncated SHA1 hash value generated from `process.argv`, other APIs that create secure contexts have no default value." } ], "name": "options", "type": "Object" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

The tls.createSecureContext() method creates a credentials object.

\n

A key is required for ciphers that make use of certificates. Either key or\npfx can be used to provide it.

\n

If the 'ca' option is not given, then Node.js will use the default\npublicly trusted list of CAs as given in\nhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

\n" }, { "textRaw": "tls.createServer([options][, secureConnectionListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.2" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out. ", "name": "handshakeTimeout", "type": "number", "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'tlsClientError'` is emitted on the `tls.Server` object whenever a handshake times out." }, { "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. ", "name": "requestCert", "type": "boolean", "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`." }, { "textRaw": "`rejectUnauthorized` {boolean} If `true` 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`. Defaults to `false`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If `true` 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`. Defaults to `false`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) ", "name": "NPNProtocols", "type": "string[]|Buffer", "desc": "An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.)" }, { "textRaw": "`ALPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. ", "name": "ALPNProtocols", "type": "string[]|Buffer", "desc": "An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client." }, { "textRaw": "`SNICallback(servername, cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). ", "name": "SNICallback(servername,", "desc": "cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." }, { "textRaw": "`sessionTimeout` {number} An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details. ", "name": "sessionTimeout", "type": "number", "desc": "An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details." }, { "textRaw": "`ticketKeys`: A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. *Note* that this is automatically shared between `cluster` module workers. ", "name": "ticketKeys", "desc": "A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. *Note* that this is automatically shared between `cluster` module workers." }, { "textRaw": "...: Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. ", "name": "...", "desc": "Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`secureConnectionListener` {Function} ", "name": "secureConnectionListener", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options", "optional": true }, { "name": "secureConnectionListener", "optional": true } ] } ], "desc": "

Creates a new tls.Server. The secureConnectionListener, if provided, is\nautomatically set as a listener for the 'secureConnection' event.

\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 the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the 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

Or

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\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

This server can be tested by connecting to it using openssl s_client:

\n
openssl s_client -connect 127.0.0.1:8000\n
\n" }, { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.10.2" ] }, "desc": "

Returns an array with the names of the supported SSL ciphers.

\n

For example:

\n
console.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...]\n
\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "tls.DEFAULT_ECDH_CURVE", "name": "DEFAULT_ECDH_CURVE", "meta": { "added": [ "v0.11.13" ] }, "desc": "

The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'prime256v1' (NIST P-256). Consult RFC 4492 and\nFIPS.186-4 for more details.

\n" } ], "type": "module", "displayName": "TLS (SSL)" }, { "textRaw": "TTY", "name": "tty", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

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.

\n", "classes": [ { "textRaw": "Class: tty.ReadStream", "type": "class", "name": "tty.ReadStream", "meta": { "added": [ "v0.5.8" ] }, "desc": "

The tty.ReadStream class is a subclass of net.Socket that represents the\nreadable side of a TTY. In normal circumstances process.stdin will be the\nonly tty.ReadStream instance in a Node.js process and there should be no\nreason to create additional instances.

\n", "properties": [ { "textRaw": "readStream.isRaw", "name": "isRaw", "meta": { "added": [ "v0.7.7" ] }, "desc": "

A boolean that is true if the TTY is currently configured to operate as a\nraw device. Defaults to false.

\n" }, { "textRaw": "readStream.isTTY", "name": "isTTY", "meta": { "added": [ "v0.5.8" ] }, "desc": "

A boolean that is always true for tty.ReadStream instances.

\n" } ], "methods": [ { "textRaw": "readStream.setRawMode(mode)", "type": "method", "name": "setRawMode", "meta": { "added": [ "v0.7.7" ] }, "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.\nNote that CTRL+C will no longer cause a SIGINT when in this mode.

\n
    \n
  • mode {boolean} If true, configures the tty.ReadStream to operate as a\nraw device. If false, configures the tty.ReadStream to operate in its\ndefault mode. The readStream.isRaw property will be set to the resulting\nmode.
  • \n
\n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ] }, { "textRaw": "Class: tty.WriteStream", "type": "class", "name": "tty.WriteStream", "meta": { "added": [ "v0.5.8" ] }, "desc": "

The tty.WriteStream class is a subclass of net.Socket that represents the\nwritable side of a TTY. In normal circumstances, process.stdout and\nprocess.stderr will be the only tty.WriteStream instances created for a\nNode.js process and there should be no reason to create additional instances.

\n", "events": [ { "textRaw": "Event: 'resize'", "type": "event", "name": "resize", "meta": { "added": [ "v0.7.7" ] }, "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
\n", "params": [] } ], "properties": [ { "textRaw": "writeStream.columns", "name": "columns", "meta": { "added": [ "v0.7.7" ] }, "desc": "

A number specifying the number of columns the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

\n" }, { "textRaw": "writeStream.isTTY", "name": "isTTY", "meta": { "added": [ "v0.5.8" ] }, "desc": "

A boolean that is always true.

\n" }, { "textRaw": "writeStream.rows", "name": "rows", "meta": { "added": [ "v0.7.7" ] }, "desc": "

A number specifying the number of rows the TTY currently has. This property\nis updated whenever the 'resize' event is emitted.

\n" } ] } ], "methods": [ { "textRaw": "tty.isatty(fd)", "type": "method", "name": "isatty", "meta": { "added": [ "v0.5.8" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {number} A numeric file descriptor ", "name": "fd", "type": "number", "desc": "A numeric file descriptor" } ] }, { "params": [ { "name": "fd" } ] } ], "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.

\n\n\n" } ], "type": "module", "displayName": "TTY" }, { "textRaw": "URL", "name": "url", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The url module provides utilities for URL resolution and parsing. It can be\naccessed using:

\n
const url = require('url');\n
\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

Note: While the Legacy API has not been deprecated, it is maintained solely\nfor backwards compatibility with existing applications. New application code\nshould use the WHATWG API.

\n

A comparison between the WHATWG and Legacy APIs is provided below. Above the URL\n'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash', properties of\nan object returned by the legacy url.parse() are shown. Below it are\nproperties of a WHATWG URL object.

\n

Note: 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.host.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 { URL } = require('url');\nconst myURL =\n  new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');\n
\n

Note: In Web Browsers, the WHATWG URL class is a global that is always\navailable. In Node.js, however, the URL class must be accessed via\nrequire('url').URL.

\n

Parsing the URL string using the Legacy API:

\n
const url = require('url');\nconst myURL =\n  url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');\n
\n", "type": "module", "displayName": "URL Strings and URL Objects" }, { "textRaw": "The WHATWG URL API", "name": "the_whatwg_url_api", "meta": { "added": [ "v7.0.0, v6.13.0" ] }, "classes": [ { "textRaw": "Class: URL", "type": "class", "name": "URL", "desc": "

Browser-compatible URL class, implemented by following the WHATWG URL\nStandard. Examples of parsed URLs may be found in the Standard itself.

\n

Note: 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, using\nthe delete keyword on any properties of URL objects (e.g. delete\nmyURL.protocol, delete myURL.pathname, etc) has no effect but will still\nreturn true.

\n", "modules": [ { "textRaw": "Constructor: new URL(input[, base])", "name": "constructor:_new_url(input[,_base])", "desc": "
    \n
  • input {string} The input URL to parse
  • \n
  • base {string|URL} The base URL to resolve against if the input is not\nabsolute.
  • \n
\n

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 { URL } = require('url');\nconst myURL = new URL('/foo', 'https://example.org/');\n// https://example.org/foo\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 { URL } = require('url');\nconst myURL = new URL({ toString: () => 'https://example.org/' });\n// https://example.org/\n
\n

Unicode characters appearing within the hostname of input will be\nautomatically converted to ASCII using the Punycode algorithm.

\n
const { URL } = require('url');\nconst myURL = new URL('https://你好你好');\n// https://xn--6qqa088eba/\n
\n

Note: This feature is only available if the node executable was compiled\nwith ICU enabled. If not, the domain names are passed through unchanged.

\n", "type": "module", "displayName": "Constructor: new URL(input[, base])" } ], "properties": [ { "textRaw": "`hash` {string} ", "type": "string", "name": "hash", "desc": "

Gets and sets the fragment portion of the URL.

\n
const { URL } = require('url');\nconst 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. Note that the selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

\n" }, { "textRaw": "`host` {string} ", "type": "string", "name": "host", "desc": "

Gets and sets the host portion of the URL.

\n
const { URL } = require('url');\nconst 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.

\n" }, { "textRaw": "`hostname` {string} ", "type": "string", "name": "hostname", "desc": "

Gets and sets the hostname portion of the URL. The key difference between\nurl.host and url.hostname is that url.hostname does not include the\nport.

\n
const { URL } = require('url');\nconst myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n// Prints example.org\n\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:81/foo\n
\n

Invalid hostname values assigned to the hostname property are ignored.

\n" }, { "textRaw": "`href` {string} ", "type": "string", "name": "href", "desc": "

Gets and sets the serialized URL.

\n
const { URL } = require('url');\nconst 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.

\n" }, { "textRaw": "`origin` {string} ", "type": "string", "name": "origin", "desc": "

Gets the read-only serialization of the URL's origin.

\n
const { URL } = require('url');\nconst myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n// Prints https://example.org\n
\n
const { URL } = require('url');\nconst idnURL = new URL('https://你好你好');\nconsole.log(idnURL.origin);\n// Prints https://xn--6qqa088eba\n\nconsole.log(idnURL.hostname);\n// Prints xn--6qqa088eba\n
\n" }, { "textRaw": "`password` {string} ", "type": "string", "name": "password", "desc": "

Gets and sets the password portion of the URL.

\n
const { URL } = require('url');\nconst 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. Note that the selection of which characters to\npercent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

\n" }, { "textRaw": "`pathname` {string} ", "type": "string", "name": "pathname", "desc": "

Gets and sets the path portion of the URL.

\n
const { URL } = require('url');\nconst 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. Note that the selection of which characters\nto percent-encode may vary somewhat from what the url.parse() and\nurl.format() methods would produce.

\n" }, { "textRaw": "`port` {string} ", "type": "string", "name": "port", "desc": "

Gets and sets the port portion of the URL.

\n
const { URL } = require('url');\nconst 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 are ignored\nmyURL.port = 1e10;\nconsole.log(myURL.port);\n// Prints 1234\n
\n

The port value may be set as either a number or as a String containing a number\nin the range 0 to 65535 (inclusive). Setting the value to the default port\nof the URL objects given protocol will result in the port value becoming\nthe empty string ('').

\n

If an invalid string is assigned to the port property, but it begins with a\nnumber, the leading number is assigned to port. Otherwise, or if the number\nlies outside the range denoted above, it is ignored.

\n" }, { "textRaw": "`protocol` {string} ", "type": "string", "name": "protocol", "desc": "

Gets and sets the protocol portion of the URL.

\n
const { URL } = require('url');\nconst 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.

\n" }, { "textRaw": "`search` {string} ", "type": "string", "name": "search", "desc": "

Gets and sets the serialized query portion of the URL.

\n
const { URL } = require('url');\nconst 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. Note that the selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

\n" }, { "textRaw": "`searchParams` {URLSearchParams} ", "type": "URLSearchParams", "name": "searchParams", "desc": "

Gets the URLSearchParams object representing the query parameters of the\nURL. This property is read-only; to replace the entirety of query parameters of\nthe URL, use the url.search setter. See URLSearchParams\ndocumentation for details.

\n" }, { "textRaw": "`username` {string} ", "type": "string", "name": "username", "desc": "

Gets and sets the username portion of the URL.

\n
const { URL } = require('url');\nconst 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. Note that the selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()\nand url.format() methods would produce.

\n" } ], "methods": [ { "textRaw": "url.toString()", "type": "method", "name": "toString", "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "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().

\n

Because of the need for standard compliance, this method does not allow users\nto customize the serialization process of the URL.

\n" }, { "textRaw": "url.toJSON()", "type": "method", "name": "toJSON", "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "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 { URL } = require('url');\nconst 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
\n" } ] }, { "textRaw": "Class: URLSearchParams", "type": "class", "name": "URLSearchParams", "meta": { "added": [ "v7.5.0, v6.13.0" ] }, "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.

\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 { URL, URLSearchParams } = require('url');\n\nconst 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
\n", "modules": [ { "textRaw": "Constructor: new URLSearchParams()", "name": "constructor:_new_urlsearchparams()", "desc": "

Instantiate a new empty URLSearchParams object.

\n", "type": "module", "displayName": "Constructor: new URLSearchParams()" }, { "textRaw": "Constructor: new URLSearchParams(string)", "name": "constructor:_new_urlsearchparams(string)", "desc": "
    \n
  • string {string} A query string
  • \n
\n

Parse the string as a query string, and use it to instantiate a new\nURLSearchParams object. A leading '?', if present, is ignored.

\n
const { URLSearchParams } = require('url');\nlet 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
\n", "type": "module", "displayName": "Constructor: new URLSearchParams(string)" }, { "textRaw": "Constructor: new URLSearchParams(obj)", "name": "constructor:_new_urlsearchparams(obj)", "meta": { "added": [ "v7.10.0, v6.13.0" ] }, "desc": "
    \n
  • obj {Object} An object representing a collection of key-value pairs
  • \n
\n

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

Note: Unlike querystring module, duplicate keys in the form of array\nvalues are not allowed. Arrays are stringified using array.toString(),\nwhich simply joins all array elements with commas.

\n
const { URLSearchParams } = require('url');\nconst 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
\n", "type": "module", "displayName": "Constructor: new URLSearchParams(obj)" }, { "textRaw": "Constructor: new URLSearchParams(iterable)", "name": "constructor:_new_urlsearchparams(iterable)", "meta": { "added": [ "v7.10.0, v6.13.0" ] }, "desc": "
    \n
  • iterable {Iterable} An iterable object whose elements are key-value pairs
  • \n
\n

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
const { URLSearchParams } = require('url');\nlet 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
\n", "type": "module", "displayName": "Constructor: new URLSearchParams(iterable)" } ], "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" } ] }, { "params": [ { "name": "name" }, { "name": "value" } ] } ], "desc": "

Append a new name-value pair to the query string.

\n" }, { "textRaw": "urlSearchParams.delete(name)", "type": "method", "name": "delete", "signatures": [ { "params": [ { "textRaw": "`name` {string} ", "name": "name", "type": "string" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Remove all name-value pairs whose name is name.

\n" }, { "textRaw": "urlSearchParams.entries()", "type": "method", "name": "entries", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "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]().

\n" }, { "textRaw": "urlSearchParams.forEach(fn[, thisArg])", "type": "method", "name": "forEach", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} Function invoked for each name-value pair in the query. ", "name": "fn", "type": "Function", "desc": "Function invoked for each name-value pair in the query." }, { "textRaw": "`thisArg` {Object} Object to be used as `this` value for when `fn` is called ", "name": "thisArg", "type": "Object", "desc": "Object to be used as `this` value for when `fn` is called", "optional": true } ] }, { "params": [ { "name": "fn" }, { "name": "thisArg", "optional": true } ] } ], "desc": "

Iterates over each name-value pair in the query and invokes the given function.

\n
const { URL } = require('url');\nconst 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
\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" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Returns the value of the first name-value pair whose name is name. If there\nare no such pairs, null is returned.

\n" }, { "textRaw": "urlSearchParams.getAll(name)", "type": "method", "name": "getAll", "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [ { "textRaw": "`name` {string} ", "name": "name", "type": "string" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Returns the values of all name-value pairs whose name is name. If there are\nno such pairs, an empty array is returned.

\n" }, { "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" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "

Returns true if there is at least one name-value pair whose name is name.

\n" }, { "textRaw": "urlSearchParams.keys()", "type": "method", "name": "keys", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Returns an ES6 Iterator over the names of each name-value pair.

\n
const { URLSearchParams } = require('url');\nconst 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
\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" } ] }, { "params": [ { "name": "name" }, { "name": "value" } ] } ], "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 { URLSearchParams } = require('url');\n\nconst 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
\n" }, { "textRaw": "urlSearchParams.sort()", "type": "method", "name": "sort", "meta": { "added": [ "v7.7.0, v6.13.0" ] }, "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 { URLSearchParams } = require('url');\nconst 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
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "urlSearchParams.toString()", "type": "method", "name": "toString", "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

Returns the search parameters serialized as a string, with characters\npercent-encoded where necessary.

\n" }, { "textRaw": "urlSearchParams.values()", "type": "method", "name": "values", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Returns an ES6 Iterator over the values of each name-value pair.

\n" }, { "textRaw": "urlSearchParams\\[@@iterator\\]()", "type": "method", "name": "urlSearchParams\\[@@iterator\\]", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "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 { URLSearchParams } = require('url');\nconst 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
\n" } ] } ], "methods": [ { "textRaw": "url.domainToASCII(domain)", "type": "method", "name": "domainToASCII", "meta": { "added": [ "v7.4.0, v6.13.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`domain` {string} ", "name": "domain", "type": "string" } ] }, { "params": [ { "name": "domain" } ] } ], "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
const url = require('url');\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" }, { "textRaw": "url.domainToUnicode(domain)", "type": "method", "name": "domainToUnicode", "meta": { "added": [ "v7.4.0, v6.13.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [ { "textRaw": "`domain` {string} ", "name": "domain", "type": "string" } ] }, { "params": [ { "name": "domain" } ] } ], "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
const url = require('url');\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" } ], "type": "module", "displayName": "The WHATWG URL API" }, { "textRaw": "Legacy URL API", "name": "legacy_url_api", "modules": [ { "textRaw": "Legacy urlObject", "name": "legacy_urlobject", "desc": "

The legacy urlObject (require('url').Url) is created and returned by the\nurl.parse() function.

\n", "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 an\nASCII "at sign" (@). The format of the string is {username}[:{password}],\nwith the [:{password}] portion being optional.

\n

For example: 'user:pass'

\n" }, { "textRaw": "urlObject.hash", "name": "hash", "desc": "

The hash property consists of the "fragment" portion of the URL including\nthe leading ASCII hash (#) character.

\n

For example: '#hash'

\n" }, { "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.host.com:8080'

\n" }, { "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.host.com'

\n" }, { "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.host.com:8080/p/a/t/h?query=string#hash'

\n" } ], "type": "module", "displayName": "Legacy urlObject" } ], "properties": [ { "textRaw": "urlObject.port", "name": "port", "desc": "

The port property is the numeric port portion of the host component.

\n

For example: '8080'

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

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

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

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

\n", "properties": [ { "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.

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

\n" } ] } ], "methods": [ { "textRaw": "url.format(urlObject)", "type": "method", "name": "format", "meta": { "added": [ "v0.1.25" ] }, "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()`." } ] }, { "params": [ { "name": "urlObject" } ] } ], "desc": "

The url.format() method returns a formatted URL string derived from\nurlObject.

\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
    • 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\n followed by the literal string @.
  • \n
  • If the urlObject.host property is undefined then:
      \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
      • 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
    • 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
    • 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
    • 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
\n" }, { "textRaw": "url.parse(urlString[, parseQueryString[, slashesDenoteHost]])", "type": "method", "name": "parse", "meta": { "added": [ "v0.1.25" ], "changes": [ { "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." } ] }, "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. Defaults to `false`. ", "name": "parseQueryString", "type": "boolean", "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. Defaults to `false`.", "optional": true }, { "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'}`. Defaults to `false`. ", "name": "slashesDenoteHost", "type": "boolean", "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'}`. Defaults to `false`.", "optional": true } ] }, { "params": [ { "name": "urlString" }, { "name": "parseQueryString", "optional": true }, { "name": "slashesDenoteHost", "optional": true } ] } ], "desc": "

The url.parse() method takes a URL string, parses it, and returns a URL\nobject.

\n" }, { "textRaw": "url.resolve(from, to)", "type": "method", "name": "resolve", "meta": { "added": [ "v0.1.25" ] }, "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." } ] }, { "params": [ { "name": "from" }, { "name": "to" } ] } ], "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

For example:

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

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

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

\n", "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 three "percent-encode sets" that describe ranges\nof characters that must be percent-encoded:

\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
  • 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
  • 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 C0 control percent-encode set is used for all\nother cases, including URL fragments in particular, but also host and path\nunder certain specific conditions.

\n

When non-ASCII characters appear within a hostname, the hostname is encoded\nusing the Punycode algorithm. Note, however, that a hostname may contain\nboth Punycode encoded and percent-encoded characters. For example:

\n
const { URL } = require('url');\nconst myURL = new URL('https://%CF%80.com/foo');\nconsole.log(myURL.href);\n// Prints https://xn--1xa.com/foo\nconsole.log(myURL.origin);\n// Prints https://π.com\n
\n\n\n", "type": "module", "displayName": "WHATWG API" } ], "type": "module", "displayName": "Percent-Encoding in URLs" } ], "type": "module", "displayName": "URL" }, { "textRaw": "Util", "name": "util", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The util module is primarily designed to support the needs of Node.js' own\ninternal APIs. However, many of the utilities are useful for application and\nmodule developers as well. It can be accessed using:

\n
const util = require('util');\n
\n", "methods": [ { "textRaw": "util.debuglog(section)", "type": "method", "name": "debuglog", "meta": { "added": [ "v0.11.3" ] }, "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." } ] }, { "params": [ { "name": "section" } ] } ], "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

For example:

\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

Multiple comma-separated section names may be specified in the NODE_DEBUG\nenvironment variable. For example: NODE_DEBUG=fs,net,tls.

\n" }, { "textRaw": "util.deprecate(function, string)", "type": "method", "name": "deprecate", "meta": { "added": [ "v0.8.0" ] }, "desc": "

The util.deprecate() method wraps the given function or class in such a way that\nit is marked as deprecated.

\n
const util = require('util');\n\nexports.puts = util.deprecate(function() {\n  for (let i = 0, len = arguments.length; i < len; ++i) {\n    process.stdout.write(arguments[i] + '\\n');\n  }\n}, 'util.puts: Use console.log instead');\n
\n

When called, util.deprecate() will return a function that will emit a\nDeprecationWarning using the process.on('warning') event. By default,\nthis warning will be emitted and printed to stderr exactly once, the first\ntime it is called. After the warning is emitted, the wrapped function\nis called.

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

\n", "signatures": [ { "params": [ { "name": "function" }, { "name": "string" } ] } ] }, { "textRaw": "util.format(format[, ...args])", "type": "method", "name": "format", "meta": { "added": [ "v0.5.3" ] }, "signatures": [ { "params": [ { "textRaw": "`format` {string} A `printf`-like format string. ", "name": "format", "type": "string", "desc": "A `printf`-like format string." }, { "name": "...args", "optional": true } ] }, { "params": [ { "name": "format" }, { "name": "...args", "optional": true } ] } ], "desc": "

The util.format() method returns a formatted string using the first argument\nas a printf-like format.

\n

The first argument is a string containing zero or more placeholder tokens.\nEach placeholder token is replaced with the converted value from the\ncorresponding argument. Supported placeholders are:

\n
    \n
  • %s - String.
  • \n
  • %d - Number (integer or floating point value).
  • \n
  • %i - Integer.
  • \n
  • %f - Floating point value.
  • \n
  • %j - JSON. Replaced with the string '[Circular]' if the argument\ncontains circular references.
  • \n
  • %% - single percent sign ('%'). This does not consume an argument.
  • \n
\n

If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.

\n
util.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n
\n

If there are more arguments passed to the util.format() method than the number\nof placeholders, the extra arguments are coerced into strings then concatenated\nto the returned string, each delimited by a space. Excessive arguments whose\ntypeof is 'object' or 'symbol' (except null) will be transformed by\nutil.inspect().

\n
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'\n
\n

If the first argument is not a string then util.format() returns\na string that is the concatenation of all arguments separated by spaces.\nEach argument is converted to a string using util.inspect().

\n
util.format(1, 2, 3); // '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'); // '%% %s'\n
\n" }, { "textRaw": "util.inherits(constructor, superConstructor)", "type": "method", "name": "inherits", "meta": { "added": [ "v0.3.0" ] }, "desc": "

Note: usage of util.inherits() is discouraged. Please use the ES6 class and\nextends keywords to get language level inheritance support. Also note that\nthe two styles are semantically incompatible.

\n
    \n
  • constructor {Function}
  • \n
  • superConstructor {Function}
  • \n
\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

As 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  constructor() {\n    super();\n  }\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
\n", "signatures": [ { "params": [ { "name": "constructor" }, { "name": "superConstructor" } ] } ] }, { "textRaw": "util.inspect(object[, options])", "type": "method", "name": "inspect", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`object` {any} Any JavaScript primitive or Object. ", "name": "object", "type": "any", "desc": "Any JavaScript primitive or Object." }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. ", "name": "showHidden", "type": "boolean", "desc": "If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`." }, { "textRaw": "`depth` {number} Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. ", "name": "depth", "type": "number", "desc": "Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`." }, { "textRaw": "`colors` {boolean} If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see [Customizing `util.inspect` colors][]. ", "name": "colors", "type": "boolean", "desc": "If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see [Customizing `util.inspect` colors][]." }, { "textRaw": "`customInspect` {boolean} If `false`, then custom `inspect(depth, opts)` functions exported on the `object` being inspected will not be called. Defaults to `true`. ", "name": "customInspect", "type": "boolean", "desc": "If `false`, then custom `inspect(depth, opts)` functions exported on the `object` being inspected will not be called. Defaults to `true`." }, { "textRaw": "`showProxy` {boolean} If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. ", "name": "showProxy", "type": "boolean", "desc": "If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`." }, { "textRaw": "`maxArrayLength` {number} Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. ", "name": "maxArrayLength", "type": "number", "desc": "Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements." }, { "textRaw": "`breakLength` {number} The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to 60 for legacy compatibility. ", "name": "breakLength", "type": "number", "desc": "The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to 60 for legacy compatibility." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ], "desc": "

The util.inspect() method returns a string representation of object that is\nprimarily useful for debugging. Additional options may be passed that alter\ncertain aspects of the formatted string.

\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

Values may supply their own custom inspect(depth, opts) functions, when\ncalled these receive the current depth in the recursive inspection, as well as\nthe options object passed to util.inspect().

\n", "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
  • number - yellow
  • \n
  • boolean - yellow
  • \n
  • string - green
  • \n
  • date - magenta
  • \n
  • regexp - red
  • \n
  • null - bold
  • \n
  • undefined - grey
  • \n
  • special - cyan (only applied to functions at this time)
  • \n
  • name - (no styling)
  • \n
\n

The predefined color codes are: white, grey, black, blue, cyan,\ngreen, magenta, red and yellow. There are also bold, italic,\nunderline and inverse codes.

\n

Color styling uses ANSI control codes that may not be supported on all\nterminals.

\n" }, { "textRaw": "Custom inspection functions on Objects", "name": "Custom inspection functions on Objects", "type": "misc", "desc": "

Objects may also define their own [util.inspect.custom](depth, opts)\n(or, equivalently inspect(depth, opts)) function that util.inspect() will\ninvoke and use the result of when inspecting the object:

\n
const util = require('util');\n\nclass Box {\n  constructor(value) {\n    this.value = value;\n  }\n\n  inspect(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] = function(depth) {\n  return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: "{ bar: 'baz' }"\n
\n

A custom inspection method can alternatively be provided by exposing\nan inspect(depth, opts) method on the object:

\n
const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj.inspect = function(depth) {\n  return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: "{ bar: 'baz' }"\n
\n" } ], "modules": [ { "textRaw": "util.inspect.defaultOptions", "name": "util.inspect.defaultoptions", "meta": { "added": [ "v6.4.0" ] }, "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);\n\nconsole.log(arr); // logs the truncated array\nutil.inspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n
\n", "type": "module", "displayName": "util.inspect.defaultOptions" }, { "textRaw": "util.inspect.custom", "name": "util.inspect.custom", "meta": { "added": [ "v6.6.0" ] }, "desc": "

A Symbol that can be used to declare custom inspect functions, see\nCustom inspection functions on Objects.

\n", "type": "module", "displayName": "util.inspect.custom" } ] } ], "modules": [ { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "desc": "

The following APIs have been deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.

\n", "methods": [ { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`console.error()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`string` {string} The message to print to `stderr` ", "name": "string", "type": "string", "desc": "The message to print to `stderr`" } ] }, { "params": [ { "name": "string" } ] } ], "desc": "

Deprecated predecessor of console.error.

\n" }, { "textRaw": "util.error([...strings])", "type": "method", "name": "error", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`console.error()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`...strings` {string} The message to print to `stderr` ", "name": "...strings", "type": "string", "desc": "The message to print to `stderr`", "optional": true } ] }, { "params": [ { "name": "...strings", "optional": true } ] } ], "desc": "

Deprecated predecessor of console.error.

\n" }, { "textRaw": "util.isArray(object)", "type": "method", "name": "isArray", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "desc": "

Internal 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
\n" }, { "textRaw": "util.isBoolean(object)", "type": "method", "name": "isBoolean", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isBuffer(object)", "type": "method", "name": "isBuffer", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isDate(object)", "type": "method", "name": "isDate", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isError(object)", "type": "method", "name": "isError", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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

Note that 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
\n" }, { "textRaw": "util.isFunction(object)", "type": "method", "name": "isFunction", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isNull(object)", "type": "method", "name": "isNull", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isNullOrUndefined(object)", "type": "method", "name": "isNullOrUndefined", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isNumber(object)", "type": "method", "name": "isNumber", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isObject(object)", "type": "method", "name": "isObject", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "desc": "

Returns true if the given object is strictly an Object and not a\nFunction. Otherwise, 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(function() {});\n// Returns: false\n
\n" }, { "textRaw": "util.isPrimitive(object)", "type": "method", "name": "isPrimitive", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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(function() {});\n// Returns: false\nutil.isPrimitive(/^$/);\n// Returns: false\nutil.isPrimitive(new Date());\n// Returns: false\n
\n" }, { "textRaw": "util.isRegExp(object)", "type": "method", "name": "isRegExp", "meta": { "added": [ "v0.6.0" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isString(object)", "type": "method", "name": "isString", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isSymbol(object)", "type": "method", "name": "isSymbol", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.isUndefined(object)", "type": "method", "name": "isUndefined", "meta": { "added": [ "v0.11.5" ], "deprecated": [ "v4.0.0" ] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`object` {any} ", "name": "object", "type": "any" } ] }, { "params": [ { "name": "object" } ] } ], "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
\n" }, { "textRaw": "util.log(string)", "type": "method", "name": "log", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use a third party module instead.", "signatures": [ { "params": [ { "textRaw": "`string` {string} ", "name": "string", "type": "string" } ] }, { "params": [ { "name": "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
\n" }, { "textRaw": "util.print([...strings])", "type": "method", "name": "print", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`console.log()`][] instead.", "desc": "

Deprecated predecessor of console.log.

\n", "signatures": [ { "params": [ { "name": "...strings", "optional": true } ] } ] }, { "textRaw": "util.puts([...strings])", "type": "method", "name": "puts", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`console.log()`][] instead.", "desc": "

Deprecated predecessor of console.log.

\n", "signatures": [ { "params": [ { "name": "...strings", "optional": true } ] } ] }, { "textRaw": "util.\\_extend(target, source)", "type": "method", "name": "\\_extend", "meta": { "added": [ "v0.7.5" ], "deprecated": [ "v6.0.0" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`Object.assign()`] instead.", "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().

\n\n\n", "signatures": [ { "params": [ { "name": "target" }, { "name": "source" } ] } ] } ], "type": "module", "displayName": "Deprecated APIs" } ], "type": "module", "displayName": "Util" }, { "textRaw": "V8", "name": "v8", "introduced_in": "v4.0.0", "desc": "

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

Note: The APIs and implementation are subject to change at any time.

\n", "methods": [ { "textRaw": "v8.getHeapStatistics()", "type": "method", "name": "getHeapStatistics", "meta": { "added": [ "v1.0.0" ] }, "desc": "

Returns an object with the following properties:

\n
    \n
  • total_heap_size {number}
  • \n
  • total_heap_size_executable {number}
  • \n
  • total_physical_size {number}
  • \n
  • total_available_size {number}
  • \n
  • used_heap_size {number}
  • \n
  • heap_size_limit {number}
  • \n
\n

For example:

\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}\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "v8.getHeapSpaceStatistics()", "type": "method", "name": "getHeapSpaceStatistics", "meta": { "added": [ "v6.0.0" ] }, "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
  • space_name {string}
  • \n
  • space_size {number}
  • \n
  • space_used_size {number}
  • \n
  • space_available_size {number}
  • \n
  • physical_space_size {number}
  • \n
\n

For example:

\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
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "v8.setFlagsFromString(string)", "type": "method", "name": "setFlagsFromString", "meta": { "added": [ "v1.0.0" ] }, "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. An unofficial, community-maintained list of options\nand their effects is available here.

\n

Usage:

\n
// Print GC events to stdout for one minute.\nconst v8 = require('v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(function() { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
\n\n\n", "signatures": [ { "params": [ { "name": "string" } ] } ] } ], "type": "module", "displayName": "V8" }, { "textRaw": "VM (Executing JavaScript)", "name": "vm", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The vm module provides APIs for compiling and running code within V8 Virtual\nMachine contexts.

\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 sandboxed environment.\nThe sandboxed code uses a different V8 Context, meaning that\nit has a different global object than the rest of the code.

\n

One can provide the context by "contextifying" a sandbox\nobject. The sandboxed code treats any property on the sandbox like a\nglobal variable. Any changes on global variables caused by the sandboxed\ncode are reflected in the sandbox object.

\n
const vm = require('vm');\n\nconst x = 1;\n\nconst sandbox = { x: 2 };\nvm.createContext(sandbox); // Contextify the sandbox.\n\nconst code = 'x += 40; var y = 17;';\n// x and y are global variables in the sandboxed environment.\n// Initially, x has the value 2 because that is the value of sandbox.x.\nvm.runInContext(code, sandbox);\n\nconsole.log(sandbox.x); // 42\nconsole.log(sandbox.y); // 17\n\nconsole.log(x); // 1; y is not defined.\n
\n

Note: The vm module is not a security mechanism.\nDo not use it to run untrusted code.

\n", "classes": [ { "textRaw": "Class: vm.Script", "type": "class", "name": "vm.Script", "meta": { "added": [ "v0.3.1" ] }, "desc": "

Instances of the vm.Script class contain precompiled scripts that can be\nexecuted in specific sandboxes (or "contexts").

\n", "methods": [ { "textRaw": "new vm.Script(code, options)", "type": "method", "name": "Script", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile. ", "name": "code", "type": "string", "desc": "The JavaScript code to compile." }, { "textRaw": "`options` ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`cachedData` {Buffer} Provides an optional `Buffer` 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", "desc": "Provides an optional `Buffer` 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. ", "name": "produceCachedData", "type": "boolean", "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." } ], "name": "options" } ] }, { "params": [ { "name": "code" }, { "name": "options" } ] } ], "desc": "

Creating a new vm.Script object compiles code but does not run it. The\ncompiled vm.Script can be run later multiple times. It is important to note\nthat the code is not bound to any global object; rather, it is bound before\neach run, just for that run.

\n" }, { "textRaw": "script.runInContext(contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "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." }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." }, { "textRaw": "`breakOnSigint`: if `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. ", "name": "breakOnSigint", "desc": "if `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ], "desc": "

Runs the compiled code contained by the vm.Script object within the given\ncontextifiedSandbox 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 sandbox object.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n  animal: 'cat',\n  count: 2\n};\n\nconst script = new vm.Script('count += 1; name = "kitty";');\n\nconst context = vm.createContext(sandbox);\nfor (let i = 0; i < 10; ++i) {\n  script.runInContext(context);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }\n
\n

Note: Using the timeout or breakOnSigint options will result in new\nevent loops and corresponding threads being started, which have a non-zero\nperformance overhead.

\n" }, { "textRaw": "script.runInNewContext([sandbox][, options])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "textRaw": "`sandbox` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created. ", "name": "sandbox", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created.", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

First contextifies the given sandbox, runs the compiled code contained by\nthe vm.Script object within the created sandbox, 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 sandbox.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst script = new vm.Script('globalVar = "set"');\n\nconst sandboxes = [{}, {}, {}];\nsandboxes.forEach((sandbox) => {\n  script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
\n" }, { "textRaw": "script.runInThisContext([options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "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
\n" } ] } ], "methods": [ { "textRaw": "vm.createContext([sandbox])", "type": "method", "name": "createContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "textRaw": "`sandbox` {Object} ", "name": "sandbox", "type": "Object", "optional": true } ] }, { "params": [ { "name": "sandbox", "optional": true } ] } ], "desc": "

If given a sandbox object, the vm.createContext() method will prepare\nthat sandbox so that it can be used in calls to\nvm.runInContext() or script.runInContext(). Inside such scripts,\nthe sandbox object 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 util = require('util');\nconst vm = require('vm');\n\nglobal.globalVar = 3;\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nvm.runInContext('globalVar *= 2;', sandbox);\n\nconsole.log(util.inspect(sandbox)); // { globalVar: 2 }\n\nconsole.log(util.inspect(globalVar)); // 3\n
\n

If sandbox is omitted (or passed explicitly as undefined), a new, empty\ncontextified sandbox object will be returned.

\n

The vm.createContext() method is primarily useful for creating a single\nsandbox that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single sandbox representing a\nwindow's global object, then run all <script> tags together within the context\nof that sandbox.

\n" }, { "textRaw": "vm.isContext(sandbox)", "type": "method", "name": "isContext", "meta": { "added": [ "v0.11.7" ] }, "signatures": [ { "params": [ { "textRaw": "`sandbox` {Object} ", "name": "sandbox", "type": "Object" } ] }, { "params": [ { "name": "sandbox" } ] } ], "desc": "

Returns true if the given sandbox object has been contextified using\nvm.createContext().

\n" }, { "textRaw": "vm.runInContext(code, contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run. ", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`contextifiedSandbox` {Object} The [contextified][] object that will be used as the `global` when the `code` is compiled and run. ", "name": "contextifiedSandbox", "type": "Object", "desc": "The [contextified][] object that will be used as the `global` when the `code` is compiled and run." }, { "textRaw": "`options` ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "code" }, { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ], "desc": "

The vm.runInContext() method compiles code, runs it within the context of\nthe contextifiedSandbox, then returns the result. Running code does not have\naccess to the local scope. The contextifiedSandbox object must have been\npreviously contextified using the vm.createContext() method.

\n

The following example compiles and executes different scripts using a single\ncontextified object:

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nfor (let i = 0; i < 10; ++i) {\n  vm.runInContext('globalVar *= 2;', sandbox);\n}\nconsole.log(util.inspect(sandbox));\n\n// { globalVar: 1024 }\n
\n" }, { "textRaw": "vm.runInDebugContext(code)", "type": "method", "name": "runInDebugContext", "meta": { "added": [ "v0.11.14" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run. ", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." } ] }, { "params": [ { "name": "code" } ] } ], "desc": "

The vm.runInDebugContext() method compiles and executes code inside the V8\ndebug context. The primary use case is to gain access to the V8 Debug object:

\n
const vm = require('vm');\nconst Debug = vm.runInDebugContext('Debug');\nconsole.log(Debug.findScript(process.emit).name);  // 'events.js'\nconsole.log(Debug.findScript(process.exit).name);  // 'internal/process.js'\n
\n

Note: The debug context and object are intrinsically tied to V8's debugger\nimplementation and may change (or even be removed) without prior warning.

\n

The Debug object can also be made available using the V8-specific\n--expose_debug_as= command line option.

\n" }, { "textRaw": "vm.runInNewContext(code[, sandbox][, options])", "type": "method", "name": "runInNewContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {string} The JavaScript code to compile and run. ", "name": "code", "type": "string", "desc": "The JavaScript code to compile and run." }, { "textRaw": "`sandbox` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created. ", "name": "sandbox", "type": "Object", "desc": "An object that will be [contextified][]. If `undefined`, a new object will be created.", "optional": true }, { "textRaw": "`options` ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

The vm.runInNewContext() first contextifies the given sandbox object (or\ncreates a new sandbox if passed as undefined), compiles the code, runs it\nwithin the context of the created context, then returns the result. Running code\ndoes not have access to the local scope.

\n

The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the sandbox.

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n  animal: 'cat',\n  count: 2\n};\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox);\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }\n
\n" }, { "textRaw": "vm.runInThisContext(code[, options])", "type": "method", "name": "runInThisContext", "meta": { "added": [ "v0.3.1" ] }, "signatures": [ { "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` ", "options": [ { "textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ", "name": "filename", "type": "string", "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. ", "name": "lineOffset", "type": "number", "desc": "Specifies the line number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ", "name": "columnOffset", "type": "number", "desc": "Specifies the column number offset that is displayed in stack traces produced by this script." }, { "textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ", "name": "displayErrors", "type": "boolean", "desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace." }, { "textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ", "name": "timeout", "type": "number", "desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown." } ], "name": "options", "optional": true } ] }, { "params": [ { "name": "code" }, { "name": "options", "optional": true } ] } ], "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

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);\nconsole.log('localVar:', localVar);\n\nconst evalResult = eval('localVar = "eval";');\nconsole.log('evalResult:', evalResult);\nconsole.log('localVar:', localVar);\n\n// vmResult: 'vm', localVar: 'initial value'\n// 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 vm.runInThisContext(), the\ncode is executed within the current V8 global context. The code passed\nto 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\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

Note: The require() in the above case shares the state with the context it\nis passed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.

\n" } ], "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 sandbox object that is\npassed in (or a newly created object if sandbox is undefined) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode run using the vm modules methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the sandbox object is what this document refers to as\n"contextifying" the sandbox.

\n\n\n", "type": "module", "displayName": "What does it mean to \"contextify\" an object?" } ], "type": "module", "displayName": "vm" }, { "textRaw": "Zlib", "name": "zlib", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

The zlib module provides compression functionality implemented using Gzip and\nDeflate/Inflate. It can be accessed using:

\n
const zlib = require('zlib');\n
\n

Compressing or decompressing a stream (such as a file) can be accomplished by\npiping the source stream data through a zlib stream into a destination stream:

\n
const gzip = zlib.createGzip();\nconst fs = require('fs');\nconst inp = fs.createReadStream('input.txt');\nconst out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);\n
\n

It is also possible to compress or decompress data in a single step:

\n
const input = '.................................';\nzlib.deflate(input, (err, buffer) => {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  } else {\n    // handle error\n  }\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, (err, buffer) => {\n  if (!err) {\n    console.log(buffer.toString());\n  } else {\n    // handle error\n  }\n});\n
\n", "modules": [ { "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 and deflate\ncontent-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

Note: the examples given below are drastically simplified to show\nthe basic concept. Using zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning for more information\non the speed/memory/compression tradeoffs involved in zlib usage.

\n
// client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst request = http.get({ host: 'example.com',\n                           path: '/',\n                           port: 80,\n                           headers: { 'Accept-Encoding': 'gzip,deflate' } });\nrequest.on('response', (response) => {\n  const output = fs.createWriteStream('example.com_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\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');\nhttp.createServer((request, response) => {\n  const raw = fs.createReadStream('index.html');\n  let acceptEncoding = request.headers['accept-encoding'];\n  if (!acceptEncoding) {\n    acceptEncoding = '';\n  }\n\n  // Note: this is not a conformant accept-encoding parser.\n  // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3\n  if (acceptEncoding.match(/\\bdeflate\\b/)) {\n    response.writeHead(200, { 'Content-Encoding': 'deflate' });\n    raw.pipe(zlib.createDeflate()).pipe(response);\n  } else if (acceptEncoding.match(/\\bgzip\\b/)) {\n    response.writeHead(200, { 'Content-Encoding': 'gzip' });\n    raw.pipe(zlib.createGzip()).pipe(response);\n  } else {\n    response.writeHead(200, {});\n    raw.pipe(response);\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 compressed 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  { finishFlush: zlib.Z_SYNC_FLUSH },\n  (err, buffer) => {\n    if (!err) {\n      console.log(buffer.toString());\n    } else {\n      // handle error\n    }\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.

\n", "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');\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  output.pipe(response);\n\n  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
\n", "type": "module", "displayName": "Flushing" } ], "miscs": [ { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

From zlib/zconf.h, modified to node.js's usage:

\n

The memory requirements for deflate are (in bytes):

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

\n
1 << windowBits;\n
\n

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

\n" }, { "textRaw": "Constants", "name": "Constants", "meta": { "added": [ "v0.5.8" ] }, "type": "misc", "desc": "

All of the constants defined in zlib.h are also defined on require('zlib').\nIn the normal course of operations, it will not be necessary to use these\nconstants. They are documented so that their presence is not surprising. This\nsection is taken almost directly from the zlib documentation. See\nhttp://zlib.net/manual.html#Constants for more details.

\n

Allowed flush values.

\n
    \n
  • zlib.Z_NO_FLUSH
  • \n
  • zlib.Z_PARTIAL_FLUSH
  • \n
  • zlib.Z_SYNC_FLUSH
  • \n
  • zlib.Z_FULL_FLUSH
  • \n
  • zlib.Z_FINISH
  • \n
  • zlib.Z_BLOCK
  • \n
  • zlib.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.Z_OK
  • \n
  • zlib.Z_STREAM_END
  • \n
  • zlib.Z_NEED_DICT
  • \n
  • zlib.Z_ERRNO
  • \n
  • zlib.Z_STREAM_ERROR
  • \n
  • zlib.Z_DATA_ERROR
  • \n
  • zlib.Z_MEM_ERROR
  • \n
  • zlib.Z_BUF_ERROR
  • \n
  • zlib.Z_VERSION_ERROR
  • \n
\n

Compression levels.

\n
    \n
  • zlib.Z_NO_COMPRESSION
  • \n
  • zlib.Z_BEST_SPEED
  • \n
  • zlib.Z_BEST_COMPRESSION
  • \n
  • zlib.Z_DEFAULT_COMPRESSION
  • \n
\n

Compression strategy.

\n
    \n
  • zlib.Z_FILTERED
  • \n
  • zlib.Z_HUFFMAN_ONLY
  • \n
  • zlib.Z_RLE
  • \n
  • zlib.Z_FIXED
  • \n
  • zlib.Z_DEFAULT_STRATEGY
  • \n
\n

The deflate compression method (the only one supported in this version).

\n
    \n
  • zlib.Z_DEFLATED
  • \n
\n

For initializing zalloc, zfree, opaque.

\n
    \n
  • zlib.Z_NULL
  • \n
\n" }, { "textRaw": "Class Options", "name": "Class Options", "meta": { "added": [ "v0.11.1" ] }, "type": "misc", "desc": "

Each class takes an options object. All options are optional.

\n

Note that some options are only relevant when compressing, and are\nignored by the decompression classes.

\n
    \n
  • flush (default: zlib.Z_NO_FLUSH)
  • \n
  • finishFlush (default: zlib.Z_FINISH)
  • \n
  • chunkSize (default: 16 * 1024)
  • \n
  • windowBits
  • \n
  • level (compression only)
  • \n
  • memLevel (compression only)
  • \n
  • strategy (compression only)
  • \n
  • dictionary (deflate/inflate only, empty dictionary by default)
  • \n
\n

See the description of deflateInit2 and inflateInit2 at\nhttp://zlib.net/manual.html#Advanced for more information on these.

\n" }, { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

All of these take a Buffer or string as the first argument, an optional\nsecond argument to supply options to the zlib classes and will call the\nsupplied callback with callback(error, result).

\n

Every method has a *Sync counterpart, which accept the same arguments, but\nwithout a callback.

\n", "methods": [ { "textRaw": "zlib.deflate(buf[, options], callback)", "type": "method", "name": "deflate", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with Deflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateSync(buf[, options])", "type": "method", "name": "deflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with Deflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflateRaw(buf[, options], callback)", "type": "method", "name": "deflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with DeflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRawSync(buf[, options])", "type": "method", "name": "deflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with DeflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gunzip(buf[, options], callback)", "type": "method", "name": "gunzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Gunzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzipSync(buf[, options])", "type": "method", "name": "gunzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Gunzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gzip(buf[, options], callback)", "type": "method", "name": "gzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Compress a Buffer or string with Gzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzipSync(buf[, options])", "type": "method", "name": "gzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Compress a Buffer or string with Gzip.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflate(buf[, options], callback)", "type": "method", "name": "inflate", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Inflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateSync(buf[, options])", "type": "method", "name": "inflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Inflate.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflateRaw(buf[, options], callback)", "type": "method", "name": "inflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with InflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRawSync(buf[, options])", "type": "method", "name": "inflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with InflateRaw.

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.unzip(buf[, options], callback)", "type": "method", "name": "unzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "

Decompress a Buffer or string with Unzip.

\n\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzipSync(buf[, options])", "type": "method", "name": "unzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "

Decompress a Buffer or string with Unzip.

\n\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] } ] } ], "meta": { "added": [ "v0.5.8" ] }, "classes": [ { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Compress data using deflate.

\n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Compress data using deflate, and do not append a zlib header.

\n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a gzip stream.

\n" }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Compress data using gzip.

\n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a deflate stream.

\n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress a raw deflate stream.

\n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.

\n" }, { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.

\n", "methods": [ { "textRaw": "zlib.close([callback])", "type": "method", "name": "close", "meta": { "added": [ "v0.9.4" ] }, "desc": "

Close the underlying handle.

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "zlib.flush([kind], callback)", "type": "method", "name": "flush", "meta": { "added": [ "v0.5.8" ] }, "desc": "

kind defaults to zlib.Z_FULL_FLUSH.

\n

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.

\n", "signatures": [ { "params": [ { "name": "kind", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.params(level, strategy, callback)", "type": "method", "name": "params", "meta": { "added": [ "v0.11.4" ] }, "desc": "

Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.

\n", "signatures": [ { "params": [ { "name": "level" }, { "name": "strategy" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "meta": { "added": [ "v0.7.0" ] }, "desc": "

Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.

\n", "signatures": [ { "params": [] } ] } ] } ], "properties": [ { "textRaw": "zlib.constants", "name": "constants", "meta": { "added": [ "v7.0.0" ] }, "desc": "

Provides an object enumerating Zlib-related constants.

\n" } ], "methods": [ { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Deflate object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new DeflateRaw object with an options.

\n

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

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Gunzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Gzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Inflate object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new InflateRaw object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "

Returns a new Unzip object with an options.

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "Zlib" } ], "stability": 2, "stabilityText": "Stable", "properties": [ { "textRaw": "V8 Inspector Integration for Node.js", "name": "js", "desc": "

NOTE: This is an experimental feature.

\n

V8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling.

\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, provide the --debug-brk\nflag in addition to --inspect.

\n
$ node --inspect index.js\nDebugger listening on port 9229.\nWarning: This is an experimental feature and could change at any time.\nTo start debugging, open the following URL in Chrome:\n    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/3a6d0a9e-0707-48f8-a7c6-48f157b67ab5\n
\n

(In the example above, the UUID 3a6d0a9e-0707-48f8-a7c6-48f157b67ab5\nat the end of the URL is generated on the fly, it varies in different\ndebugging sessions.)

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

\n", "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", "optional": true } ] }, { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ], "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, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().

\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 an end 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
\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.

\n" }, { "textRaw": "`message` {string} ", "type": "string", "name": "message", "desc": "

The error.message property is the string description of the error as set by calling new Error(message).\nThe message passed to the constructor will also appear in the first line of\nthe stack trace of the Error, however changing this property after the\nError object is created may not change the first line of the stack trace\n(for example, when error.stack is read before this property is changed).

\n
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
\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

For example:

\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

It is important to note that frames are only generated for JavaScript\nfunctions. If, for example, execution synchronously passes through a C++ addon\nfunction called cheetahify, which itself calls a JavaScript function, the\nframe representing the cheetahify call will not be present in the stack\ntraces:

\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(); // 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\n to 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.

\n

System-level errors are generated as augmented Error instances, which are\ndetailed here.

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

\n" }, { "params": [ { "name": "message" } ], "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.

\n" } ] }, { "textRaw": "Class: RangeError", "type": "class", "name": "RangeError", "desc": "

A subclass of Error that indicates that a provided argument was not within the\nset or range of acceptable values for a function; whether that is a numeric\nrange, or outside the set of options for a given function parameter.

\n

For example:

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

\n" }, { "textRaw": "Class: ReferenceError", "type": "class", "name": "ReferenceError", "desc": "

A subclass of Error that indicates that an attempt is being made to access a\nvariable that is not defined. Such errors commonly indicate typos in code, or\nan otherwise broken program.

\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 should always be considered a bug in the code\nor its dependencies.

\n" }, { "textRaw": "Class: SyntaxError", "type": "class", "name": "SyntaxError", "desc": "

A subclass of Error that indicates that a program is not valid JavaScript.\nThese errors may only be generated and propagated as a result of code\nevaluation. Code evaluation may happen as a result of eval, Function,\nrequire, or vm. These errors are almost always indicative of a broken\nprogram.

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

\n" }, { "textRaw": "Class: TypeError", "type": "class", "name": "TypeError", "desc": "

A subclass of Error that indicates that a provided argument is not an\nallowable type. For example, passing a function to a parameter which expects a\nstring would be considered 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.

\n" } ], "globals": [ { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "meta": { "added": [ "v0.1.103" ] }, "desc": "
    \n
  • {Function}
  • \n
\n

Used to handle binary data. See the buffer section.

\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "

clearImmediate is described in the timers section.

\n" }, { "textRaw": "clearInterval(intervalObject)", "type": "global", "name": "clearInterval", "meta": { "added": [ "v0.0.1" ] }, "desc": "

clearInterval is described in the timers section.

\n" }, { "textRaw": "clearTimeout(timeoutObject)", "type": "global", "name": "clearTimeout", "meta": { "added": [ "v0.0.1" ] }, "desc": "

clearTimeout is described in the timers section.

\n" }, { "textRaw": "console", "name": "console", "meta": { "added": [ "v0.1.100" ] }, "type": "global", "desc": "
    \n
  • {Object}
  • \n
\n

Used to print to stdout and stderr. See the console section.

\n" }, { "textRaw": "global", "name": "global", "meta": { "added": [ "v0.1.27" ] }, "type": "global", "desc": "
    \n
  • {Object} The global namespace object.
  • \n
\n

In browsers, the top-level scope is the global scope. That means that in\nbrowsers if you're in the global scope var something will define a global\nvariable. In Node.js this is different. The top-level scope is not the global\nscope; var something inside an Node.js module will be local to that module.

\n" }, { "textRaw": "process", "name": "process", "meta": { "added": [ "v0.1.7" ] }, "type": "global", "desc": "
    \n
  • {Object}
  • \n
\n

The process object. See the process object section.

\n" }, { "textRaw": "setImmediate(callback[, ...args])", "type": "global", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "

setImmediate is described in the timers section.

\n" }, { "textRaw": "setInterval(callback, delay[, ...args])", "type": "global", "name": "setInterval", "meta": { "added": [ "v0.0.1" ] }, "desc": "

setInterval is described in the timers section.

\n" }, { "textRaw": "setTimeout(callback, delay[, ...args])", "type": "global", "name": "setTimeout", "meta": { "added": [ "v0.0.1" ] }, "desc": "

setTimeout is described in the timers section.

\n\n\n" }, { "textRaw": "Process", "name": "Process", "introduced_in": "v0.10.0", "type": "global", "desc": "

The process object is a global that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require().

\n", "modules": [ { "textRaw": "Process Events", "name": "process_events", "desc": "

The process object is an instance of EventEmitter.

\n", "events": [ { "textRaw": "Event: 'beforeExit'", "type": "event", "name": "beforeExit", "meta": { "added": [ "v0.11.12" ] }, "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", "params": [] }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "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.

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "meta": { "added": [ "v0.1.7" ] }, "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, as the only argument.

\n

For example:

\n
process.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
process.on('exit', (code) => {\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n});\n
\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.10" ] }, "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 listener callback is invoked with the following arguments:

\n
    \n
  • message {Object} a parsed JSON object or primitive value
  • \n
  • sendHandle {Handle object} a net.Socket or net.Server object, or\nundefined.
  • \n
\n", "params": [] }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "meta": { "added": [ "v1.4.1" ] }, "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 listener callback is invoked with a reference to the rejected Promise as\nthe only argument.

\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

For example:

\n
const unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, p) => {\n  unhandledRejections.set(p, reason);\n});\nprocess.on('rejectionHandled', (p) => {\n  unhandledRejections.delete(p);\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).

\n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "meta": { "added": [ "v0.1.18" ] }, "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.\nAdding a handler for the 'uncaughtException' event overrides this default\nbehavior.

\n

The listener function is called with the Error object passed as the only\nargument.

\n

For example:

\n
process.on('uncaughtException', (err) => {\n  fs.writeSync(1, `Caught exception: ${err}`);\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", "modules": [ { "textRaw": "Warning: Using `'uncaughtException'` correctly", "name": "warning:_using_`'uncaughtexception'`_correctly", "desc": "

Note that '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 of the power cord when upgrading a computer — nine out of ten\ntimes nothing happens - but the 10th 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 uncaughtException\nis emitted or not, an external monitor should be employed in a separate process\nto detect application failures and recover or restart as needed.

\n", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ], "params": [] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "meta": { "added": [ "v1.4.1" ] }, "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

The listener function is called with the following arguments:

\n
    \n
  • reason {Error|any} The object with which the promise was rejected\n(typically an Error object).
  • \n
  • p the Promise that was rejected.
  • \n
\n

For example:

\n
process.on('unhandledRejection', (reason, p) => {\n  console.log('Unhandled Rejection at: Promise', p, '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
function 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. Alternatively, the 'rejectionHandled' event may be used.

\n", "params": [] }, { "textRaw": "Event: 'warning'", "type": "event", "name": "warning", "meta": { "added": [ "v6.0.0" ] }, "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

The listener function is called with a single warning argument whose value is\nan Error object. There are three key properties that describe the warning:

\n
    \n
  • name {string} The name of the warning (currently Warning by default).
  • \n
  • message {string} A system-provided description of the warning.
  • \n
  • stack {string} A stack trace to the location in the code where the warning\nwas issued.
  • \n
\n
process.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) Warning: Possible EventEmitter memory leak detected. 2 foo\n... 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> var 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", "modules": [ { "textRaw": "Emitting custom warnings", "name": "emitting_custom_warnings", "desc": "

The process.emitWarning() method can be used to issue\ncustom or application specific warnings.

\n
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Prints: (node 12345) Warning: Something happened!\n\n// Emit a warning using an object...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Prints: (node 12345) CustomWarning: Something happened!\n\n// Emit a warning using a custom Error object...\nclass CustomWarning extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomWarning';\n    Error.captureStackTrace(this, CustomWarning);\n  }\n}\nconst myWarning = new CustomWarning('Something happened!');\nprocess.emitWarning(myWarning);\n// Prints: (node 12345) CustomWarning: Something happened!\n
\n", "type": "module", "displayName": "Emitting custom warnings" }, { "textRaw": "Emitting custom deprecation warnings", "name": "emitting_custom_deprecation_warnings", "desc": "

Custom deprecation warnings can be emitted by setting the name of a custom\nwarning to DeprecationWarning. For instance:

\n
process.emitWarning('This API is deprecated', 'DeprecationWarning');\n
\n

Or,

\n
const err = new Error('This API is deprecated');\nerr.name = 'DeprecationWarning';\nprocess.emitWarning(err);\n
\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\nDeprecationWarning.

\n", "type": "module", "displayName": "Emitting custom deprecation warnings" } ], "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "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\nSIGINT, SIGHUP, etc.

\n

The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT' for SIGINT signals).

\n

For example:

\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

Note: An easy way to send the SIGINT signal is with <Ctrl>-C in most\nterminal programs.

\n

It is important to take note of the following:

\n
    \n
  • SIGUSR1 is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so will not stop the debugger from starting.
  • \n
  • SIGTERM and SIGINT have default handlers on non-Windows platforms that\nresets the terminal mode before exiting with code 128 + signal number. If\none of 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). It is not generated\nwhen terminal raw mode is enabled.
  • \n
  • SIGBREAK is delivered on Windows when <Ctrl>+<Break> is pressed, on\nnon-Windows platforms it can be listened on, but there is no way to send or\ngenerate 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 terminate\nNode.js on all platforms.
  • \n
  • SIGSTOP cannot have a listener installed.
  • \n
  • SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised artificially\n using kill(2), inherently leave the process in a state from which it is not\n safe to attempt to call JS listeners. Doing so might lead to the process\n hanging in an endless loop, since listeners attached using process.on() are\n called asynchronously and therefore unable to correct the underlying problem.
  • \n
\n

Note: Windows does not support sending signals, but Node.js offers some\nemulation with process.kill(), and subprocess.kill(). Sending\nsignal 0 can be used to test for the existence of a process. Sending SIGINT,\nSIGTERM, and SIGKILL cause the unconditional termination of the target\nprocess.

\n", "params": [] } ], "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 Node.js's 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 Node.js's 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\nERROR.
  • \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 a '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 Node.js's 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 --debug, --inspect and/or\n--debug-brk options were set, but the port number chosen was invalid\nor unavailable.
  • \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.
  • \n
\n\n\n", "type": "module", "displayName": "Exit Codes" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "meta": { "added": [ "v0.7.0" ] }, "desc": "

The process.abort() method causes the Node.js process to exit immediately and\ngenerate a core file.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "meta": { "added": [ "v0.1.17" ] }, "signatures": [ { "params": [ { "textRaw": "`directory` {string} ", "name": "directory", "type": "string" } ] }, { "params": [ { "name": "directory" } ] } ], "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
console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n} catch (err) {\n  console.error(`chdir: ${err}`);\n}\n
\n" }, { "textRaw": "process.cpuUsage([previousValue])", "type": "method", "name": "cpuUsage", "meta": { "added": [ "v6.1.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "options": [ { "textRaw": "`user` {integer} ", "name": "user", "type": "integer" }, { "textRaw": "`system` {integer} ", "name": "system", "type": "integer" } ], "name": "return", "type": "Object" }, "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()`", "optional": true } ] }, { "params": [ { "name": "previousValue", "optional": true } ] } ], "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
const startUsage = process.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(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
\n" }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "meta": { "added": [ "v0.1.8" ] }, "signatures": [ { "return": { "textRaw": "Returns: {string} ", "name": "return", "type": "string" }, "params": [] }, { "params": [] } ], "desc": "

The process.cwd() method returns the current working directory of the Node.js\nprocess.

\n
console.log(`Current directory: ${process.cwd()}`);\n
\n" }, { "textRaw": "process.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.2" ] }, "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 that same as calling the parent\nprocess's ChildProcess.disconnect().

\n

If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect() will be undefined.

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.emitWarning(warning[, name][, ctor])", "type": "method", "name": "emitWarning", "meta": { "added": [ "v6.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`warning` {string | Error} The warning to emit. ", "name": "warning", "type": "string | Error", "desc": "The warning to emit." }, { "textRaw": "`name` {string} When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`. ", "name": "name", "type": "string", "desc": "When `warning` is a String, `name` is the name to use for the warning. Default: `Warning`.", "optional": true }, { "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", "desc": "When `warning` is a String, `ctor` is an optional function used to limit the generated stack trace. Default `process.emitWarning`", "optional": true } ] }, { "params": [ { "name": "warning" }, { "name": "name", "optional": true }, { "name": "ctor", "optional": true } ] } ], "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\nprocess.on('warning') event.

\n
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n
// Emit a warning using a string and a name...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) 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\nprocess.on('warning') event.

\n
process.on('warning', (warning) => {\n  console.warn(warning.name);\n  console.warn(warning.message);\n  console.warn(warning.stack);\n});\n
\n

If warning is passed as an Error object, it will be passed through to the\nprocess.on('warning') event handler unmodified (and the optional name\nand ctor arguments will be ignored):

\n
// Emit a warning using an Error object...\nconst myWarning = new Error('Warning! Something happened!');\nmyWarning.name = 'CustomWarning';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) CustomWarning: Warning! Something Happened!\n
\n

A TypeError is thrown if warning is anything other than a string or Error\nobject.

\n

Note that 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 name is\nDeprecationWarning:

\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
\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
let warned = false;\nfunction emitMyWarning() {\n  if (!warned) {\n    process.emitWarning('Only warn once!');\n    warned = true;\n  }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
\n", "type": "module", "displayName": "Avoiding duplicate warnings" } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "meta": { "added": [ "v0.1.13" ] }, "signatures": [ { "params": [ { "textRaw": "`code` {integer} The exit code. Defaults to `0`. ", "name": "code", "type": "integer", "desc": "The exit code. Defaults to `0`.", "optional": true } ] }, { "params": [ { "name": "code", "optional": true } ] } ], "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
process.exit(1);\n
\n

The shell that executed Node.js should see the exit code as 1.

\n

It is important to note that calling process.exit() will force the process to\nexit as quickly as possible even if there are still asynchronous operations\npending that have not yet completed fully, including I/O operations to\nprocess.stdout and process.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
// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n  printUsageToStdout();\n  process.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
// 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" }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "meta": { "added": [ "v2.0.0" ] }, "desc": "

The process.getegid() method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)

\n
if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows\nor Android)

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.geteuid() method returns the numerical effective user identity of\nthe process. (See geteuid(2).)

\n
if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.getgid() method returns the numerical group identity of the\nprocess. (See getgid(2).)

\n
if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ] }, "signatures": [ { "return": { "textRaw": "Returns: {integer} ", "name": "return", "type": "integer" }, "params": [] }, { "params": [] } ], "desc": "

The process.getuid() method returns the numeric user identity of the process.\n(See getuid(2).)

\n
if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.hrtime([time])", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ] }, "desc": "

The process.hrtime() method returns the current high-resolution real time in a\n[seconds, nanoseconds] tuple Array. time is an optional parameter that must\nbe the result of a previous process.hrtime() call (and therefore, a real time\nin a [seconds, nanoseconds] tuple Array containing a previous time) to diff\nwith the current time. 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

Passing in the result of a previous call to process.hrtime() is useful for\ncalculating an amount of time passed between calls:

\n
const time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  const diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log(`Benchmark took ${diff[0] * 1e9 + diff[1]} nanoseconds`);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);\n
\n

Constructing an array by some method other than calling process.hrtime() and\npassing the result to process.hrtime() will result in undefined behavior.

\n", "signatures": [ { "params": [ { "name": "time", "optional": true } ] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "meta": { "added": [ "v0.9.4" ] }, "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": "`extra_group` {string|number} A group name or numeric identifier. ", "name": "extra_group", "type": "string|number", "desc": "A group name or numeric identifier." } ] }, { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ], "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

Note that care must be taken when dropping privileges. Example:

\n
console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]\n
\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ] }, "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. Defaults to `'SIGTERM'`. ", "name": "signal", "type": "string|number", "desc": "The signal to send, either as a string or number. Defaults to `'SIGTERM'`.", "optional": true } ] }, { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ], "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

Note:Even though the name of this function is process.kill(), it is really\njust a signal sender, like the kill system call. The signal sent may do\nsomething other than kill the target process.

\n

For example:

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

Note: When SIGUSR1 is received by a Node.js process, Node.js will start the\ndebugger, see Signal Events.

\n" }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "meta": { "added": [ "v0.1.16" ] }, "signatures": [ { "return": { "textRaw": "Returns: {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" } ], "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

The process.memoryUsage() method returns an object describing the memory usage\nof the Node.js process measured in bytes.

\n

For example, the code:

\n
console.log(process.memoryUsage());\n
\n

Will generate:

\n\n
{\n  rss: 4935680,\n  heapTotal: 1826816,\n  heapUsed: 650472,\n  external: 49879\n}\n
\n

heapTotal and heapUsed refer to V8's memory usage.\nexternal refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8. rss, Resident Set Size, is the amount of space\noccupied in the main memory device (that is a subset of the total allocated\nmemory) for the process, which includes the heap, code segment and stack.

\n

The heap is where objects, strings and closures are stored. Variables are\nstored in the stack and the actual JavaScript code resides in the\ncode segment.

\n" }, { "textRaw": "process.nextTick(callback[, ...args])", "type": "method", "name": "nextTick", "meta": { "added": [ "v0.1.26" ] }, "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`", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "...args", "optional": true } ] } ], "desc": "

The process.nextTick() method adds the callback to the "next tick queue".\nOnce the current turn of the event loop turn runs to completion, all callbacks\ncurrently in the next tick queue will be called.

\n

This is not a simple alias to setTimeout(fn, 0). It is much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.

\n
console.log('start');\nprocess.nextTick(() => {\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
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.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
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}\n
\n

Note: the next tick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true); loop.

\n" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "meta": { "added": [ "v0.5.9" ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} ", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "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

Note: This function uses JSON.stringify() internally to serialize the\nmessage.*

\n" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A group name or ID ", "name": "id", "type": "string|number", "desc": "A group name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} A user name or ID ", "name": "id", "type": "string|number", "desc": "A user name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {string|number} The group name or ID ", "name": "id", "type": "string|number", "desc": "The group name or ID" } ] }, { "params": [ { "name": "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`groups` {Array} ", "name": "groups", "type": "Array" } ] }, { "params": [ { "name": "groups" } ] } ], "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 process\nto have root or the CAP_SETGID capability.

\n

The groups array can contain numeric group IDs, group names or both.

\n

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n" }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ] }, "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
if (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

Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)

\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ] }, "signatures": [ { "params": [ { "textRaw": "`mask` {number} ", "name": "mask", "type": "number", "optional": true } ] }, { "params": [ { "name": "mask", "optional": true } ] } ], "desc": "

The process.umask() method sets or returns the Node.js process's file mode\ncreation mask. Child processes inherit the mask from the parent process. Invoked\nwithout an argument, the current mask is returned, otherwise the umask is set to\nthe argument value and the previous mask is returned.

\n
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n" }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {number} ", "name": "return", "type": "number" }, "params": [] }, { "params": [] } ], "desc": "

The process.uptime() method returns the number of seconds the current Node.js\nprocess has been running.

\n

Note: the return value includes fractions of a second. Use Math.floor()\nto get whole seconds.

\n" } ], "properties": [ { "textRaw": "`arch` {string} ", "type": "string", "name": "arch", "meta": { "added": [ "v0.5.0" ] }, "desc": "

The process.arch property returns a string identifying the operating system CPU\narchitecture for which the Node.js binary was compiled.

\n

The current possible values are: 'arm', 'arm64', 'ia32', 'mips',\n'mipsel', 'ppc', 'ppc64', 's390', 's390x', 'x32', and 'x64'.

\n
console.log(`This processor architecture is ${process.arch}`);\n
\n" }, { "textRaw": "`argv` {Array} ", "type": "Array", "name": "argv", "meta": { "added": [ "v0.1.27" ] }, "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 of\nargv[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
// print process.argv\nprocess.argv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n
\n

Launching the Node.js process as:

\n
$ node process-2.js one two=three four\n
\n

Would generate the output:

\n
0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n
\n" }, { "textRaw": "`argv0` {string} ", "type": "string", "name": "argv0", "meta": { "added": [ "6.4.0" ] }, "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
\n" }, { "textRaw": "`config` {Object} ", "type": "Object", "name": "config", "meta": { "added": [ "v0.7.7" ] }, "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     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: 'true'\n   }\n}\n
\n

Note: The process.config property is not read-only and there are\nexisting modules in the ecosystem that are known to extend, modify, or entirely\nreplace the value of process.config.

\n" }, { "textRaw": "`connected` {boolean} ", "type": "boolean", "name": "connected", "meta": { "added": [ "v0.7.2" ] }, "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().

\n" }, { "textRaw": "`env` {Object} ", "type": "Object", "name": "env", "meta": { "added": [ "v0.1.27" ] }, "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. In other words, the following example\nwould not work:

\n
$ node -e 'process.env.foo = "bar"' && echo $foo\n
\n

While the following will:

\n
process.env.foo = 'bar';\nconsole.log(process.env.foo);\n
\n

Assigning a property on process.env will implicitly convert the value\nto a string.

\n

Example:

\n
process.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
\n

Use delete to delete a property from process.env.

\n

Example:

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\n

On Windows operating systems, environment variables are case-insensitive.

\n

Example:

\n
process.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
\n" }, { "textRaw": "`execArgv` {Object} ", "type": "Object", "name": "execArgv", "meta": { "added": [ "v0.7.7" ] }, "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

For example:

\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" }, { "textRaw": "`execPath` {string} ", "type": "string", "name": "execPath", "meta": { "added": [ "v0.1.100" ] }, "desc": "

The process.execPath property returns the absolute pathname of the executable\nthat started the Node.js process.

\n

For example:

\n\n
'/usr/local/bin/node'\n
\n" }, { "textRaw": "`exitCode` {integer} ", "type": "integer", "name": "exitCode", "meta": { "added": [ "v0.11.8" ] }, "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.

\n" }, { "textRaw": "process.mainModule", "name": "mainModule", "meta": { "added": [ "v0.1.17" ] }, "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.

\n" }, { "textRaw": "`noDeprecation` {boolean} ", "type": "boolean", "name": "noDeprecation", "meta": { "added": [ "v0.8.0" ] }, "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.

\n" }, { "textRaw": "`pid` {integer} ", "type": "integer", "name": "pid", "meta": { "added": [ "v0.1.15" ] }, "desc": "

The process.pid property returns the PID of the process.

\n
console.log(`This process is pid ${process.pid}`);\n
\n" }, { "textRaw": "`platform` {string} ", "type": "string", "name": "platform", "meta": { "added": [ "v0.1.16" ] }, "desc": "

The process.platform property returns a string identifying the operating\nsystem platform on which the Node.js process is running. For instance\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

\n
console.log(`This platform is ${process.platform}`);\n
\n" }, { "textRaw": "`ppid` {integer} ", "type": "integer", "name": "ppid", "meta": { "added": [ "v6.13.0" ] }, "desc": "

The process.ppid property returns the PID of the current parent process.

\n
console.log(`The parent process is pid ${process.ppid}`);\n
\n" }, { "textRaw": "process.release", "name": "release", "meta": { "added": [ "v3.0.0" ] }, "desc": "

The process.release property returns an Object containing metadata related to\nthe 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' for Node.js. For\nlegacy io.js releases, this will be 'io.js'.
  • \n
  • lts: a string with a value indicating the codename of the LTS (Long-term\nSupport) line the current release is part of. This property only exists for\nLTS releases and is undefined for all other release types, including stable\nreleases. Current valid values are:
      \n
    • 'Argon' for the v4.x LTS line beginning with v4.2.0.
    • \n
    • 'Boron' for the v6.x LTS line beginning with v6.9.0.
    • \n
    \n
  • \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.\nIf the Node.js release is not an LTS release, this will be undefined.
  • \n
\n

For example:

\n\n
{\n  name: 'node',\n  lts: 'Argon',\n  sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.4.5/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.

\n" }, { "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

Note: process.stderr differs from other Node.js streams in important ways,\nsee note on process I/O for more information.

\n" }, { "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 example:

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  const chunk = process.stdin.read();\n  if (chunk !== null) {\n    process.stdout.write(`data: ${chunk}`);\n  }\n});\n\nprocess.stdin.on('end', () => {\n  process.stdout.write('end');\n});\n
\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

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

\n" }, { "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
process.stdin.pipe(process.stdout);\n
\n

Note: process.stdout differs from other Node.js streams in important ways,\nsee note on process I/O for more information.

\n", "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. They cannot be closed (end() will throw).
  4. \n
  5. They will never emit the 'finish' event.
  6. \n
  7. Writes may be synchronous depending on what the stream is connected to\nand whether the system is Windows or POSIX:
      \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
  8. \n
\n

These behaviors are partly for historical reasons, as changing them would\ncreate backwards 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.

\n", "type": "module", "displayName": "A note on process I/O" } ] }, { "textRaw": "`throwDeprecation` {boolean} ", "type": "boolean", "name": "throwDeprecation", "meta": { "added": [ "v0.9.12" ] }, "desc": "

The process.throwDeprecation property indicates whether the\n--throw-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.

\n" }, { "textRaw": "`title` {string} ", "type": "string", "name": "title", "meta": { "added": [ "v0.1.104" ] }, "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

Note: When a new value is assigned, different platforms will impose different\nmaximum length restrictions on the title. Usually such restrictions are quite\nlimited. For instance, on Linux and macOS, process.title is limited to the\nsize of the binary name plus the length of the command line arguments because\nsetting the process.title overwrites the argv memory of the process.\nNode.js v0.8 allowed for longer process title strings by also overwriting the\nenviron memory but that was potentially insecure and confusing in some\n(rather obscure) cases.

\n" }, { "textRaw": "`traceDeprecation` {boolean} ", "type": "boolean", "name": "traceDeprecation", "meta": { "added": [ "v0.8.0" ] }, "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.

\n" }, { "textRaw": "`version` {string} ", "type": "string", "name": "version", "meta": { "added": [ "v0.1.3" ] }, "desc": "

The process.version property returns the Node.js version string.

\n
console.log(`Version: ${process.version}`);\n
\n" }, { "textRaw": "`versions` {Object} ", "type": "Object", "name": "versions", "meta": { "added": [ "v0.2.0" ] }, "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
console.log(process.versions);\n
\n

Will generate an object similar to:

\n\n
{\n  http_parser: '2.3.0',\n  node: '1.1.1',\n  v8: '4.1.0.14',\n  uv: '1.3.0',\n  zlib: '1.2.8',\n  ares: '1.10.0-DEV',\n  modules: '43',\n  icu: '55.1',\n  openssl: '1.0.1k'\n}\n
\n" } ] } ], "vars": [ { "textRaw": "\\_\\_dirname", "name": "\\_\\_dirname", "meta": { "added": [ "v0.1.27" ] }, "type": "var", "desc": "
    \n
  • {string}
  • \n
\n

The directory name of the current module. This the same as the\npath.dirname() of the __filename.

\n

__dirname is not actually a global but rather local to each module.

\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
\n" }, { "textRaw": "\\_\\_filename", "name": "\\_\\_filename", "meta": { "added": [ "v0.0.1" ] }, "type": "var", "desc": "
    \n
  • {string}
  • \n
\n

The file name of the current module. This is the resolved absolute path of the\ncurrent module file.

\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

__filename is not actually a global but rather local to each 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.

\n" }, { "textRaw": "exports", "name": "exports", "meta": { "added": [ "v0.1.12" ] }, "type": "var", "desc": "

A reference to the module.exports that is shorter to type.\nSee module system documentation for details on when to use exports and\nwhen to use module.exports.

\n

exports is not actually a global but rather local to each module.

\n

See the module system documentation for more information.

\n" }, { "textRaw": "module", "name": "module", "meta": { "added": [ "v0.1.16" ] }, "type": "var", "desc": "
    \n
  • {Object}
  • \n
\n

A reference to the current module. In particular\nmodule.exports is used for defining what a module exports and makes\navailable through require().

\n

module is not actually a global but rather local to each module.

\n

See the module system documentation for more information.

\n" }, { "textRaw": "require()", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ] }, "desc": "
    \n
  • {Function}
  • \n
\n

To require modules. See the Modules section. require is not actually a\nglobal but rather local to each module.

\n", "properties": [ { "textRaw": "`cache` {Object} ", "type": "Object", "name": "cache", "meta": { "added": [ "v0.3.0" ] }, "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. Note that\nthis does not apply to native addons, for which reloading will result in an\nError.

\n" }, { "textRaw": "`extensions` {Object} ", "type": "Object", "name": "extensions", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.10.6" ] }, "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\nnon-JavaScript modules into Node.js by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node.js program, or compiling them to\nJavaScript ahead of time.

\n

Since the Module system is locked, this feature will probably never go\naway. However, it may have subtle bugs and complexities that are best\nleft untouched.

\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.0" ] }, "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", "signatures": [ { "params": [] } ] } ] } ] }