{ "source": "doc/api/all.markdown", "miscs": [ { "textRaw": "About this Documentation", "name": "About this Documentation", "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\n

\n

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

\n

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

\n

Every .html and .json file is generated based on the corresponding\n.markdown file in the doc/api/ folder in Node.js's source tree. The\ndocumentation is generated using the tools/doc/generate.js program.\nThe HTML template is located at doc/template.html.\n\n\n

\n

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

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

\n

The stability indices are as follows:\n\n

\n
Stability: 0 - Deprecated\nThis feature is known to be problematic, and changes are\nplanned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards\ncompatibility should not be expected.
\n
Stability: 1 - Experimental\nThis feature is subject to change, and is gated by a command line flag.\nIt may change or be removed in future versions.
\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
Stability: 3 - Locked\nOnly fixes related to security, performance, or bug fixes will be accepted.\nPlease do not suggest API changes in this area; they will be refused.
\n" }, { "textRaw": "JSON Output", "name": "json_output", "stability": 1, "stabilityText": "Experimental", "desc": "

Every HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n

\n

This feature was added in Node.js v0.6.12. It is experimental.\n\n

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

\n

Caveat: some syscalls, like lchown(2), are BSD-specific. That means, for\nexample, that fs.lchown() only works on Mac OS X and other BSD-derived systems,\nand is not available on Linux.\n\n

\n

Most Unix syscalls have Windows equivalents, but behavior may differ on Windows\nrelative to Linux and OS X. 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": "Synopsis", "name": "Synopsis", "type": "misc", "desc": "

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

\n
const http = require('http');\n\nhttp.createServer( (request, response) => {\n  response.writeHead(200, {'Content-Type': 'text/plain'});\n  response.end('Hello World\\n');\n}).listen(8124);\n\nconsole.log('Server running at http://127.0.0.1:8124/');
\n

To run the server, put the code into a file called example.js and execute\nit with the node program\n\n

\n
$ node example.js\nServer running at http://127.0.0.1:8124/
\n

All of the examples in the documentation can be run similarly.\n\n

\n" }, { "textRaw": "Command Line Options", "name": "Command Line Options", "type": "misc", "desc": "

Node.js comes with a wide variety of CLI options. These options expose built-in\ndebugging, multiple ways to execute scripts, and other helpful runtime options.\n\n

\n

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

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

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

\n

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

\n

node --v8-options\n\n

\n

Execute without arguments to start the [REPL][].\n\n

\n

For more info about node debug, please see the [debugger][] documentation.\n\n\n

\n", "type": "misc", "displayName": "Synopsis" }, { "textRaw": "Options", "name": "options", "modules": [ { "textRaw": "`-v`, `--version`", "name": "`-v`,_`--version`", "desc": "

Print node's version.\n\n\n

\n", "type": "module", "displayName": "`-v`, `--version`" }, { "textRaw": "`-h`, `--help`", "name": "`-h`,_`--help`", "desc": "

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

\n", "type": "module", "displayName": "`-h`, `--help`" }, { "textRaw": "`-e`, `--eval \"script\"`", "name": "`-e`,_`--eval_\"script\"`", "desc": "

Evaluate the following argument as JavaScript.\n\n\n

\n", "type": "module", "displayName": "`-e`, `--eval \"script\"`" }, { "textRaw": "`-p`, `--print \"script\"`", "name": "`-p`,_`--print_\"script\"`", "desc": "

Identical to -e but prints the result.\n\n\n

\n", "type": "module", "displayName": "`-p`, `--print \"script\"`" }, { "textRaw": "`-c`, `--check`", "name": "`-c`,_`--check`", "desc": "

Syntax check the script without executing.\n\n\n

\n", "type": "module", "displayName": "`-c`, `--check`" }, { "textRaw": "`-i`, `--interactive`", "name": "`-i`,_`--interactive`", "desc": "

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

\n", "type": "module", "displayName": "`-i`, `--interactive`" }, { "textRaw": "`-r`, `--require module`", "name": "`-r`,_`--require_module`", "desc": "

Preload the specified module at startup.\n\n

\n

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

\n", "type": "module", "displayName": "`-r`, `--require module`" }, { "textRaw": "`--no-deprecation`", "name": "`--no-deprecation`", "desc": "

Silence deprecation warnings.\n\n\n

\n", "type": "module", "displayName": "`--no-deprecation`" }, { "textRaw": "`--trace-deprecation`", "name": "`--trace-deprecation`", "desc": "

Print stack traces for deprecations.\n\n\n

\n", "type": "module", "displayName": "`--trace-deprecation`" }, { "textRaw": "`--throw-deprecation`", "name": "`--throw-deprecation`", "desc": "

Throw errors for deprecations.\n\n\n

\n", "type": "module", "displayName": "`--throw-deprecation`" }, { "textRaw": "`--trace-sync-io`", "name": "`--trace-sync-io`", "desc": "

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

\n", "type": "module", "displayName": "`--trace-sync-io`" }, { "textRaw": "`--zero-fill-buffers`", "name": "`--zero-fill-buffers`", "desc": "

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

\n", "type": "module", "displayName": "`--zero-fill-buffers`" }, { "textRaw": "`--track-heap-objects`", "name": "`--track-heap-objects`", "desc": "

Track heap object allocations for heap snapshots.\n\n

\n", "type": "module", "displayName": "`--track-heap-objects`" }, { "textRaw": "`--zero-fill-buffers`", "name": "`--zero-fill-buffers`", "desc": "

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

\n", "type": "module", "displayName": "`--zero-fill-buffers`" }, { "textRaw": "`--prof-process`", "name": "`--prof-process`", "desc": "

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

\n", "type": "module", "displayName": "`--prof-process`" }, { "textRaw": "`--v8-options`", "name": "`--v8-options`", "desc": "

Print v8 command line options.\n\n\n

\n", "type": "module", "displayName": "`--v8-options`" }, { "textRaw": "`--tls-cipher-list=list`", "name": "`--tls-cipher-list=list`", "desc": "

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

\n", "type": "module", "displayName": "`--tls-cipher-list=list`" }, { "textRaw": "`--enable-fips`", "name": "`--enable-fips`", "desc": "

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

\n", "type": "module", "displayName": "`--enable-fips`" }, { "textRaw": "`--force-fips`", "name": "`--force-fips`", "desc": "

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

\n", "type": "module", "displayName": "`--force-fips`" }, { "textRaw": "`--icu-data-dir=file`", "name": "`--icu-data-dir=file`", "desc": "

Specify ICU data load path. (overrides NODE_ICU_DATA)\n\n\n

\n", "type": "module", "displayName": "`--icu-data-dir=file`" } ], "type": "misc", "displayName": "Options" }, { "textRaw": "Environment Variables", "name": "environment_variables", "modules": [ { "textRaw": "`NODE_DEBUG=module[,…]`", "name": "`node_debug=module[,…]`", "desc": "

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

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

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

\n

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

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

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

\n", "type": "module", "displayName": "`NODE_DISABLE_COLORS=1`" }, { "textRaw": "`NODE_ICU_DATA=file`", "name": "`node_icu_data=file`", "desc": "

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

\n", "type": "module", "displayName": "`NODE_ICU_DATA=file`" }, { "textRaw": "`NODE_REPL_HISTORY=file`", "name": "`node_repl_history=file`", "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\n\n

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

Node.js includes a full-featured out-of-process debugging utility accessible\nvia a simple [TCP-based protocol][] and built-in debugging client. To use it,\nstart Node.js with the debug argument followed by the path to the script to\ndebug; a prompt will be displayed indicating successful launch of the debugger:\n\n

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

Node.js's debugger client does not yet support the full range of commands, but\nsimple step and inspection are possible.\n\n

\n

Inserting the statement debugger; into the source code of a script will\nenable a breakpoint at that position in the code.\n\n

\n

For example, suppose myscript.js is written as:\n\n

\n
// myscript.js\nx = 5;\nsetTimeout(() => {\n  debugger;\n  console.log('world');\n}, 1000);\nconsole.log('hello');
\n

Once the debugger is run, a breakpoint will occur at line 4:\n\n

\n
$ node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(() => {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 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\n< world\nbreak in /home/indutny/Code/git/indutny/myscript.js:5\n  3   debugger;\n  4   console.log('world');\n  5 }, 1000);\n  6 console.log('hello');\n  7\ndebug> quit
\n

The repl command allows code to be evaluated remotely. The next command\nsteps over to the next line. Type help to see what other commands are\navailable.\n\n

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

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

\n", "type": "misc", "displayName": "Watchers" }, { "textRaw": "Commands reference", "name": "commands_reference", "modules": [ { "textRaw": "Stepping", "name": "Stepping", "desc": "

It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

\n
$ ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 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', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = () => {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
\n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Breakpoints", "name": "breakpoints", "desc": "

It is also possible to set a breakpoint in a file (module) that\nisn't loaded yet:\n\n

\n
$ ./node debug test/fixtures/break-in-module/main.js\n< debugger listening on port 5858\nconnecting to port 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', 23)\nWarning: script 'mod.js' was not loaded yet.\n  1 var mod = require('./mod.js');\n  2 mod.hello();\n  3 mod.hello();\ndebug> c\nbreak in test/fixtures/break-in-module/mod.js:23\n 21\n 22 exports.hello = () => {\n 23   return 'hello from module';\n 24 };\n 25\ndebug>
\n", "type": "module", "displayName": "Breakpoints" }, { "textRaw": "Execution control", "name": "Execution control", "type": "module", "displayName": "Various" }, { "textRaw": "Various", "name": "various", "type": "module", "displayName": "Various" } ], "type": "misc", "displayName": "Commands 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\n

\n

Once a process has been set in debug mode this way, it can be connected to\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

\n\n", "type": "misc", "displayName": "Advanced Usage" } ] }, { "textRaw": "Errors", "name": "Errors", "type": "misc", "desc": "

Applications running in Node.js will generally experience four categories of\nerrors:\n\n

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

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

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

\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

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

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

\n

Errors that occur within Asynchronous APIs may be reported in multiple ways:\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\n

\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\n[process.on('uncaughtException')][] event.\n\n

\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

Errors generated in this way cannot be intercepted using try / catch as\nthey are thrown after the calling code has already exited.\n\n

\n

Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.\n\n

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

\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

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

\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.log(err);\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\n

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

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

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

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

\n

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

\n", "classes": [ { "textRaw": "Class: System Error", "type": "class", "name": "System", "properties": [ { "textRaw": "error.code", "name": "code", "desc": "

Returns a string representing the error code, which is always E followed by\na sequence of capital letters, and may be referenced in man 2 intro.\n\n

\n

The properties error.code and error.errno are aliases of one another and\nreturn the same value.\n\n

\n" }, { "textRaw": "error.errno", "name": "errno", "desc": "

Returns a string representing the error code, which is always E followed by\na sequence of capital letters, and may be referenced in man 2 intro.\n\n

\n

The properties error.code and error.errno are aliases of one another and\nreturn the same value.\n\n

\n" }, { "textRaw": "error.syscall", "name": "syscall", "desc": "

Returns a string describing the [syscall][] that failed.\n\n

\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][online].\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\n

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

\n", "methods": [ { "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])", "type": "method", "name": "captureStackTrace", "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\n

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack  // similar to `new Error().stack`
\n

The first line of the trace, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().\n\n

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

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:\n\n

\n
function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would should up in the .stack property. by passing\n// the constructor, we omit that frame and all frames above it.\nnew MyError().stack
\n", "signatures": [ { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ] } ], "properties": [ { "textRaw": "Error.stackTraceLimit", "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\n

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

\n

If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.\n\n

\n", "properties": [ { "textRaw": "error.message", "name": "message", "desc": "

Returns the string description of 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\n

\n
const err = new Error('The message');\nconsole.log(err.message);\n  // Prints: The message
\n" }, { "textRaw": "error.stack", "name": "stack", "desc": "

Returns a string describing the point in the code at which the Error was\ninstantiated.\n\n

\n

For example:\n\n

\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

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

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

\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

The location information will be one of:\n\n

\n\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.\n\n

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

\n

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

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

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

\n

For example:\n\n

\n
require('net').connect(-1);\n  // throws RangeError, port should be > 0 && < 65536
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.\n\n

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

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.\n\n

\n
doesNotExist;\n  // throws ReferenceError, doesNotExist is not a variable in this program.
\n

ReferenceError instances will have an error.arguments property whose value\nis an array containing a single element: a string representing the variable\nthat was not defined.\n\n

\n
const assert = require('assert');\ntry {\n  doesNotExist;\n} catch(err) {\n  assert(err.arguments[0], 'doesNotExist');\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\n

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

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n  // err will be a SyntaxError\n}
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.\n\n

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

\n
require('url').parse(function() { });\n  // throws TypeError, since it expected a string
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.\n\n

\n" } ] }, { "textRaw": "Global Objects", "name": "Global Objects", "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\n

\n", "globals": [ { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

Used to handle binary data. See the [buffer section][].\n\n

\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "desc": "

[clearImmediate] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "clearInterval(intervalObject)", "type": "global", "name": "clearInterval", "desc": "

[clearInterval] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "clearTimeout(timeoutObject)", "type": "global", "name": "clearTimeout", "desc": "

[clearTimeout] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

Used to print to stdout and stderr. See the [console][] section.\n\n

\n" }, { "textRaw": "global", "name": "global", "type": "global", "desc": "

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

\n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

The process object. See the [process object][] section.\n\n

\n" }, { "textRaw": "setImmediate(callback[, arg][, ...])", "type": "global", "name": "setImmediate", "desc": "

[setImmediate] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "setInterval(callback, delay[, arg][, ...])", "type": "global", "name": "setInterval", "desc": "

[setInterval] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "setTimeout(callback, delay[, arg][, ...])", "type": "global", "name": "setTimeout", "desc": "

[setTimeout] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n

\n", "events": [ { "textRaw": "Event: 'beforeExit'", "type": "event", "name": "beforeExit", "desc": "

This event is emitted when Node.js empties its event loop and has nothing else \nto schedule. Normally, Node.js exits when there is no work scheduled, but a \nlistener for 'beforeExit' can make asynchronous calls, and cause Node.js to \ncontinue.\n\n

\n

'beforeExit' is not emitted for conditions causing explicit termination, such \nas [process.exit()][] or uncaught exceptions, and should not be used as an\nalternative to the 'exit' event unless the intention is to schedule more work.\n\n

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all 'exit' listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.\n\n

\n

This event is only emitted when Node.js exits explicitly by process.exit() or\nimplicitly by the event loop draining.\n\n

\n

Example of listening for 'exit':\n\n

\n
process.on('exit', (code) => {\n  // do *NOT* do this\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});
\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Messages sent by [ChildProcess.send()][] are obtained using the 'message'\nevent on the child's process object.\n\n

\n" }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "desc": "

Emitted whenever a Promise was rejected and an error handler was attached to it\n(for example with .catch()) later than after an event loop turn. This event\nis emitted with the following arguments:\n\n

\n\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 rejection\ncan be handled at a future point in time — possibly much later than the\nevent loop turn it takes for the 'unhandledRejection' event to be emitted.\n\n

\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 is a\ngrowing-and-shrinking list of unhandled rejections. In synchronous code, the\n'uncaughtException' event tells you when the list of unhandled exceptions\ngrows. And in asynchronous code, the 'unhandledRejection' event tells you\nwhen the list of unhandled rejections grows, while the 'rejectionHandled'\nevent tells you when the list of unhandled rejections shrinks.\n\n

\n

For example using the rejection detection hooks in order to keep a map of all\nthe rejected promise reasons at a given time:\n\n

\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

This map will grow and shrink over time, reflecting rejections that start\nunhandled and then become handled. You could record the errors in some error\nlog, either periodically (probably best for long-running programs, allowing\nyou to clear the map, which in the case of a very buggy program could grow\nindefinitely) or upon process exit (more convenient for scripts).\n\n

\n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "desc": "

The 'uncaughtException' event is emitted when an exception bubbles all the\nway back to the event loop. By default, Node.js handles such exceptions by \nprinting the stack trace to stderr and exiting. Adding a handler for the\n'uncaughtException' event overrides this default behavior.\n\n

\n

For example:\n\n

\n
process.on('uncaughtException', (err) => {\n  console.log(`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", "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\n

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

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

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

\n", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ], "params": [] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "desc": "

Emitted whenever a Promise is rejected and no error handler is attached to\nthe promise within a turn of the event loop. When programming with promises\nexceptions are encapsulated as rejected promises. Such promises can be caught\nand handled using [promise.catch(...)][] and rejections are propagated through\na promise chain. This event is useful for detecting and keeping track of\npromises that were rejected whose rejections were not handled yet. This event\nis emitted with the following arguments:\n\n

\n\n

Here is an example that logs every unhandled rejection to the console\n\n

\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

For example, here is a rejection that will trigger the 'unhandledRejection'\nevent:\n\n

\n
somePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch` or `.then`
\n

Here is an example of a coding pattern that will also trigger\n'unhandledRejection':\n\n

\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\nvar resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn
\n

In cases like this, you may not want to track the rejection as a developer\nerror like you would for other 'unhandledRejection' events. To address\nthis, you can either attach a dummy .catch(() => { }) handler to\nresource.loaded, preventing the 'unhandledRejection' event from being\nemitted, or you can use the ['rejectionHandled'][] event.\n\n

\n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n

\n

Example of listening for SIGINT:\n\n

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n

\n

Note:\n\n

\n\n

Note that Windows does not support sending Signals, but Node.js offers some\nemulation with process.kill(), and child_process.kill(). Sending signal 0\ncan be used to test for the existence of a process. Sending SIGINT,\nSIGTERM, and SIGKILL cause the unconditional termination of the target\nprocess.\n\n

\n", "params": [] } ], "modules": [ { "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", "desc": "

This causes Node.js to emit an abort. This will cause Node.js to exit and\ngenerate a core file.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "

Changes the current working directory of the process or throws an exception if that fails.\n\n

\n
console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n}\ncatch (err) {\n  console.log(`chdir: ${err}`);\n}
\n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "desc": "

Returns the current working directory of the process.\n\n

\n
console.log(`Current directory: ${process.cwd()}`);
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.disconnect()", "type": "method", "name": "disconnect", "desc": "

Close the IPC channel to the parent process, allowing this child to exit\ngracefully once there are no other connections keeping it alive.\n\n

\n

Identical to the parent process's [ChildProcess.disconnect()][].\n\n

\n

If Node.js was not spawned with an IPC channel, process.disconnect() will be\nundefined.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

\n

To exit with a 'failure' code:\n\n

\n
process.exit(1);
\n

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

\n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the effective group identity of the process. (See getegid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the effective user identity of the process. (See geteuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but Node.js ensures it always is.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

\n
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n

\n

user is a user name or user ID. extra_group is a group name or group ID.\n\n

\n

Some care needs to be taken when dropping privileges. Example:\n\n

\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", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\nSIGINT or SIGHUP. If omitted, the signal will be SIGTERM.\nSee [Signal Events][] and kill(2) for more information.\n\n

\n

Will throw an error if target does not exist, and as a special case, a signal\nof 0 can be used to test for the existence of a process. Windows platforms\nwill throw an error if the pid is used to kill a process group.\n\n

\n

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

\n

Example of sending a signal to yourself:\n\n

\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

Note: When SIGUSR1 is received by Node.js it starts the debugger, see\n[Signal Events][].\n\n

\n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "

Returns an object describing the memory usage of the Node.js process\nmeasured in bytes.\n\n

\n
const util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\n

This will generate:\n\n

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

heapTotal and heapUsed refer to V8's memory usage.\n\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback[, arg][, ...])", "type": "method", "name": "nextTick", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ], "desc": "

Once the current event loop turn runs to completion, call the callback\nfunction.\n\n

\n

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

\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

This is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n

\n
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
\n

It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n

\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

This API is hazardous. If you do this:\n\n

\n
maybeSync(true, () => {\n  foo();\n});\nbar();
\n

then it's not clear whether foo() or bar() will be called first.\n\n

\n

This approach is much better:\n\n

\n
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n

Note: the nextTick 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\n

\n" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object" }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle" }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

When Node.js is spawned with an IPC channel attached, it can send messages to its\nparent process using process.send(). Each will be received as a\n['message'][] event on the parent's ChildProcess object.\n\n

\n

Note: this function uses [JSON.stringify()][] internally to serialize the message.\n\n

\n

If Node.js was not spawned with an IPC channel, process.send() will be undefined.\n\n

\n" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the effective group identity of the process. (See setegid(2).)\nThis accepts either a numerical ID or a groupname string. If a groupname\nis specified, this method blocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the effective user identity of the process. (See seteuid(2).)\nThis accepts either a numerical ID or a username string. If a username\nis specified, this method blocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n

\n

The list can contain group IDs, group names or both.\n\n

\n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

\n
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);
\n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

Number of seconds Node.js has been running.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "process.arch", "name": "arch", "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

\n
console.log('This processor architecture is ' + process.arch);
\n" }, { "textRaw": "process.argv", "name": "argv", "desc": "

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

\n
// print process.argv\nprocess.argv.forEach((val, index, array) => {\n  console.log(`${index}: ${val}`);\n});
\n

This will generate:\n\n

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n" }, { "textRaw": "process.config", "name": "config", "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current Node.js executable. This is the same as\nthe config.gypi file that was produced when running the ./configure script.\n\n

\n

An example of the possible output looks like:\n\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" }, { "textRaw": "`connected` {Boolean} Set to false after `process.disconnect()` is called ", "type": "Boolean", "name": "connected", "desc": "

If process.connected is false, it is no longer possible to send messages.\n\n

\n", "shortDesc": "Set to false after `process.disconnect()` is called" }, { "textRaw": "process.env", "name": "env", "desc": "

An object containing the user environment. See environ(7).\n\n

\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

You can write to this object, but changes won't be reflected outside of your\nprocess. That means that the following won't work:\n\n

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

But this will:\n\n

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

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

\n

Example:\n\n

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

Use delete to delete a property from process.env.\n\n

\n

Example:\n\n

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined
\n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

This is the set of Node.js-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv, and do not include the Node.js executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n

\n

Example:\n\n

\n
$ node --harmony script.js --version
\n

results in process.execArgv:\n\n

\n
['--harmony']
\n

and process.argv:\n\n

\n
['/usr/local/bin/node', 'script.js', '--version']
\n" }, { "textRaw": "process.execPath", "name": "execPath", "desc": "

This is the absolute pathname of the executable that started the process.\n\n

\n

Example:\n\n

\n
/usr/local/bin/node
\n" }, { "textRaw": "process.exitCode", "name": "exitCode", "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\n

\n

Specifying a code to process.exit(code) will override any previous\nsetting of process.exitCode.\n\n\n

\n" }, { "textRaw": "process.mainModule", "name": "mainModule", "desc": "

Alternate way to retrieve [require.main][]. The difference is that if the main\nmodule changes at runtime, require.main might still refer to the original main\nmodule in modules that were required before the change occurred. Generally it's\nsafe to assume that the two refer to the same module.\n\n

\n

As with require.main, it will be undefined if there was no entry script.\n\n

\n" }, { "textRaw": "process.pid", "name": "pid", "desc": "

The PID of the process.\n\n

\n
console.log(`This process is pid ${process.pid}`);
\n" }, { "textRaw": "process.platform", "name": "platform", "desc": "

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

\n
console.log(`This platform is ${process.platform}`);
\n" }, { "textRaw": "process.release", "name": "release", "desc": "

An Object containing metadata related to the current release, including URLs\nfor the source tarball and headers-only tarball.\n\n

\n

process.release contains the following properties:\n\n

\n\n

e.g.\n\n

\n
{ name: 'node',\n  sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }
\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\n

\n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

A writable stream to stderr (on fd 2).\n\n

\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed (end() will throw), they never emit the finish\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)\n\n

\n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

A Readable Stream for stdin (on fd 0).\n\n

\n

Example of opening standard input and listening for both events:\n\n

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  var 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

As a Stream, process.stdin can also be used in "old" mode that is compatible\nwith scripts written for node.js prior to v0.10.\nFor more information see [Stream compatibility][].\n\n

\n

In "old" Streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to "old" mode.\n\n

\n

If you are starting a new project you should prefer a more recent "new" Streams\nmode over "old" one.\n\n

\n" }, { "textRaw": "process.stdout", "name": "stdout", "desc": "

A Writable Stream to stdout (on fd 1).\n\n

\n

For example, a console.log equivalent could look like this:\n\n

\n
console.log = (msg) => {\n  process.stdout.write(`${msg}\\n`);\n};
\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed (end() will throw), they never emit the 'finish'\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)\n\n

\n

To check if Node.js is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:\n\n

\n
$ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
\n

See [the tty docs][] for more information.\n\n

\n" }, { "textRaw": "process.title", "name": "title", "desc": "

Getter/setter to set what is displayed in ps.\n\n

\n

When used as a setter, the maximum length is platform-specific and probably\nshort.\n\n

\n

On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n

\n

v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n

\n" }, { "textRaw": "process.version", "name": "version", "desc": "

A compiled-in property that exposes NODE_VERSION.\n\n

\n
console.log(`Version: ${process.version}`);
\n" }, { "textRaw": "process.versions", "name": "versions", "desc": "

A property exposing version strings of Node.js and its dependencies.\n\n

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

Will print something like:\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" } ] } ], "vars": [ { "textRaw": "\\_\\_dirname", "name": "\\_\\_dirname", "type": "var", "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n

\n

For instance, given two modules: a and b, where b is a dependency of\na and there is a directory structure of:\n\n

\n\n

References to __dirname within b.js will return\n/Users/mjr/app/node_modules/b while references to __dirname within a.js\nwill return /Users/mj/app.\n\n

\n" }, { "textRaw": "\\_\\_filename", "name": "\\_\\_filename", "type": "var", "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" }, { "textRaw": "exports", "name": "exports", "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\n

\n

exports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

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

\n

module isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" }, { "textRaw": "require()", "type": "var", "name": "require", "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", "properties": [ { "textRaw": "`cache` {Object} ", "type": "Object", "name": "cache", "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.\n\n

\n" }, { "textRaw": "`extensions` {Object} ", "type": "Object", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\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\n

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

\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "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\n

\n", "signatures": [ { "params": [] } ] } ] } ] } ], "modules": [ { "textRaw": "Addons", "name": "addons", "desc": "

Node.js Addons are dynamically-linked shared objects, written in C or C++, that\ncan be loaded into Node.js using the [require()][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\n

\n

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

\n\n

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

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

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

First, create the file hello.cc:\n\n

\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

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

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

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

\n

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

\n

In the hello.cc example, then, the initialization function is init and the\nAddon module name is addon.\n\n

\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

\n
{\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "hello.cc" ]\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\n

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

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

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

\n

Once built, the binary Addon can be used from within Node.js by pointing\n[require()][require] to the built addon.node module:\n\n

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

Please see the examples below for further information or\n

\n

https://github.com/arturadib/node-qt for an example in production.\n\n

\n

Because the exact path to the compiled Addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/), Addons can use\nthe [bindings][] package to load the compiled module.\n\n

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

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

\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()][require] function is written to look for\nfiles with the .node file extension and initialize those as dynamically-linked\nlibraries.\n\n

\n

When calling [require()][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')][require] will give precedence to the addon.js file\nand load it instead.\n\n

\n", "type": "module", "displayName": "Loading Addons using require()" } ], "type": "module", "displayName": "Hello world" }, { "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][v8-docs]\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\n

\n

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

\n
{\n  "targets": [\n    {\n      "target_name": "addon",\n      "sources": [ "addon.cc" ]\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\n

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

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

\n
$ node-gyp configure build
\n", "modules": [ { "textRaw": "Function arguments", "name": "function_arguments", "desc": "

Addons will typically expose objects and functions that can be accessed from\nJavaScript running within Node.js. When functions are invoked from JavaScript,\nthe input arguments and return value must be mapped to and from the C/C++\ncode.\n\n

\n

The following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:\n\n

\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

Once compiled, the example Addon can be required and used from within Node.js:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));
\n", "type": "module", "displayName": "Function arguments" }, { "textRaw": "Callbacks", "name": "callbacks", "desc": "

It is common practice within Addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:\n\n

\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

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

\n

To test it, run the following JavaScript:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n  console.log(msg); // 'hello world'\n});
\n

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

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

\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

To test it in JavaScript:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nvar obj1 = addon('hello');\nvar obj2 = addon('world');\nconsole.log(obj1.msg + ' ' + obj2.msg); // 'hello world'
\n", "type": "module", "displayName": "Object factory" }, { "textRaw": "Function factory", "name": "function_factory", "desc": "

Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:\n\n

\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

To test:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nvar fn = addon();\nconsole.log(fn()); // 'hello world'
\n", "type": "module", "displayName": "Function factory" }, { "textRaw": "Wrapping C++ objects", "name": "wrapping_c++_objects", "desc": "

It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new operator:\n\n

\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

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

\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

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

\n
// myobject.cc\n#include "myobject.h"\n\nnamespace demo {\n\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<Function> cons = Local<Function>::New(isolate, constructor);\n    args.GetReturnValue().Set(cons->NewInstance(argc, argv));\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

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

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

Test it with:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log(obj.plusOne()); // 11\nconsole.log(obj.plusOne()); // 12\nconsole.log(obj.plusOne()); // 13
\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\n

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

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

\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

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

\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

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

\n
// myobject.cc\n#include <node.h>\n#include "myobject.h"\n\nnamespace demo {\n\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    args.GetReturnValue().Set(cons->NewInstance(argc, argv));\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<Object> instance = cons->NewInstance(argc, argv);\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

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

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

Test it with:\n\n

\n
// test.js\nconst createObject = require('./build/Release/addon');\n\nvar obj = createObject(10);\nconsole.log(obj.plusOne()); // 11\nconsole.log(obj.plusOne()); // 12\nconsole.log(obj.plusOne()); // 13\n\nvar obj2 = createObject(20);\nconsole.log(obj2.plusOne()); // 21\nconsole.log(obj2.plusOne()); // 22\nconsole.log(obj2.plusOne()); // 23
\n", "type": "module", "displayName": "Factory of wrapped objects" }, { "textRaw": "Passing wrapped objects around", "name": "passing_wrapped_objects_around", "desc": "

In addition to wrapping and returning C++ objects, it is possible to pass\nwrapped objects around by unwrapping them with the Node.js helper function\nnode::ObjectWrap::Unwrap. The following examples shows a function add()\nthat can take two MyObject objects as input arguments:\n\n

\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

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

\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

The implementation of myobject.cc is similar to before:\n\n

\n
// myobject.cc\n#include <node.h>\n#include "myobject.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::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<Function> cons = Local<Function>::New(isolate, constructor);\n    args.GetReturnValue().Set(cons->NewInstance(argc, argv));\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<Object> instance = cons->NewInstance(argc, argv);\n\n  args.GetReturnValue().Set(instance);\n}\n\n}  // namespace demo
\n

Test it with:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
\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 by before the JavaScript VM is terminated and Node.js shuts down.\n"AtExit" hooks are registered using the node::AtExit API.\n\n

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

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

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

\n

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

\n

The following addon.cc implements AtExit:\n\n

\n
// addon.cc\n#undef NDEBUG\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(sanity_check);\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb2, cookie);\n  AtExit(at_exit_cb1, exports->GetIsolate());\n}\n\nNODE_MODULE(addon, init);\n\n}  // namespace demo
\n

Test in JavaScript by running:\n\n

\n
// test.js\nconst addon = require('./build/Release/addon');
\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\n

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

\n" } ], "type": "module", "displayName": "Addons" }, { "textRaw": "Assert", "name": "assert", "stability": 3, "stabilityText": "Locked", "desc": "

The assert module provides a simple set of assertion tests that can be used to\ntest invariants. The module is intended for internal use by Node.js, but can be\nused in application code via require('assert'). However, assert is not a\ntesting framework, and is not intended to be used as a general purpose assertion\nlibrary.\n\n

\n

The API for the assert module is [Locked][]. This means that there will be no\nadditions or changes to any of the methods implemented and exposed by\nthe module.\n\n

\n", "methods": [ { "textRaw": "assert(value[, message])", "type": "method", "name": "assert", "desc": "

An alias of [assert.ok()][] .\n\n

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

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

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

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

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

\n
const assert = require('assert');\n\nconst obj1 = {\n  a : {\n    b : 1\n  }\n};\nconst obj2 = {\n  a : {\n    b : 2\n  }\n};\nconst obj3 = {\n  a : {\n    b : 1\n  }\n}\nconst obj4 = Object.create(obj1);\n\nassert.deepEqual(obj1, obj1);\n  // OK, 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

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

\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.deepStrictEqual(actual, expected[, message])", "type": "method", "name": "deepStrictEqual", "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\n

\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

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

\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.doesNotThrow(block[, error][, message])", "type": "method", "name": "doesNotThrow", "desc": "

Asserts that the function block does not throw an error. See\n[assert.throws()][] for more details.\n\n

\n

When assert.doesNotThrow() is called, it will immediately call the block\nfunction.\n\n

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

\n

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

\n
assert.doesNotThrow(\n  () => {\n    throw new TypeError('Wrong value');\n  },\n  SyntaxError\n);
\n

However, the following will result in an AssertionError with the message\n'Got unwanted exception (TypeError)..':\n\n

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

If an AssertionError is thrown and a value is provided for the message\nparameter, the value of message will be appended to the AssertionError\nmessage:\n\n

\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", "signatures": [ { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.equal(actual, expected[, message])", "type": "method", "name": "equal", "desc": "

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

\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

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

\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.fail(actual, expected, message, operator)", "type": "method", "name": "fail", "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.\n\n

\n
const assert = require('assert');\n\nassert.fail(1, 2, undefined, '>');\n  // AssertionError: 1 > 2\n\nassert.fail(1, 2, 'whoops', '>');\n  // AssertionError: whoops
\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message" }, { "name": "operator" } ] } ] }, { "textRaw": "assert.ifError(value)", "type": "method", "name": "ifError", "desc": "

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

\n
const assert = require('assert');\n\nassert.ifError(0); // OK\nassert.ifError(1); // Throws 1\nassert.ifError('error') // Throws 'error'\nassert.ifError(new Error()); // Throws Error
\n", "signatures": [ { "params": [ { "name": "value" } ] } ] }, { "textRaw": "assert.notDeepEqual(actual, expected[, message])", "type": "method", "name": "notDeepEqual", "desc": "

Tests for any deep inequality. Opposite of [assert.deepEqual()][].\n\n

\n
const assert = require('assert');\n\nconst obj1 = {\n  a : {\n    b : 1\n  }\n};\nconst obj2 = {\n  a : {\n    b : 2\n  }\n};\nconst obj3 = {\n  a : {\n    b : 1\n  }\n}\nconst obj4 = Object.create(obj1);\n\nassert.notDeepEqual(obj1, obj1);\n  // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n  // OK, 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 obj2 are not deeply equal
\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\n

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

Tests for deep strict inequality. Opposite of [assert.deepStrictEqual()][].\n\n

\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

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

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

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

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

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

Tests strict inequality as determined by the strict not equal operator\n( !== ).\n\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

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

\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.ok(value[, message])", "type": "method", "name": "ok", "desc": "

Tests if value is truthy. It is equivalent to\nassert.equal(!!value, true, message).\n\n

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

\n
const assert = require('assert');\n\nassert.ok(true);  // OK\nassert.ok(1);     // 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", "signatures": [ { "params": [ { "name": "value" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.strictEqual(actual, expected[, message])", "type": "method", "name": "strictEqual", "desc": "

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

\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

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

\n", "signatures": [ { "params": [ { "name": "actual" }, { "name": "expected" }, { "name": "message", "optional": true } ] } ] }, { "textRaw": "assert.throws(block[, error][, message])", "type": "method", "name": "throws", "desc": "

Expects the function block to throw an error.\n\n

\n

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

\n

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

\n

Validate instanceof using constructor:\n\n

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

Validate error message using [RegExp][]:\n\n

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

Custom error validation:\n\n

\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

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

\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", "signatures": [ { "params": [ { "name": "block" }, { "name": "error", "optional": true }, { "name": "message", "optional": true } ] } ] } ], "type": "module", "displayName": "Assert" }, { "textRaw": "Buffer", "name": "buffer", "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\n

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

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

\n

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

\n
const buf1 = Buffer.alloc(10);\n  // Creates a zero-filled Buffer of length 10.\n\nconst buf2 = Buffer.alloc(10, 1);\n  // Creates a Buffer of length 10, filled with 0x01.\n\nconst buf3 = Buffer.allocUnsafe(10);\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().\n\nconst buf4 = Buffer.from([1,2,3]);\n  // Creates a Buffer containing [01, 02, 03].\n\nconst buf5 = Buffer.from('test');\n  // Creates a Buffer containing ASCII bytes [74, 65, 73, 74].\n\nconst buf6 = Buffer.from('tést', 'utf8');\n  // Creates a Buffer containing UTF8 bytes [74, c3, a9, 73, 74].
\n", "modules": [ { "textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`", "name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`", "desc": "

Historically, Buffer instances have been created using the Buffer\nconstructor function, which allocates the returned Buffer\ndifferently based on what arguments are provided:\n\n

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

\n

To make the creation of Buffer objects more reliable and less error prone,\nnew Buffer.from(), Buffer.alloc(), and Buffer.allocUnsafe() methods have\nbeen introduced as an alternative means of creating Buffer instances.\n\n

\n

Developers should migrate all existing uses of the new Buffer() constructors\nto one of these new APIs.\n\n

\n\n

Buffer instances returned by Buffer.allocUnsafe(size) may be allocated\noff a shared internal memory pool if the size is less than or equal to half\nBuffer.poolSize.\n\n

\n", "modules": [ { "textRaw": "What makes `Buffer.allocUnsafe(size)` \"unsafe\"?", "name": "what_makes_`buffer.allocunsafe(size)`_\"unsafe\"?", "desc": "

When calling Buffer.allocUnsafe(), the segment of allocated memory is\nuninitialized (it is not zeroed-out). While this design makes the allocation\nof memory quite fast, the allocated segment of memory might contain old data\nthat is potentially sensitive. Using a Buffer created by\nBuffer.allocUnsafe(size) without completely overwriting the memory can\nallow this old data to be leaked when the Buffer memory is read.\n\n

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

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

Buffers are commonly used to represent sequences of encoded characters\nsuch as UTF8, UCS2, Base64 or even Hex-encoded data. It is possible to\nconvert back and forth between Buffers and ordinary JavaScript string objects\nby using an explicit encoding method.\n\n

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

The character encodings currently supported by Node.js include:\n\n

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

Buffers are also Uint8Array TypedArray instances. However, there are subtle\nincompatibilities with the TypedArray specification in ECMAScript 2015. For\ninstance, while ArrayBuffer#slice() creates a copy of the slice,\nthe implementation of [Buffer#slice()][buf.slice()] creates a view over the\nexisting Buffer without copying, making Buffer#slice() far more efficient.\n\n

\n

It is also possible to create new TypedArray instances from a Buffer with the\nfollowing caveats:\n\n

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

\n
const arr = new Uint16Array(2);\narr[0] = 5000;\narr[1] = 4000;\n\nconst buf1 = Buffer.from(arr); // copies the buffer\nconst buf2 = Buffer.from(arr.buffer); // shares the memory with arr;\n\nconsole.log(buf1);\n  // Prints: <Buffer 88 a0>, copied buffer has only two elements\nconsole.log(buf2);\n  // Prints: <Buffer 88 13 a0 0f>\n\narr[1] = 6000;\nconsole.log(buf1);\n  // Prints: <Buffer 88 a0>\nconsole.log(buf2);\n  // Prints: <Buffer 88 13 70 17>
\n

Note that when creating a Buffer using the TypedArray's .buffer, it is\npossible to use only a portion of the underlying ArrayBuffer by passing in\nbyteOffset and length parameters:\n\n

\n
const arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\nconsole.log(buf.length);\n  // Prints: 16
\n

The Buffer.from() and [TypedArray.from()][] (e.g.Uint8Array.from()) have\ndifferent signatures and implementations. Specifically, the TypedArray variants\naccept a second argument that is a mapping function that is invoked on every\nelement of the typed array:\n\n

\n\n

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

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

Buffers can be iterated over using the ECMAScript 2015 (ES6) for..of syntax:\n\n

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

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

\n", "type": "module", "displayName": "Buffers and ES6 iteration" }, { "textRaw": "The `--zero-fill-buffers` command line option", "name": "the_`--zero-fill-buffers`_command_line_option", "desc": "

Node.js can be started using the --zero-fill-buffers command line option to\nforce all newly allocated Buffer and SlowBuffer instances created using\neither new Buffer(size) and new SlowBuffer(size) to be automatically\nzero-filled upon creation. Use of this flag changes the default behavior of\nthese methods and can have a significant impact on performance. Use of the\n--zero-fill-buffers option is recommended only when absolutely necessary to\nenforce that newly allocated Buffer instances cannot contain potentially\nsensitive data.\n\n

\n
$ node --zero-fill-buffers\n> Buffer(5);\n<Buffer 00 00 00 00 00>
\n", "type": "module", "displayName": "The `--zero-fill-buffers` command line option" } ], "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\n

\n", "classMethods": [ { "textRaw": "Class Method: Buffer.alloc(size[, fill[, encoding]])", "type": "classMethod", "name": "alloc", "signatures": [ { "params": [ { "textRaw": "`size` {Number} ", "name": "size", "type": "Number" }, { "textRaw": "`fill` {Value} Default: `undefined` ", "name": "fill", "type": "Value", "desc": "Default: `undefined`" }, { "textRaw": "`encoding` {String} Default: `utf8` ", "name": "encoding", "type": "String", "desc": "Default: `utf8`", "optional": true } ] }, { "params": [ { "name": "size" }, { "name": "fill" }, { "name": "encoding", "optional": true } ] } ], "desc": "

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

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

The size must be less than or equal to the value of\nrequire('buffer').kMaxLength (on 64-bit architectures, kMaxLength is\n(2^31)-1). Otherwise, a [RangeError][] is thrown. If a size less than 0\nis specified, a zero-length Buffer will be created.\n\n

\n

If fill is specified, the allocated Buffer will be initialized by calling\nbuf.fill(fill). See [buf.fill()][] for more information.\n\n

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

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

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

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

\n

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

\n" }, { "textRaw": "Class Method: Buffer.allocUnsafe(size)", "type": "classMethod", "name": "allocUnsafe", "signatures": [ { "params": [ { "textRaw": "`size` {Number} ", "name": "size", "type": "Number" } ] }, { "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 require('buffer').kMaxLength (on 64-bit\narchitectures, kMaxLength is (2^31)-1). Otherwise, a [RangeError][] is\nthrown. If a size less than 0 is specified, a zero-length Buffer will be\ncreated.\n\n

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

\n
const buf = Buffer.allocUnsafe(5);\nconsole.log(buf);\n  // <Buffer 78 e0 82 02 01>\n  // (octets will be different, every time)\nbuf.fill(0);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>
\n

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

\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(size) (and the\nnew Buffer(size) constructor) only when size is less than or equal to\nBuffer.poolSize >> 1 (floor of Buffer.poolSize divided by two). The default\nvalue of Buffer.poolSize is 8192 but can be modified.\n\n

\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(size) provides.\n\n

\n" }, { "textRaw": "Class Method: Buffer.byteLength(string[, encoding])", "type": "classMethod", "name": "byteLength", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`string` {String | Buffer | TypedArray | DataView | ArrayBuffer} ", "name": "string", "type": "String | Buffer | TypedArray | DataView | ArrayBuffer" }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "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\n[String.prototype.length][] since that returns the number of characters in\na string.\n\n

\n

Example:\n\n

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

When string is a Buffer/[DataView][]/[TypedArray][]/ArrayBuffer,\nreturns the actual byte length.\n\n

\n

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

\n" }, { "textRaw": "Class Method: Buffer.compare(buf1, buf2)", "type": "classMethod", "name": "compare", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "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\nBuffers. This is equivalent is calling [buf1.compare(buf2)][].\n\n

\n
const arr = [Buffer.from('1234'), Buffer.from('0123')];\narr.sort(Buffer.compare);
\n" }, { "textRaw": "Class Method: Buffer.concat(list[, totalLength])", "type": "classMethod", "name": "concat", "signatures": [ { "return": { "textRaw": "Return: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`list` {Array} List of Buffer objects to concat ", "name": "list", "type": "Array", "desc": "List of Buffer objects to concat" }, { "textRaw": "`totalLength` {Number} Total length of the Buffers in the list when concatenated ", "name": "totalLength", "type": "Number", "desc": "Total length of the Buffers in the 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 Buffers in\nthe list together.\n\n

\n

If the list has no items, or if the totalLength is 0, then a new zero-length\nBuffer is returned.\n\n

\n

If totalLength is not provided, it is calculated from the Buffers in the\nlist. This, however, adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

\n

Example: build a single Buffer from a list of three Buffers:\n\n

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

Allocates a new Buffer using an array of octets.\n\n

\n
const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);\n  // creates a new Buffer containing ASCII bytes\n  // ['b','u','f','f','e','r']
\n

A TypeError will be thrown if array is not an Array.\n\n

\n" }, { "textRaw": "Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])", "type": "classMethod", "name": "from", "signatures": [ { "params": [ { "textRaw": "`arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` ", "name": "arrayBuffer", "type": "ArrayBuffer", "desc": "The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()`" }, { "textRaw": "`byteOffset` {Number} Default: `0` ", "name": "byteOffset", "type": "Number", "desc": "Default: `0`" }, { "textRaw": "`length` {Number} Default: `arrayBuffer.length - byteOffset` ", "name": "length", "type": "Number", "desc": "Default: `arrayBuffer.length - byteOffset`", "optional": true } ] }, { "params": [ { "name": "arrayBuffer" }, { "name": "byteOffset" }, { "name": "length", "optional": true } ] } ], "desc": "

When passed a reference to the .buffer property of a TypedArray instance,\nthe newly created Buffer will share the same allocated memory as the\nTypedArray.\n\n

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

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

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

A TypeError will be thrown if arrayBuffer is not an ArrayBuffer.\n\n

\n" }, { "textRaw": "Class Method: Buffer.from(buffer)", "type": "classMethod", "name": "from", "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer} ", "name": "buffer", "type": "Buffer" } ] }, { "params": [ { "name": "buffer" } ] } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.\n\n

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

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

\n" }, { "textRaw": "Class Method: Buffer.from(str[, encoding])", "type": "classMethod", "name": "from", "signatures": [ { "params": [ { "textRaw": "`str` {String} String to encode. ", "name": "str", "type": "String", "desc": "String to encode." }, { "textRaw": "`encoding` {String} Encoding to use, Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Encoding to use, Default: `'utf8'`", "optional": true } ] }, { "params": [ { "name": "str" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Creates a new Buffer containing the given JavaScript string str. If\nprovided, the encoding parameter identifies the character encoding.\nIf not provided, encoding defaults to 'utf8'.\n\n

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

A TypeError will be thrown if str is not a string.\n\n

\n" }, { "textRaw": "Class Method: Buffer.isBuffer(obj)", "type": "classMethod", "name": "isBuffer", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`obj` {Object} ", "name": "obj", "type": "Object" } ] }, { "params": [ { "name": "obj" } ] } ], "desc": "

Returns 'true' if obj is a Buffer.\n\n

\n" }, { "textRaw": "Class Method: Buffer.isEncoding(encoding)", "type": "classMethod", "name": "isEncoding", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`encoding` {String} The encoding string to test ", "name": "encoding", "type": "String", "desc": "The encoding string to test" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Returns true if the encoding is a valid encoding argument, or false\notherwise.\n\n

\n" } ], "properties": [ { "textRaw": "buf[index]", "name": "[index]", "desc": "

The index operator [index] can be used to get and set the octet at position\nindex in the Buffer. The values refer to individual bytes, so the legal value\nrange is between 0x00 and 0xFF (hex) or 0 and 255 (decimal).\n\n

\n

Example: copy an ASCII string into a Buffer, one byte at a time:\n\n

\n
const str = "Node.js";\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf.toString('ascii'));\n  // Prints: Node.js
\n" }, { "textRaw": "`length` {Number} ", "type": "Number", "name": "length", "desc": "

Returns the amount of memory allocated for the Buffer in number of bytes. Note\nthat this does not necessarily reflect the amount of usable data within the\nBuffer. For instance, in the example below, a Buffer with 1234 bytes is\nallocated, but only 11 ASCII bytes are written.\n\n

\n
const buf = Buffer.allocUnsafe(1234);\n\nconsole.log(buf.length);\n  // Prints: 1234\n\nbuf.write('some string', 0, 'ascii');\nconsole.log(buf.length);\n  // Prints: 1234
\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\n

\n
var buf = Buffer.allocUnsafe(10);\nbuf.write('abcdefghj', 0, 'ascii');\nconsole.log(buf.length);\n  // Prints: 10\nbuf = buf.slice(0,5);\nconsole.log(buf.length);\n  // Prints: 5
\n" } ], "methods": [ { "textRaw": "buf.compare(otherBuffer)", "type": "method", "name": "compare", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`otherBuffer` {Buffer} ", "name": "otherBuffer", "type": "Buffer" } ] }, { "params": [ { "name": "otherBuffer" } ] } ], "desc": "

Compares two Buffer instances and returns a number indicating whether buf\ncomes before, after, or is the same as the otherBuffer in sort order.\nComparison is based on the actual sequence of bytes in each Buffer.\n\n

\n\n
const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.compare(buf1));\n  // Prints: 0\nconsole.log(buf1.compare(buf2));\n  // Prints: -1\nconsole.log(buf1.compare(buf3));\n  // Prints: 1\nconsole.log(buf2.compare(buf1));\n  // Prints: 1\nconsole.log(buf2.compare(buf3));\n  // Prints: 1\n\n[buf1, buf2, buf3].sort(Buffer.compare);\n  // produces sort order [buf1, buf3, buf2]
\n" }, { "textRaw": "buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])", "type": "method", "name": "copy", "signatures": [ { "return": { "textRaw": "Return: {Number} The number of bytes copied. ", "name": "return", "type": "Number", "desc": "The number of bytes copied." }, "params": [ { "textRaw": "`targetBuffer` {Buffer} Buffer to copy into ", "name": "targetBuffer", "type": "Buffer", "desc": "Buffer to copy into" }, { "textRaw": "`targetStart` {Number} Default: 0 ", "name": "targetStart", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`sourceStart` {Number} Default: 0 ", "name": "sourceStart", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`sourceEnd` {Number} Default: `buffer.length` ", "name": "sourceEnd", "type": "Number", "desc": "Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "targetBuffer" }, { "name": "targetStart" }, { "name": "sourceStart" }, { "name": "sourceEnd", "optional": true } ] } ], "desc": "

Copies data from a region of this Buffer to a region in the target Buffer even\nif the target memory region overlaps with the source.\n\n

\n

Example: build two Buffers, then copy buf1 from byte 16 through byte 19\ninto buf2, starting at the 8th byte in buf2.\n\n

\n
const buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nbuf1.copy(buf2, 8, 16, 20);\nconsole.log(buf2.toString('ascii', 0, 25));\n  // Prints: !!!!!!!!qrst!!!!!!!!!!!!!
\n

Example: Build a single Buffer, then copy data from one region to an overlapping\nregion in the same Buffer\n\n

\n
const buf = Buffer.allocUnsafe(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf[i] = i + 97; // 97 is ASCII a\n}\n\nbuf.copy(buf, 0, 4, 10);\nconsole.log(buf.toString());\n\n// efghijghijklmnopqrstuvwxyz
\n" }, { "textRaw": "buf.entries()", "type": "method", "name": "entries", "signatures": [ { "return": { "textRaw": "Return: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Creates and returns an [iterator][] of [index, byte] pairs from the Buffer\ncontents.\n\n

\n
const buf = Buffer.from('buffer');\nfor (var pair of buf.entries()) {\n  console.log(pair);\n}\n// prints:\n//   [0, 98]\n//   [1, 117]\n//   [2, 102]\n//   [3, 102]\n//   [4, 101]\n//   [5, 114]
\n" }, { "textRaw": "buf.equals(otherBuffer)", "type": "method", "name": "equals", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`otherBuffer` {Buffer} ", "name": "otherBuffer", "type": "Buffer" } ] }, { "params": [ { "name": "otherBuffer" } ] } ], "desc": "

Returns a boolean indicating whether this and otherBuffer have exactly the\nsame bytes.\n\n

\n
const buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\nconsole.log(buf1.equals(buf2));\n  // Prints: true\nconsole.log(buf1.equals(buf3));\n  // Prints: false
\n" }, { "textRaw": "buf.fill(value[, offset[, end]][, encoding])", "type": "method", "name": "fill", "signatures": [ { "return": { "textRaw": "Return: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`value` {String|Buffer|Number} ", "name": "value", "type": "String|Buffer|Number" }, { "textRaw": "`offset` {Number} Default: 0 ", "name": "offset", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`end` {Number} Default: `buf.length` ", "name": "end", "type": "Number", "desc": "Default: `buf.length`", "optional": true }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "end", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Fills the Buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buf.length) are not given the entire buffer will be\nfilled. The method returns a reference to the Buffer, so calls can be chained.\nThis is meant as a small simplification to creating a Buffer. Allowing the\ncreation and fill of the Buffer to be done on a single line:\n\n

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

encoding is only relevant if value is a string. Otherwise it is ignored.\nvalue is coerced to a uint32 value if it is not a String or Number.\n\n

\n

The fill() operation writes bytes into the Buffer dumbly. If the final write\nfalls in between a multi-byte character then whatever bytes fit into the buffer\nare written.\n\n

\n
Buffer.alloc(3, '\\u0222');\n  // Prints: <Buffer c8 a2 c8>
\n" }, { "textRaw": "buf.indexOf(value[, byteOffset][, encoding])", "type": "method", "name": "indexOf", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`value` {String|Buffer|Number} ", "name": "value", "type": "String|Buffer|Number" }, { "textRaw": "`byteOffset` {Number} Default: 0 ", "name": "byteOffset", "type": "Number", "desc": "Default: 0", "optional": true }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Operates similar to [Array#indexOf()][] in that it returns either the\nstarting index position of value in Buffer or -1 if the Buffer does not\ncontain value. The value can be a String, Buffer or Number. Strings are by\ndefault interpreted as UTF8. Buffers will use the entire Buffer (to compare a\npartial Buffer use [buf.slice()][]). Numbers can range from 0 to 255.\n\n

\n
const buf = Buffer.from('this is a buffer');\n\nbuf.indexOf('this');\n  // returns 0\nbuf.indexOf('is');\n  // returns 2\nbuf.indexOf(Buffer.from('a buffer'));\n  // returns 8\nbuf.indexOf(97); // ascii for 'a'\n  // returns 8\nbuf.indexOf(Buffer.from('a buffer example'));\n  // returns -1\nbuf.indexOf(Buffer.from('a buffer example').slice(0,8));\n  // returns 8\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'ucs2');\n\nutf16Buffer.indexOf('\\u03a3',  0, 'ucs2');\n  // returns 4\nutf16Buffer.indexOf('\\u03a3', -4, 'ucs2');\n  // returns 6
\n" }, { "textRaw": "buf.includes(value[, byteOffset][, encoding])", "type": "method", "name": "includes", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`value` {String|Buffer|Number} ", "name": "value", "type": "String|Buffer|Number" }, { "textRaw": "`byteOffset` {Number} Default: 0 ", "name": "byteOffset", "type": "Number", "desc": "Default: 0", "optional": true }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "byteOffset", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Operates similar to [Array#includes()][]. The value can be a String, Buffer\nor Number. Strings are interpreted as UTF8 unless overridden with the\nencoding argument. Buffers will use the entire Buffer (to compare a partial\nBuffer use [buf.slice()][]). Numbers can range from 0 to 255.\n\n

\n

The byteOffset indicates the index in buf where searching begins.\n\n

\n
const buf = Buffer.from('this is a buffer');\n\nbuf.includes('this');\n  // returns true\nbuf.includes('is');\n  // returns true\nbuf.includes(Buffer.from('a buffer'));\n  // returns true\nbuf.includes(97); // ascii for 'a'\n  // returns true\nbuf.includes(Buffer.from('a buffer example'));\n  // returns false\nbuf.includes(Buffer.from('a buffer example').slice(0,8));\n  // returns true\nbuf.includes('this', 4);\n  // returns false
\n" }, { "textRaw": "buf.keys()", "type": "method", "name": "keys", "signatures": [ { "return": { "textRaw": "Return: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Creates and returns an [iterator][] of Buffer keys (indices).\n\n

\n
const buf = Buffer.from('buffer');\nfor (var key of buf.keys()) {\n  console.log(key);\n}\n// prints:\n//   0\n//   1\n//   2\n//   3\n//   4\n//   5
\n" }, { "textRaw": "buf.readDoubleBE(offset[, noAssert])", "type": "method", "name": "readDoubleBE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 8` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 8`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified\nendian format (readDoubleBE() returns big endian, readDoubleLE() returns\nlittle endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n
const buf = Buffer.from([1,2,3,4,5,6,7,8]);\n\nbuf.readDoubleBE();\n  // Returns: 8.20788039913184e-304\nbuf.readDoubleLE();\n  // Returns: 5.447603722011605e-270\nbuf.readDoubleLE(1);\n  // throws RangeError: Index out of range\n\nbuf.readDoubleLE(1, true); // Warning: reads passed end of buffer!\n  // Segmentation fault! don't do this!
\n" }, { "textRaw": "buf.readDoubleLE(offset[, noAssert])", "type": "method", "name": "readDoubleLE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 8` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 8`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n
const buf = Buffer.from([1,2,3,4,5,6,7,8]);\n\nbuf.readDoubleBE();\n  // Returns: 8.20788039913184e-304\nbuf.readDoubleLE();\n  // Returns: 5.447603722011605e-270\nbuf.readDoubleLE(1);\n  // throws RangeError: Index out of range\n\nbuf.readDoubleLE(1, true); // Warning: reads passed end of buffer!\n  // Segmentation fault! don't do this!
\n" }, { "textRaw": "buf.readFloatBE(offset[, noAssert])", "type": "method", "name": "readFloatBE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified\nendian format (readFloatBE() returns big endian, readFloatLE() returns\nlittle endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n
const buf = Buffer.from([1,2,3,4]);\n\nbuf.readFloatBE();\n  // Returns: 2.387939260590663e-38\nbuf.readFloatLE();\n  // Returns: 1.539989614439558e-36\nbuf.readFloatLE(1);\n  // throws RangeError: Index out of range\n\nbuf.readFloatLE(1, true); // Warning: reads passed end of buffer!\n  // Segmentation fault! don't do this!
\n" }, { "textRaw": "buf.readFloatLE(offset[, noAssert])", "type": "method", "name": "readFloatLE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n
const buf = Buffer.from([1,2,3,4]);\n\nbuf.readFloatBE();\n  // Returns: 2.387939260590663e-38\nbuf.readFloatLE();\n  // Returns: 1.539989614439558e-36\nbuf.readFloatLE(1);\n  // throws RangeError: Index out of range\n\nbuf.readFloatLE(1, true); // Warning: reads passed end of buffer!\n  // Segmentation fault! don't do this!
\n" }, { "textRaw": "buf.readInt8(offset[, noAssert])", "type": "method", "name": "readInt8", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 1` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 1`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 8-bit integer from the Buffer at the specified offset.\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Integers read from the Buffer are interpreted as two's complement signed values.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readInt8(0);\n  // returns 1\nbuf.readInt8(1);\n  // returns -2
\n" }, { "textRaw": "buf.readInt16BE(offset[, noAssert])", "type": "method", "name": "readInt16BE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with\nthe specified endian format (readInt16BE() returns big endian,\nreadInt16LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Integers read from the Buffer are interpreted as two's complement signed values.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readInt16BE();\n  // returns 510\nbuf.readInt16LE(1);\n  // returns 1022
\n" }, { "textRaw": "buf.readInt16LE(offset[, noAssert])", "type": "method", "name": "readInt16LE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Integers read from the Buffer are interpreted as two's complement signed values.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readInt16BE();\n  // returns 510\nbuf.readInt16LE(1);\n  // returns 1022
\n" }, { "textRaw": "buf.readInt32BE(offset[, noAssert])", "type": "method", "name": "readInt32BE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with\nthe specified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Integers read from the Buffer are interpreted as two's complement signed values.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readInt32BE();\n  // returns 33424132\nbuf.readInt32LE();\n  // returns 67370497\nbuf.readInt32LE(1);\n  // throws RangeError: Index out of range
\n" }, { "textRaw": "buf.readInt32LE(offset[, noAssert])", "type": "method", "name": "readInt32LE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Integers read from the Buffer are interpreted as two's complement signed values.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readInt32BE();\n  // returns 33424132\nbuf.readInt32LE();\n  // returns 67370497\nbuf.readInt32LE(1);\n  // throws RangeError: Index out of range
\n" }, { "textRaw": "buf.readIntBE(offset, byteLength[, noAssert])", "type": "method", "name": "readIntBE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset\nand interprets the result as a two's complement signed value. Supports up to 48\nbits of accuracy. For example:\n\n

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUInt16LE(0x90ab, 0);\nbuf.writeUInt32LE(0x12345678, 2);\nbuf.readIntLE(0, 6).toString(16);  // Specify 6 bytes (48 bits)\n// Returns: '1234567890ab'\n\nbuf.readIntBE(0, 6).toString(16);\n// Returns: -546f87a9cbee
\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n" }, { "textRaw": "buf.readIntLE(offset, byteLength[, noAssert])", "type": "method", "name": "readIntLE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUInt16LE(0x90ab, 0);\nbuf.writeUInt32LE(0x12345678, 2);\nbuf.readIntLE(0, 6).toString(16);  // Specify 6 bytes (48 bits)\n// Returns: '1234567890ab'\n\nbuf.readIntBE(0, 6).toString(16);\n// Returns: -546f87a9cbee
\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n" }, { "textRaw": "buf.readUInt8(offset[, noAssert])", "type": "method", "name": "readUInt8", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 1` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 1`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 8-bit integer from the Buffer at the specified offset.\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n
const buf = Buffer.from([1,-2,3,4]);\n\nbuf.readUInt8(0);\n  // returns 1\nbuf.readUInt8(1);\n  // returns 254
\n" }, { "textRaw": "buf.readUInt16BE(offset[, noAssert])", "type": "method", "name": "readUInt16BE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with\nspecified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Example:\n\n

\n
const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);\n\nbuf.readUInt16BE(0);\n  // Returns: 0x0304\nbuf.readUInt16LE(0);\n  // Returns: 0x0403\nbuf.readUInt16BE(1);\n  // Returns: 0x0423\nbuf.readUInt16LE(1);\n  // Returns: 0x2304\nbuf.readUInt16BE(2);\n  // Returns: 0x2342\nbuf.readUInt16LE(2);\n  // Returns: 0x4223
\n" }, { "textRaw": "buf.readUInt16LE(offset[, noAssert])", "type": "method", "name": "readUInt16LE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 16-bit integer from the Buffer at the specified offset with\nspecified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Example:\n\n

\n
const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);\n\nbuf.readUInt16BE(0);\n  // Returns: 0x0304\nbuf.readUInt16LE(0);\n  // Returns: 0x0403\nbuf.readUInt16BE(1);\n  // Returns: 0x0423\nbuf.readUInt16LE(1);\n  // Returns: 0x2304\nbuf.readUInt16BE(2);\n  // Returns: 0x2342\nbuf.readUInt16LE(2);\n  // Returns: 0x4223
\n" }, { "textRaw": "buf.readUInt32BE(offset[, noAssert])", "type": "method", "name": "readUInt32BE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with\nspecified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Example:\n\n

\n
const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);\n\nbuf.readUInt32BE(0);\n  // Returns: 0x03042342\nconsole.log(buf.readUInt32LE(0));\n  // Returns: 0x42230403
\n" }, { "textRaw": "buf.readUInt32LE(offset[, noAssert])", "type": "method", "name": "readUInt32LE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 32-bit integer from the Buffer at the specified offset with\nspecified endian format (readInt32BE() returns big endian,\nreadInt32LE() returns little endian).\n\n

\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n

Example:\n\n

\n
const buf = Buffer.from([0x3, 0x4, 0x23, 0x42]);\n\nbuf.readUInt32BE(0);\n  // Returns: 0x03042342\nconsole.log(buf.readUInt32LE(0));\n  // Returns: 0x42230403
\n" }, { "textRaw": "buf.readUIntBE(offset, byteLength[, noAssert])", "type": "method", "name": "readUIntBE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset\nand interprets the result as an unsigned integer. Supports up to 48\nbits of accuracy. For example:\n\n

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUInt16LE(0x90ab, 0);\nbuf.writeUInt32LE(0x12345678, 2);\nbuf.readUIntLE(0, 6).toString(16);  // Specify 6 bytes (48 bits)\n// Returns: '1234567890ab'\n\nbuf.readUIntBE(0, 6).toString(16);\n// Returns: ab9078563412
\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n" }, { "textRaw": "buf.readUIntLE(offset, byteLength[, noAssert])", "type": "method", "name": "readUIntLE", "signatures": [ { "return": { "textRaw": "Return: {Number} ", "name": "return", "type": "Number" }, "params": [ { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUInt16LE(0x90ab, 0);\nbuf.writeUInt32LE(0x12345678, 2);\nbuf.readUIntLE(0, 6).toString(16);  // Specify 6 bytes (48 bits)\n// Returns: '1234567890ab'\n\nbuf.readUIntBE(0, 6).toString(16);\n// Returns: ab9078563412
\n

Setting noAssert to true skips validation of the offset. This allows the\noffset to be beyond the end of the Buffer.\n\n

\n" }, { "textRaw": "buf.slice([start[, end]])", "type": "method", "name": "slice", "signatures": [ { "return": { "textRaw": "Return: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`start` {Number} Default: 0 ", "name": "start", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`end` {Number} Default: `buffer.length` ", "name": "end", "type": "Number", "desc": "Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "start" }, { "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\n

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

\n

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n

\n
const buf1 = Buffer.allocUnsafe(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nconst buf2 = buf1.slice(0, 3);\nbuf2.toString('ascii', 0, buf2.length);\n  // Returns: 'abc'\nbuf1[0] = 33;\nbuf2.toString('ascii', 0, buf2.length);\n  // Returns : '!bc'
\n

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

\n
const buf = Buffer.from('buffer');\n\nbuf.slice(-6, -1).toString();\n  // Returns 'buffe', equivalent to buf.slice(0, 5)\nbuf.slice(-6, -2).toString();\n  // Returns 'buff', equivalent to buf.slice(0, 4)\nbuf.slice(-5, -2).toString();\n  // Returns 'uff', equivalent to buf.slice(1, 4)
\n" }, { "textRaw": "buf.swap16()", "type": "method", "name": "swap16", "signatures": [ { "return": { "textRaw": "Return: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [] }, { "params": [] } ], "desc": "

Interprets the Buffer as an array of unsigned 16-bit integers and swaps\nthe byte-order in-place. Throws a RangeError if the Buffer length is\nnot a multiple of 16 bits. The method returns a reference to the Buffer, so\ncalls can be chained.\n\n

\n
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\nconsole.log(buf);\n  // Prints Buffer(0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8)\nbuf.swap16();\nconsole.log(buf);\n  // Prints Buffer(0x2, 0x1, 0x4, 0x3, 0x6, 0x5, 0x8, 0x7)
\n" }, { "textRaw": "buf.swap32()", "type": "method", "name": "swap32", "signatures": [ { "return": { "textRaw": "Return: {Buffer} ", "name": "return", "type": "Buffer" }, "params": [] }, { "params": [] } ], "desc": "

Interprets the Buffer as an array of unsigned 32-bit integers and swaps\nthe byte-order in-place. Throws a RangeError if the Buffer length is\nnot a multiple of 32 bits. The method returns a reference to the Buffer, so\ncalls can be chained.\n\n

\n
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\nconsole.log(buf);\n  // Prints Buffer(0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8)\nbuf.swap32();\nconsole.log(buf);\n  // Prints Buffer(0x4, 0x3, 0x2, 0x1, 0x8, 0x7, 0x6, 0x5)
\n" }, { "textRaw": "buf.toString([encoding[, start[, end]]])", "type": "method", "name": "toString", "signatures": [ { "return": { "textRaw": "Return: {String} ", "name": "return", "type": "String" }, "params": [ { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`" }, { "textRaw": "`start` {Number} Default: 0 ", "name": "start", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`end` {Number} Default: `buffer.length` ", "name": "end", "type": "Number", "desc": "Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "encoding" }, { "name": "start" }, { "name": "end", "optional": true } ] } ], "desc": "

Decodes and returns a string from the Buffer data using the specified\ncharacter set encoding.\n\n

\n
const buf = Buffer.allocUnsafe(26);\nfor (var i = 0 ; i < 26 ; i++) {\n  buf[i] = i + 97; // 97 is ASCII a\n}\nbuf.toString('ascii');\n  // Returns: 'abcdefghijklmnopqrstuvwxyz'\nbuf.toString('ascii',0,5);\n  // Returns: 'abcde'\nbuf.toString('utf8',0,5);\n  // Returns: 'abcde'\nbuf.toString(undefined,0,5);\n  // Returns: 'abcde', encoding defaults to 'utf8'
\n" }, { "textRaw": "buf.toJSON()", "type": "method", "name": "toJSON", "signatures": [ { "return": { "textRaw": "Return: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "

Returns a JSON representation of the Buffer instance. [JSON.stringify()][]\nimplicitly calls this function when stringifying a Buffer instance.\n\n

\n

Example:\n\n

\n
const buf = Buffer.from('test');\nconst json = JSON.stringify(buf);\n\nconsole.log(json);\n// Prints: '{"type":"Buffer","data":[116,101,115,116]}'\n\nconst copy = JSON.parse(json, (key, value) => {\n    return value && value.type === 'Buffer'\n      ? Buffer.from(value.data)\n      : value;\n  });\n\nconsole.log(copy.toString());\n// Prints: 'test'
\n" }, { "textRaw": "buf.values()", "type": "method", "name": "values", "signatures": [ { "return": { "textRaw": "Return: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "

Creates and returns an [iterator][] for Buffer values (bytes). This function is\ncalled automatically when the Buffer is used in a for..of statement.\n\n

\n
const buf = Buffer.from('buffer');\nfor (var value of buf.values()) {\n  console.log(value);\n}\n// prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114\n\nfor (var value of buf) {\n  console.log(value);\n}\n// prints:\n//   98\n//   117\n//   102\n//   102\n//   101\n//   114
\n" }, { "textRaw": "buf.write(string[, offset[, length]][, encoding])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Return: {Number} Numbers of bytes written ", "name": "return", "type": "Number", "desc": "Numbers of bytes written" }, "params": [ { "textRaw": "`string` {String} Bytes to be written to buffer ", "name": "string", "type": "String", "desc": "Bytes to be written to buffer" }, { "textRaw": "`offset` {Number} Default: 0 ", "name": "offset", "type": "Number", "desc": "Default: 0" }, { "textRaw": "`length` {Number} Default: `buffer.length - offset` ", "name": "length", "type": "Number", "desc": "Default: `buffer.length - offset`", "optional": true }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "offset" }, { "name": "length", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Writes string to the Buffer at offset using the given encoding.\nThe length parameter is the number of bytes to write. If the Buffer did not\ncontain enough space to fit the entire string, only a partial amount of the\nstring will be written however, it will not write only partially encoded\ncharacters.\n\n

\n
const buf = Buffer.allocUnsafe(256);\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n  // Prints: 12 bytes: ½ + ¼ = ¾
\n" }, { "textRaw": "buf.writeDoubleBE(value, offset[, noAssert])", "type": "method", "name": "writeDoubleBE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 8` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 8`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeDoubleBE() writes big endian, writeDoubleLE() writes little\nendian). The value argument should be a valid 64-bit double. Behavior is\nnot defined when value is anything other than a 64-bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" }, { "textRaw": "buf.writeDoubleLE(value, offset[, noAssert])", "type": "method", "name": "writeDoubleLE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 8` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 8`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset with specified endian\nformat (writeDoubleBE() writes big endian, writeDoubleLE() writes little\nendian). The value argument should be a valid 64-bit double. Behavior is\nnot defined when value is anything other than a 64-bit double.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" }, { "textRaw": "buf.writeFloatBE(value, offset[, noAssert])", "type": "method", "name": "writeFloatBE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeFloatBE() writes big endian, writeFloatLE() writes little\nendian). Behavior is not defined when value is anything other than a 32-bit\nfloat.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer 4f 4a fe bb>\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer bb fe 4a 4f>
\n" }, { "textRaw": "buf.writeFloatLE(value, offset[, noAssert])", "type": "method", "name": "writeFloatLE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset with specified endian\nformat (writeFloatBE() writes big endian, writeFloatLE() writes little\nendian). Behavior is not defined when value is anything other than a 32-bit\nfloat.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer 4f 4a fe bb>\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer bb fe 4a 4f>
\n" }, { "textRaw": "buf.writeInt8(value, offset[, noAssert])", "type": "method", "name": "writeInt8", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 1` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 1`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset. The value should be a\nvalid signed 8-bit integer. Behavior is not defined when value is anything\nother than a signed 8-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

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

\n
const buf = Buffer.allocUnsafe(2);\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\nconsole.log(buf);\n  // Prints: <Buffer 02 fe>
\n" }, { "textRaw": "buf.writeInt16BE(value, offset[, noAssert])", "type": "method", "name": "writeInt16BE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeInt16BE() writes big endian, writeInt16LE() writes little\nendian). The value should be a valid signed 16-bit integer. Behavior is\nnot defined when value is anything other than a signed 16-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

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

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeInt16BE(0x0102,0);\nbuf.writeInt16LE(0x0304,2);\nconsole.log(buf);\n  // Prints: <Buffer 01 02 04 03>
\n" }, { "textRaw": "buf.writeInt16LE(value, offset[, noAssert])", "type": "method", "name": "writeInt16LE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset with specified endian\nformat (writeInt16BE() writes big endian, writeInt16LE() writes little\nendian). The value should be a valid signed 16-bit integer. Behavior is\nnot defined when value is anything other than a signed 16-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

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

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeInt16BE(0x0102,0);\nbuf.writeInt16LE(0x0304,2);\nconsole.log(buf);\n  // Prints: <Buffer 01 02 04 03>
\n" }, { "textRaw": "buf.writeInt32BE(value, offset[, noAssert])", "type": "method", "name": "writeInt32BE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeInt32BE() writes big endian, writeInt32LE() writes little\nendian). The value should be a valid signed 32-bit integer. Behavior is\nnot defined when value is anything other than a signed 32-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

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

\n
const buf = Buffer.allocUnsafe(8);\nbuf.writeInt32BE(0x01020304,0);\nbuf.writeInt32LE(0x05060708,4);\nconsole.log(buf);\n  // Prints: <Buffer 01 02 03 04 08 07 06 05>
\n" }, { "textRaw": "buf.writeInt32LE(value, offset[, noAssert])", "type": "method", "name": "writeInt32LE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset with specified endian\nformat (writeInt32BE() writes big endian, writeInt32LE() writes little\nendian). The value should be a valid signed 32-bit integer. Behavior is\nnot defined when value is anything other than a signed 32-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

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

\n
const buf = Buffer.allocUnsafe(8);\nbuf.writeInt32BE(0x01020304,0);\nbuf.writeInt32LE(0x05060708,4);\nconsole.log(buf);\n  // Prints: <Buffer 01 02 03 04 08 07 06 05>
\n" }, { "textRaw": "buf.writeIntBE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeIntBE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 value to the Buffer at the specified offset and byteLength.\nSupports up to 48 bits of accuracy. For example:\n\n

\n
const buf1 = Buffer.allocUnsafe(6);\nbuf1.writeUIntBE(0x1234567890ab, 0, 6);\nconsole.log(buf1);\n  // Prints: <Buffer 12 34 56 78 90 ab>\n\nconst buf2 = Buffer.allocUnsafe(6);\nbuf2.writeUIntLE(0x1234567890ab, 0, 6);\nconsole.log(buf2);\n  // Prints: <Buffer ab 90 78 56 34 12>
\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Behavior is not defined when value is anything other than an integer.\n\n

\n" }, { "textRaw": "buf.writeIntLE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeIntLE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset and byteLength.\nSupports up to 48 bits of accuracy. For example:\n\n

\n
const buf1 = Buffer.allocUnsafe(6);\nbuf1.writeUIntBE(0x1234567890ab, 0, 6);\nconsole.log(buf1);\n  // Prints: <Buffer 12 34 56 78 90 ab>\n\nconst buf2 = Buffer.allocUnsafe(6);\nbuf2.writeUIntLE(0x1234567890ab, 0, 6);\nconsole.log(buf2);\n  // Prints: <Buffer ab 90 78 56 34 12>
\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Behavior is not defined when value is anything other than an integer.\n\n

\n" }, { "textRaw": "buf.writeUInt8(value, offset[, noAssert])", "type": "method", "name": "writeUInt8", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 1` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 1`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset. The value should be a\nvalid unsigned 8-bit integer. Behavior is not defined when value is anything\nother than an unsigned 8-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n  // Prints: <Buffer 03 04 23 42>
\n" }, { "textRaw": "buf.writeUInt16BE(value, offset[, noAssert])", "type": "method", "name": "writeUInt16BE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeUInt16BE() writes big endian, writeUInt16LE() writes little\nendian). The value should be a valid unsigned 16-bit integer. Behavior is\nnot defined when value is anything other than an unsigned 16-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n  // Prints: <Buffer de ad be ef>\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n  // Prints: <Buffer ad de ef be>
\n" }, { "textRaw": "buf.writeUInt16LE(value, offset[, noAssert])", "type": "method", "name": "writeUInt16LE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 2` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 2`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n  // Prints: <Buffer de ad be ef>\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n  // Prints: <Buffer ad de ef be>
\n" }, { "textRaw": "buf.writeUInt32BE(value, offset[, noAssert])", "type": "method", "name": "writeUInt32BE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 the Buffer at the specified offset with specified endian\nformat (writeUInt32BE() writes big endian, writeUInt32LE() writes little\nendian). The value should be a valid unsigned 32-bit integer. Behavior is\nnot defined when value is anything other than an unsigned 32-bit integer.\n\n

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer fe ed fa ce>\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer ce fa ed fe>
\n" }, { "textRaw": "buf.writeUInt32LE(value, offset[, noAssert])", "type": "method", "name": "writeUInt32LE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - 4` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - 4`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Example:\n\n

\n
const buf = Buffer.allocUnsafe(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer fe ed fa ce>\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n  // Prints: <Buffer ce fa ed fe>
\n" }, { "textRaw": "buf.writeUIntBE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeUIntBE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "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 value to the Buffer at the specified offset and byteLength.\nSupports up to 48 bits of accuracy. For example:\n\n

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\nconsole.log(buf);\n  // Prints: <Buffer 12 34 56 78 90 ab>
\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Behavior is not defined when value is anything other than an unsigned integer.\n\n

\n" }, { "textRaw": "buf.writeUIntLE(value, offset, byteLength[, noAssert])", "type": "method", "name": "writeUIntLE", "signatures": [ { "return": { "textRaw": "Return: {Number} The offset plus the number of written bytes ", "name": "return", "type": "Number", "desc": "The offset plus the number of written bytes" }, "params": [ { "textRaw": "`value` {Number} Bytes to be written to Buffer ", "name": "value", "type": "Number", "desc": "Bytes to be written to Buffer" }, { "textRaw": "`offset` {Number} `0 <= offset <= buf.length - byteLength` ", "name": "offset", "type": "Number", "desc": "`0 <= offset <= buf.length - byteLength`" }, { "textRaw": "`byteLength` {Number} `0 < byteLength <= 6` ", "name": "byteLength", "type": "Number", "desc": "`0 < byteLength <= 6`" }, { "textRaw": "`noAssert` {Boolean} Default: false ", "name": "noAssert", "type": "Boolean", "desc": "Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "byteLength" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the Buffer at the specified offset and byteLength.\nSupports up to 48 bits of accuracy. For example:\n\n

\n
const buf = Buffer.allocUnsafe(6);\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\nconsole.log(buf);\n  // Prints: <Buffer 12 34 56 78 90 ab>
\n

Set noAssert to true to skip validation of value and offset. This means\nthat value may be too large for the specific function and offset may be\nbeyond the end of the Buffer leading to the values being silently dropped. This\nshould not be used unless you are certain of correctness.\n\n

\n

Behavior is not defined when value is anything other than an unsigned integer.\n\n

\n" } ], "signatures": [ { "params": [ { "textRaw": "`array` {Array} ", "name": "array", "type": "Array" } ], "desc": "

Allocates a new Buffer using an array of octets.\n\n

\n
const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);\n  // creates a new Buffer containing ASCII bytes\n  // ['b','u','f','f','e','r']
\n" }, { "params": [ { "name": "array" } ], "desc": "

Allocates a new Buffer using an array of octets.\n\n

\n
const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);\n  // creates a new Buffer containing ASCII bytes\n  // ['b','u','f','f','e','r']
\n" }, { "params": [ { "textRaw": "`buffer` {Buffer} ", "name": "buffer", "type": "Buffer" } ], "desc": "

Copies the passed buffer data onto a new Buffer instance.\n\n

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

Copies the passed buffer data onto a new Buffer instance.\n\n

\n
const buf1 = new Buffer('buffer');\nconst buf2 = new Buffer(buf1);\n\nbuf1[0] = 0x61;\nconsole.log(buf1.toString());\n  // 'auffer'\nconsole.log(buf2.toString());\n  // 'buffer' (copy is not changed)
\n" }, { "params": [ { "textRaw": "`arrayBuffer` - The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` ", "name": "arrayBuffer", "desc": "The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()`" }, { "textRaw": "`byteOffset` {Number} Default: `0` ", "name": "byteOffset", "type": "Number", "desc": "Default: `0`" }, { "textRaw": "`length` {Number} Default: `arrayBuffer.length - byteOffset` ", "name": "length", "type": "Number", "desc": "Default: `arrayBuffer.length - byteOffset`", "optional": true } ], "desc": "

When passed a reference to the .buffer property of a TypedArray instance,\nthe newly created Buffer will share the same allocated memory as the\nTypedArray.\n\n

\n

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

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

When passed a reference to the .buffer property of a TypedArray instance,\nthe newly created Buffer will share the same allocated memory as the\nTypedArray.\n\n

\n

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

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

Allocates a new Buffer of size bytes. The size must be less than\nor equal to the value of require('buffer').kMaxLength (on 64-bit\narchitectures, kMaxLength is (2^31)-1). Otherwise, a [RangeError][] is\nthrown. If a size less than 0 is specified, a zero-length Buffer will be\ncreated.\n\n

\n

Unlike ArrayBuffers, the underlying memory for Buffer instances created in\nthis way is not initialized. The contents of a newly created Buffer are\nunknown and could contain sensitive data. Use [buf.fill(0)][] to initialize\na Buffer to zeroes.\n\n

\n
const buf = new Buffer(5);\nconsole.log(buf);\n  // <Buffer 78 e0 82 02 01>\n  // (octets will be different, every time)\nbuf.fill(0);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>
\n" }, { "params": [ { "name": "size" } ], "desc": "

Allocates a new Buffer of size bytes. The size must be less than\nor equal to the value of require('buffer').kMaxLength (on 64-bit\narchitectures, kMaxLength is (2^31)-1). Otherwise, a [RangeError][] is\nthrown. If a size less than 0 is specified, a zero-length Buffer will be\ncreated.\n\n

\n

Unlike ArrayBuffers, the underlying memory for Buffer instances created in\nthis way is not initialized. The contents of a newly created Buffer are\nunknown and could contain sensitive data. Use [buf.fill(0)][] to initialize\na Buffer to zeroes.\n\n

\n
const buf = new Buffer(5);\nconsole.log(buf);\n  // <Buffer 78 e0 82 02 01>\n  // (octets will be different, every time)\nbuf.fill(0);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>
\n" }, { "params": [ { "textRaw": "`str` {String} String to encode. ", "name": "str", "type": "String", "desc": "String to encode." }, { "textRaw": "`encoding` {String} Default: `'utf8'` ", "name": "encoding", "type": "String", "desc": "Default: `'utf8'`", "optional": true } ], "desc": "

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

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

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

\n
const buf1 = new Buffer('this is a tést');\nconsole.log(buf1.toString());\n  // prints: this is a tést\nconsole.log(buf1.toString('ascii'));\n  // prints: this is a tC)st\n\nconst buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');\nconsole.log(buf2.toString());\n  // prints: this is a tést
\n" } ] }, { "textRaw": "Class: SlowBuffer", "type": "class", "name": "SlowBuffer", "desc": "

Returns an un-pooled Buffer.\n\n

\n

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

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

\n
// need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n  var data = socket.read();\n  // allocate for retained data\n  var sb = SlowBuffer(10);\n  // copy the data into the new allocation\n  data.copy(sb, 0, 0, 10);\n  store.push(sb);\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\n

\n", "signatures": [ { "params": [ { "textRaw": "`size` Number ", "name": "size", "desc": "Number" } ], "desc": "

Allocates a new SlowBuffer of size bytes. The size must be less than\nor equal to the value of require('buffer').kMaxLength (on 64-bit\narchitectures, kMaxLength is (2^31)-1). Otherwise, a [RangeError][] is\nthrown. If a size less than 0 is specified, a zero-length SlowBuffer will be\ncreated.\n\n

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

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

Allocates a new SlowBuffer of size bytes. The size must be less than\nor equal to the value of require('buffer').kMaxLength (on 64-bit\narchitectures, kMaxLength is (2^31)-1). Otherwise, a [RangeError][] is\nthrown. If a size less than 0 is specified, a zero-length SlowBuffer will be\ncreated.\n\n

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

\n
const SlowBuffer = require('buffer').SlowBuffer;\nconst buf = new SlowBuffer(5);\nconsole.log(buf);\n  // <Buffer 78 e0 82 02 01>\n  // (octets will be different, every time)\nbuf.fill(0);\nconsole.log(buf);\n  // <Buffer 00 00 00 00 00>
\n" } ] } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` {Number} Default: 50 ", "type": "Number", "name": "INSPECT_MAX_BYTES", "desc": "

Returns the maximum number of bytes that will be returned when\nbuffer.inspect() is called. This can be overridden by user modules. See\n[util.inspect()][] for more details on buffer.inspect() behavior.\n\n

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

\n", "shortDesc": "Default: 50" } ], "type": "module", "displayName": "Buffer" }, { "textRaw": "Child Process", "name": "child_process", "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\n

\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

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

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

\n

For convenience, the child_process module provides a handful of synchronous\nand asynchronous alternatives to [child_process.spawn()][] and\n[child_process.spawnSync()][]. Note that each of these alternatives are\nimplemented on top of child_process.spawn() or child_process.spawnSync().\n\n

\n\n

For certain use cases, such as automating shell scripts, the\n[synchronous 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\n

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

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

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

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

\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);\n});\n\nbat.stderr.on('data', (data) => {\n  console.log(data);\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", "type": "module", "displayName": "Spawning `.bat` and `.cmd` files on Windows" } ], "methods": [ { "textRaw": "child_process.exec(command[, options][, callback])", "type": "method", "name": "exec", "signatures": [ { "return": { "textRaw": "Return: {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", "default": "utf8", "type": "String" }, { "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", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: `200*1024`) ", "name": "maxBuffer", "default": "200*1024", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" }, { "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\n

\n
const exec = require('child_process').exec;\nconst child = exec('cat *.js bad_file | wc -l',\n  (error, stdout, stderr) => {\n    console.log(`stdout: ${stdout}`);\n    console.log(`stderr: ${stderr}`);\n    if (error !== null) {\n      console.log(`exec error: ${error}`);\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\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', Buffer objects will be passed to\nthe callback instead.\n\n

\n

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

\n
{\n  encoding: 'utf8',\n  timeout: 0,\n  maxBuffer: 200*1024,\n  killSignal: 'SIGTERM',\n  cwd: null,\n  env: null\n}
\n

If timeout is greater than 0, the parent will send the the signal\nidentified by the killSignal property (the default is 'SIGTERM') if the\nchild runs longer than timeout milliseconds.\n\n

\n

The maxBuffer option specifies the largest amount of data (in bytes) allowed\non stdout or stderr - if this value is exceeded then the child process is\nterminated.\n\n

\n

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

\n" }, { "textRaw": "child_process.execFile(file[, args][, options][, callback])", "type": "method", "name": "execFile", "signatures": [ { "return": { "textRaw": "Return: {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` {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": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed (Default: 200\\*1024) ", "name": "maxBuffer", "default": "200\\*1024", "type": "Number", "desc": "largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" }, { "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\n[child_process.exec()][].\n\n

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

\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

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', Buffer objects will be passed to\nthe callback instead.\n\n

\n" }, { "textRaw": "child_process.fork(modulePath[, args][, options])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "Return: {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", "default": "process.execArgv", "type": "Array", "desc": "List of string arguments passed to the executable" }, { "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 is 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 is false)" }, { "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\n[child_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\n[ChildProcess#send()][] for details.\n\n

\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 it's 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\n

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

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

\n

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

\n" }, { "textRaw": "child_process.spawn(command[, args][, options])", "type": "method", "name": "spawn", "signatures": [ { "return": { "textRaw": "return: {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": "`stdio` {Array|String} Child's stdio configuration. (See [`options.stdio`][]) ", "name": "stdio", "type": "Array|String", "desc": "Child's stdio configuration. (See [`options.stdio`][])" }, { "textRaw": "`detached` {Boolean} Prepare child 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. Defaults 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. Defaults 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.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\n

\n

A third argument may be used to specify additional options, with these defaults:\n\n

\n
{\n  cwd: undefined,\n  env: process.env\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\n

\n

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

\n

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

\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

Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

\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}`);\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

Example of checking for failed exec:\n\n

\n
const spawn = require('child_process').spawn;\nconst child = spawn('bad_command');\n\nchild.on('error', (err) => {\n  console.log('Failed to start child process.');\n});
\n", "properties": [ { "textRaw": "options.detached", "name": "detached", "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\n

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

\n

By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method.\nDoing so will cause the parent's event loop to not include the child in its\nreference count, allowing the parent to exit independently of the child, unless\nthere is an established IPC channel between the child and parent.\n\n

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

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

\n
const spawn = require('child_process').spawn;\n\nconst child = spawn(process.argv[0], ['child_program.js'], {\n  detached: true,\n  stdio: ['ignore']\n});\n\nchild.unref();
\n

Alternatively one can redirect the child process' output into files:\n\n

\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 child = spawn('prg', [], {\n detached: true,\n stdio: [ 'ignore', out, err ]\n});\n\nchild.unref();
\n" }, { "textRaw": "options.stdio", "name": "stdio", "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 child.stdin, child.stdout, and\nchild.stderr streams on the ChildProcess object. This is equivalent to\nsetting the options.stdio equal to ['pipe', 'pipe', 'pipe'].\n\n

\n

For convenience, options.stdio may be one of the following strings:\n\n

\n\n

Otherwise, the value of option.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

\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 ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.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 ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, the\nChildProcess.on('message') event handler will be triggered in the parent.\nIf the child is a Node.js process, the presence of an IPC channel will enable\nprocess.send(), process.disconnect(), process.on('disconnect'), and\nprocess.on('message') within the child.
  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\n

\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

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('disconnected') event.\nThis allows the child to exit normally without the process being held open\nby the open IPC channel.\n\n

\n

See also: [child_process.exec()][] and [child_process.fork()][]\n\n

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

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

\n", "methods": [ { "textRaw": "child_process.execFileSync(file[, args][, options])", "type": "method", "name": "execFileSync", "signatures": [ { "return": { "textRaw": "return: {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` {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` {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", "default": "pipe", "type": "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "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", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." } ], "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\n

\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\n[child_process.spawnSync()][]\n\n

\n" }, { "textRaw": "child_process.execSync(command[, options])", "type": "method", "name": "execSync", "signatures": [ { "return": { "textRaw": "return: {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` {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", "default": "pipe", "type": "Array", "desc": "Child's stdio configuration." }, { "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "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", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." } ], "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\n

\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\n[child_process.spawnSync()][]\n\n

\n" }, { "textRaw": "child_process.spawnSync(command[, args][, options])", "type": "method", "name": "spawnSync", "signatures": [ { "return": { "textRaw": "return: {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` {Array} Child's stdio configuration. ", "name": "stdio", "type": "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", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String} The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String", "desc": "The signal value to be used when the spawned process will be killed." }, { "textRaw": "`maxBuffer` {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed ", "name": "maxBuffer", "type": "Number", "desc": "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", "default": "buffer", "type": "String", "desc": "The encoding used for all stdio inputs and outputs." }, { "textRaw": "`shell` {Boolean|String} If `true`, runs `command` inside of a shell. Uses '/bin/sh' on UNIX, and '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. Defaults 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. Defaults 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\n

\n" } ], "type": "module", "displayName": "Synchronous Process Creation" } ], "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "desc": "

Instances of the ChildProcess class are [EventEmitters][] that represent\nspawned child processes.\n\n

\n

Instances of ChildProcess are not intended to be created directly. Rather,\nuse the [child_process.spawn()][], [child_process.exec()][],\n[child_process.execFile()][], or [child_process.fork()][] methods to create\ninstances of ChildProcess.\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "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\n

\n" }, { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

The 'disconnect' event is emitted after calling the\nChildProcess.disconnect() method in the parent or child process. After\ndisconnecting it is no longer possible to send or receive messages, and the\nChildProcess.connected property is false.\n\n

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

The 'error' event is emitted whenever:\n\n

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

\n

See also [ChildProcess#kill()][] and [ChildProcess#send()][].\n\n

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

\n

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

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

\n

See waitpid(2).\n\n

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

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

\n" } ], "properties": [ { "textRaw": "`connected` {Boolean} Set to false after `.disconnect` is called ", "type": "Boolean", "name": "connected", "desc": "

The child.connected property indicates whether it is still possible to send\nand receive messages from a child process. When child.connected is false, it\nis no longer possible to send or receive messages.\n\n

\n", "shortDesc": "Set to false after `.disconnect` is called" }, { "textRaw": "`pid` {Number} Integer ", "type": "Number", "name": "pid", "desc": "

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

\n

Example:\n\n

\n
const spawn = require('child_process').spawn;\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();
\n", "shortDesc": "Integer" }, { "textRaw": "`stderr` {Stream} ", "type": "Stream", "name": "stderr", "desc": "

A Readable Stream that represents the child process's stderr.\n\n

\n

If the child was spawned with stdio[2] set to anything other than 'pipe',\nthen this will be undefined.\n\n

\n

child.stderr is an alias for child.stdio[2]. Both properties will refer to\nthe same value.\n\n

\n" }, { "textRaw": "`stdin` {Stream} ", "type": "Stream", "name": "stdin", "desc": "

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

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

\n

If the child was spawned with stdio[0] set to anything other than 'pipe',\nthen this will be undefined.\n\n

\n

child.stdin is an alias for child.stdio[0]. Both properties will refer to\nthe same value.\n\n

\n" }, { "textRaw": "`stdio` {Array} ", "type": "Array", "name": "stdio", "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 child.stdio[0], child.stdio[1], and\nchild.stdio[2] are also available as child.stdin, child.stdout, and\nchild.stderr, respectively.\n\n

\n

In the following example, only the child's fd 1 (stdout) is configured as a\npipe, so only the parent's child.stdio[1] is a stream, all other values in\nthe array are null.\n\n

\n
const assert = require('assert');\nconst fs = require('fs');\nconst child_process = require('child_process');\n\nconst child = child_process.spawn('ls', {\n    stdio: [\n      0, // Use parents 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.equal(child.stdio[0], null);\nassert.equal(child.stdio[0], child.stdin);\n\nassert(child.stdout);\nassert.equal(child.stdio[1], child.stdout);\n\nassert.equal(child.stdio[2], null);\nassert.equal(child.stdio[2], child.stderr);
\n" }, { "textRaw": "`stdout` {Stream} ", "type": "Stream", "name": "stdout", "desc": "

A Readable Stream that represents the child process's stdout.\n\n

\n

If the child was spawned with stdio[1] set to anything other than 'pipe',\nthen this will be undefined.\n\n

\n

child.stdout is an alias for child.stdio[1]. Both properties will refer\nto the same value.\n\n

\n" } ], "methods": [ { "textRaw": "child.disconnect()", "type": "method", "name": "disconnect", "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 child.connected and process.connected properties in both\nthe parent and child (respectively) will be set to false, and it will be no\nlonger possible to pass messages between the processes.\n\n

\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 child.disconnect().\n\n

\n

Note that when the child process is a Node.js instance (e.g. spawned using\n[child_process.fork()]), the process.disconnect() method can be invoked\nwithin the child process to close the IPC channel as well.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "child.kill([signal])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} ", "name": "signal", "type": "String", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "desc": "

The child.kill() methods sends a signal to the child process. If no argument\nis given, the process will be sent the 'SIGTERM' signal. See signal(7) for\na list of available signals.\n\n

\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

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

\n

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

\n

See kill(2)\n\n

\n" }, { "textRaw": "child.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle} ", "name": "sendHandle", "type": "Handle" }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle" }, { "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 child.send() method can be\nused to send messages to the child process. When the child process is a Node.js\ninstance, these messages can be received via the process.on('message') event.\n\n

\n

For example, in the parent script:\n\n

\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

And then the child script, 'sub.js' might look like this:\n\n

\n
process.on('message', (m) => {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\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\n

\n

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property are considered to be reserved\nfor use within Node.js core and will not be emitted in the child's\nprocess.on('message') event. 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\n

\n

The optional sendHandle argument that may be passed to child.send() is for\npassing 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.\n\n

\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

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

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

\n

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

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

\n
const child = require('child_process').fork('child.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  child.send('server', server);\n});
\n

The child would then receive the server object as:\n\n

\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

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

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

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

\n
const normal = require('child_process').fork('child.js', ['normal']);\nconst special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nconst server = require('net').createServer();\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

The child.js would receive the socket handle as the second argument passed\nto the event callback function:\n\n

\n
process.on('message', (m, socket) => {\n  if (m === 'socket') {\n    socket.end(`Request handled with ${process.argv[2]} priority`);\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\n

\n

Note: this function uses [JSON.stringify()][] internally to serialize the message.\n\n

\n" } ] } ], "type": "module", "displayName": "Child Process" }, { "textRaw": "Cluster", "name": "cluster", "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\n

\n

The cluster module allows you to easily create child processes that\nall share server ports.\n\n

\n
const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var 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

Running Node.js will now share port 8000 between the workers:\n\n

\n
$ NODE_DEBUG=cluster node server.js\n23521,Master Worker 23524 online\n23521,Master Worker 23526 online\n23521,Master Worker 23523 online\n23521,Master Worker 23528 online
\n

Please note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

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

\n

The cluster module supports two methods of distributing incoming\nconnections.\n\n

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

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

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

\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

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

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

\n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "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\n

\n", "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "desc": "

Similar to the cluster.on('disconnect') event, but specific to this worker.\n\n

\n
cluster.fork().on('disconnect', () => {\n  // Worker has disconnected\n});
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

This event is the same as the one provided by [child_process.fork()][].\n\n

\n

In a worker you can also use process.on('error').\n\n

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

Similar to the cluster.on('exit') event, but specific to this worker.\n\n

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

Similar to the cluster.on('listening') event, but specific to this worker.\n\n

\n
cluster.fork().on('listening', (address) => {\n  // Worker is listening\n});
\n

It is not emitted in the worker.\n\n

\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Similar to the cluster.on('message') event, but specific to this worker.\n\n

\n

This event is the same as the one provided by [child_process.fork()][].\n\n

\n

In a worker you can also use process.on('message').\n\n

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

\n
const cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var 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 (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach((id) => {\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" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "desc": "

Similar to the cluster.on('online') event, but specific to this worker.\n\n

\n
cluster.fork().on('online', () => {\n  // Worker is online\n});
\n

It is not emitted in the worker.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "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\n

\n

In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.\n\n

\n

Causes .suicide to be set.\n\n

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

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

\n

Note that in a worker, process.disconnect exists, but it is not this function,\nit is [disconnect][].\n\n

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

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var 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  var 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", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.isConnected()", "type": "method", "name": "isConnected", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.isDead()", "type": "method", "name": "isDead", "desc": "

This function returns true if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "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\n

\n

Causes .suicide to be set.\n\n

\n

This method is aliased as worker.destroy() for backwards compatibility.\n\n

\n

Note that in a worker, process.kill() exists, but it is not this function,\nit is [kill][].\n\n

\n" }, { "textRaw": "worker.send(message[, sendHandle][, callback])", "type": "method", "name": "send", "signatures": [ { "return": { "textRaw": "Return: Boolean ", "name": "return", "desc": "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\n

\n

In the master this sends a message to a specific worker. It is identical to\n[ChildProcess.send()][].\n\n

\n

In a worker this sends a message to the master. It is identical to\nprocess.send().\n\n

\n

This example will echo back all messages from the master:\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', (msg) => {\n    process.send(msg);\n  });\n}
\n" } ], "properties": [ { "textRaw": "`id` {Number} ", "type": "Number", "name": "id", "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.\n\n

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

\n" }, { "textRaw": "`process` {ChildProcess} ", "type": "ChildProcess", "name": "process", "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\n

\n

See: [Child Process module][]\n\n

\n

Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .suicide is not true. This protects against accidental\ndisconnection.\n\n

\n" }, { "textRaw": "`suicide` {Boolean} ", "type": "Boolean", "name": "suicide", "desc": "

Set by calling .kill() or .disconnect(), until then it is undefined.\n\n

\n

The boolean worker.suicide lets you distinguish between voluntary and accidental\nexit, the master may choose not to respawn a worker based on this value.\n\n

\n
cluster.on('exit', (worker, code, signal) => {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// kill worker\nworker.kill();
\n" } ] } ], "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "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\n

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

\n
cluster.on('disconnect', (worker) => {\n  console.log(`The worker #${worker.id} has disconnected`);\n});
\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

When any of the workers die the cluster module will emit the 'exit' event.\n\n

\n

This can be used to restart the worker by calling .fork() again.\n\n

\n
cluster.on('exit', (worker, code, signal) => {\n  console.log('worker %d died (%s). restarting...',\n    worker.process.pid, signal || code);\n  cluster.fork();\n});
\n

See [child_process event: 'exit'][].\n\n

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

\n
var timeouts = [];\nfunction errorMsg() {\n  console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "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\n

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

\n
cluster.on('listening', (worker, address) => {\n  console.log(\n    `A worker is now connected to ${address.address}:${address.port}`);\n});
\n

The addressType is one of:\n\n

\n\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Emitted when any worker receives a message.\n\n

\n

See [child_process event: 'message'][].\n\n

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

\n
cluster.on('online', (worker) => {\n  console.log('Yay, the worker responded after it was forked');\n});
\n" }, { "textRaw": "Event: 'setup'", "type": "event", "name": "setup", "params": [], "desc": "

Emitted every time .setupMaster() is called.\n\n

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

\n

If accuracy is important, use cluster.settings.\n\n

\n" } ], "methods": [ { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "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\n

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

\n

The method takes an optional callback argument which will be called when finished.\n\n

\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "return {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\n

\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "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\n

\n

Note that:\n\n

\n\n

Example:\n\n

\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

This can only be called from the master process.\n\n

\n" } ], "properties": [ { "textRaw": "`isMaster` {Boolean} ", "type": "Boolean", "name": "isMaster", "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\n

\n" }, { "textRaw": "`isWorker` {Boolean} ", "type": "Boolean", "name": "isWorker", "desc": "

True if the process is not a master (it is the negation of cluster.isMaster).\n\n

\n" }, { "textRaw": "cluster.schedulingPolicy", "name": "schedulingPolicy", "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\n

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

\n

cluster.schedulingPolicy can also be set through the\nNODE_CLUSTER_SCHED_POLICY environment variable. Valid\nvalues are "rr" and "none".\n\n

\n" }, { "textRaw": "`settings` {Object} ", "type": "Object", "name": "settings", "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the Node.js executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "list of string arguments passed to the Node.js executable." }, { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" } ], "desc": "

After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.\n\n

\n

It is effectively frozen after being set, because .setupMaster() can\nonly be called once.\n\n

\n

This object is not supposed to be changed or set manually, by you.\n\n

\n" }, { "textRaw": "`worker` {Object} ", "type": "Object", "name": "worker", "desc": "

A reference to the current worker object. Not available in the master process.\n\n

\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" }, { "textRaw": "`workers` {Object} ", "type": "Object", "name": "workers", "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\n

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

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker((worker) => {\n  worker.send('big announcement to all workers');\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\n

\n
socket.on('data', (id) => {\n  var worker = cluster.workers[id];\n});
\n" } ], "type": "module", "displayName": "Cluster" }, { "textRaw": "Console", "name": "console", "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\n

\n

The module exports two specific components:\n\n

\n\n

Example using the global console:\n\n

\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

Example using the Console class:\n\n

\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

While the API for the Console class is designed fundamentally around the\nbrowser console object, the Console in Node.js is not intended to\nduplicate the browser's functionality exactly.\n\n

\n", "modules": [ { "textRaw": "Asynchronous vs Synchronous Consoles", "name": "asynchronous_vs_synchronous_consoles", "desc": "

The console functions are asynchronous unless the destination is a file.\nDisks are fast and operating systems normally employ write-back caching;\nit should be a very rare occurrence indeed that a write blocks, but it\nis possible.\n\n

\n", "type": "module", "displayName": "Asynchronous vs Synchronous Consoles" } ], "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\n

\n
const Console = require('console').Console;\nconst Console = console.Console;
\n", "methods": [ { "textRaw": "console.assert(value[, message][, ...])", "type": "method", "name": "assert", "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\n

\n
console.assert(true, 'does nothing');\n  // OK\nconsole.assert(false, 'Whoops %s', 'didn\\'t work');\n  // AssertionError: Whoops didn't work
\n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj[, options])", "type": "method", "name": "dir", "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

\n\n", "signatures": [ { "params": [ { "name": "obj" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "console.error([data][, ...])", "type": "method", "name": "error", "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\n[util.format()][]).\n\n

\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

If formatting elements (e.g. %d) are not found in the first string then\n[util.inspect()][] is called on each argument and the resulting string\nvalues are concatenated. See [util.format()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data][, ...])", "type": "method", "name": "info", "desc": "

The console.info() function is an alias for [console.log()][].\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.log([data][, ...])", "type": "method", "name": "log", "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\n[util.format()][]).\n\n

\n
var count = 5;\nconsole.log('count: %d', count);\n  // Prints: count: 5, to stdout\nconsole.log('count: ', count);\n  // Prints: count: 5, to stdout
\n

If formatting elements (e.g. %d) are not found in the first string then\n[util.inspect()][] is called on each argument and the resulting string\nvalues are concatenated. See [util.format()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "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\n[console.timeEnd()][] to stop the timer and output the elapsed time in\nmilliseconds to stdout. Timer durations are accurate to the sub-millisecond.\n\n

\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

Stops a timer that was previously started by calling [console.time()][] and\nprints the result to stdout:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');\n// prints 100-elements: 225.438ms
\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(message[, ...])", "type": "method", "name": "trace", "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\n

\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", "signatures": [ { "params": [ { "name": "message" }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data][, ...])", "type": "method", "name": "warn", "desc": "

The console.warn() function is an alias for [console.error()][].\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "stdout" }, { "name": "stderr", "optional": true } ], "desc": "

Creates a new Console by passing one or two writable stream instances.\nstdout is a writable stream to print log or info output. stderr\nis used for warning or error output. If stderr isn't passed, warning and error\noutput will be sent to stdout.\n\n

\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\nvar count = 5;\nlogger.log('count: %d', count);\n// in stdout.log: count 5
\n

The global console is a special Console whose output is sent to\n[process.stdout][] and [process.stderr][]. It is equivalent to calling:\n\n

\n
new Console(process.stdout, process.stderr);
\n" } ] } ], "type": "module", "displayName": "Console" }, { "textRaw": "Crypto", "name": "crypto", "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\n

\n

Use require('crypto') to access this module.\n\n

\n
const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n                   .update('I love cupcakes')\n                   .digest('hex');\nconsole.log(hash);\n  // Prints:\n  //   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
\n", "classes": [ { "textRaw": "Class: Certificate", "type": "class", "name": "Certificate", "desc": "

SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and now specified formally as part of [HTML5's keygen element][].\n\n

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

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

\n
const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "certificate.exportChallenge(spkac)", "type": "method", "name": "exportChallenge", "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\n

\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", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.exportPublicKey(spkac)", "type": "method", "name": "exportPublicKey", "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\n

\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", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.verifySpkac(spkac)", "type": "method", "name": "verifySpkac", "desc": "

Returns true if the given spkac data structure is valid, false otherwise.\nThe spkac argument must be a Node.js [Buffer][].\n\n

\n
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(new Buffer(spkac)));\n  // Prints true or false
\n", "signatures": [ { "params": [ { "name": "spkac" } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "desc": "

Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:\n\n

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

\n

Example: Using Cipher objects as streams:\n\n

\n
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nvar encrypted = '';\ncipher.on('readable', () => {\n  var 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

Example: Using Cipher and piped streams:\n\n

\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

Example: Using the [cipher.update()][] and [cipher.final()][] methods:\n\n

\n
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nvar encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n  // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
\n", "methods": [ { "textRaw": "cipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

Returns any remaining enciphered contents. If output_encoding\nparameter is one of 'binary', 'base64' or 'hex', a string is returned.\nIf an output_encoding is not provided, a [Buffer][] is returned.\n\n

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

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAAD(buffer)", "type": "method", "name": "setAAD", "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\n

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "cipher.getAuthTag()", "type": "method", "name": "getAuthTag", "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\n

\n

The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the [cipher.final()][] method.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "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\n

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

\n

The cipher.setAutoPadding() method must be called before [cipher.final()][].\n\n

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "cipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "desc": "

Updates the cipher with data. If the input_encoding argument is given,\nit's value must be one of 'utf8', 'ascii', or 'binary' 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\n[Buffer][] then input_encoding is ignored.\n\n

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', '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\n

\n

The cipher.update() method can be called multiple times with new data until\n[cipher.final()][] is called. Calling cipher.update() after\n[cipher.final()][] will result in an error being thrown.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "desc": "

Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:\n\n

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

\n

Example: Using Decipher objects as streams:\n\n

\n
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nvar decrypted = '';\ndecipher.on('readable', () => {\n  var 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\nvar encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\ndecipher.write(encrypted, 'hex');\ndecipher.end();
\n

Example: Using Decipher and piped streams:\n\n

\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

Example: Using the [decipher.update()][] and [decipher.final()][] methods:\n\n

\n
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nvar encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\nvar decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n  // Prints: some clear text data
\n", "methods": [ { "textRaw": "decipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

Returns any remaining deciphered contents. If output_encoding\nparameter is one of 'binary', 'base64' or 'hex', a string is returned.\nIf an output_encoding is not provided, a [Buffer][] is returned.\n\n

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

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAAD(buffer)", "type": "method", "name": "setAAD", "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\n

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAuthTag(buffer)", "type": "method", "name": "setAuthTag", "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()][] with throw, indicating that the\ncipher text should be discarded due to failed authentication.\n\n

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

When data has been encrypted without standard block padding, calling\ndecipher.setAuthPadding(false) will disable automatic padding to prevent\n[decipher.final()][] from checking for and removing padding.\n\n

\n

Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.\n\n

\n

The decipher.setAutoPadding() method must be called before\n[decipher.update()][].\n\n

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "decipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "desc": "

Updates the decipher with data. If the input_encoding argument is given,\nit's value must be one of 'binary', '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\n[Buffer][] then input_encoding is ignored.\n\n

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', '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\n

\n

The decipher.update() method can be called multiple times with new data until\n[decipher.final()][] is called. Calling decipher.update() after\n[decipher.final()][] will result in an error being thrown.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "desc": "

The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.\n\n

\n

Instances of the DiffieHellman class can be created using the\n[crypto.createDiffieHellman()][] function.\n\n

\n
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst alice_key = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bob_key = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst alice_secret = alice.computeSecret(bob_key);\nconst bob_secret = bob.computeSecret(alice_key);\n\n// OK\nassert.equal(alice_secret.toString('hex'), bob_secret.toString('hex'));
\n", "methods": [ { "textRaw": "diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "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'binary', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a [Buffer][].\n\n

\n

If output_encoding is given a string is returned; otherwise, a\n[Buffer][] is returned.\n\n

\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", "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 'binary', 'hex',\nor 'base64'. If encoding is provided a string is returned; otherwise a\n[Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "desc": "

Returns the Diffie-Hellman generator in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a [Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a [Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "desc": "

Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a [Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'binary', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a [Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "desc": "

Sets the Diffie-Hellman private key. If the encoding argument is provided\nand is either 'binary', '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\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "desc": "

Sets the Diffie-Hellman public key. If the encoding argument is provided\nand is either 'binary', '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\n

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "diffieHellman.verifyError", "name": "verifyError", "desc": "

A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.\n\n

\n

The following values are valid for this property (as defined in constants\nmodule):\n\n

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

The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.\n\n

\n

Instances of the ECDH class can be created using the\n[crypto.createECDH()][] function.\n\n

\n
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst alice_key = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createECDH('secp521r1');\nconst bob_key = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst alice_secret = alice.computeSecret(bob_key);\nconst bob_secret = bob.computeSecret(alice_key);\n\nassert(alice_secret, bob_secret);\n  // OK
\n", "methods": [ { "textRaw": "ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "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'binary', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a [Buffer][].\n\n

\n

If output_encoding is given a string will be returned; otherwise a\n[Buffer][] is returned.\n\n

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

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

\n

The encoding argument can be 'binary', 'hex', or 'base64'. If\nencoding is provided a string is returned; otherwise a [Buffer][]\nis returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding" }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "desc": "

Returns the EC Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If encoding is provided\na string is returned; otherwise a [Buffer][] is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.getPublicKey([encoding[, format]])", "type": "method", "name": "getPublicKey", "desc": "

Returns the EC Diffie-Hellman public key in the specified encoding and\nformat.\n\n

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

\n

The encoding argument can be 'binary', 'hex', or 'base64'. If\nencoding is specified, a string is returned; otherwise a [Buffer][] is\nreturned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding" }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "desc": "

Sets the EC Diffie-Hellman private key. The encoding can be 'binary',\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\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "stability": 0, "stabilityText": "Deprecated", "desc": "

Sets the EC Diffie-Hellman public key. Key encoding can be 'binary',\n'hex' or 'base64'. If encoding is provided public_key is expected to\nbe a string; otherwise a [Buffer][] is expected.\n\n

\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\n[ecdh.setPrivateKey()][] will be called. The [ecdh.setPrivateKey()][] method\nattempts to generate the public point/key associated with the private key being\nset.\n\n

\n

Example (obtaining a shared secret):\n\n

\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 bob.generateKeys();\n\nconst alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// alice_secret and bob_secret should be the same shared secret value\nconsole.log(alice_secret === bob_secret);
\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "desc": "

The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:\n\n

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

\n

Example: Using Hash objects as streams:\n\n

\n
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n  var data = hash.read();\n  if (data)\n    console.log(data.toString('hex'));\n    // Prints:\n    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n});\n\nhash.write('some data to hash');\nhash.end();
\n

Example: Using Hash and piped streams:\n\n

\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

Example: Using the [hash.update()][] and [hash.digest()][] methods:\n\n

\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", "methods": [ { "textRaw": "hash.digest([encoding])", "type": "method", "name": "digest", "desc": "

Calculates the digest of all of the data passed to be hashed (using the\n[hash.update()][] method). The encoding can be 'hex', 'binary' or\n'base64'. If encoding is provided a string will be returned; otherwise\na [Buffer][] is returned.\n\n

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

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hash.update(data[, input_encoding])", "type": "method", "name": "update", "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'binary'. If encoding is not provided, and the data is a string, an\nencoding of 'binary' is enforced. If data is a [Buffer][] then\ninput_encoding is ignored.\n\n

\n

This can be called many times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "desc": "

The Hmac Class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:\n\n

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

\n

Example: Using Hmac objects as streams:\n\n

\n
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n  var data = hmac.read();\n  if (data)\n    console.log(data.toString('hex'));\n    // Prints:\n    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n});\n\nhmac.write('some data to hash');\nhmac.end();
\n

Example: Using Hmac and piped streams:\n\n

\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

Example: Using the [hmac.update()][] and [hmac.digest()][] methods:\n\n

\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", "methods": [ { "textRaw": "hmac.digest([encoding])", "type": "method", "name": "digest", "desc": "

Calculates the HMAC digest of all of the data passed using [hmac.update()][].\nThe encoding can be 'hex', 'binary' or 'base64'. If encoding is\nprovided a string is returned; otherwise a [Buffer][] is returned;\n\n

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

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hmac.update(data[, input_encoding])", "type": "method", "name": "update", "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'binary'. 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\n

\n

This can be called many times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "desc": "

The Sign Class is a utility for generating signatures. It can be used in one\nof two ways:\n\n

\n\n

The [crypto.createSign()][] method is used to create Sign instances. Sign\nobjects are not to be created directly using the new keyword.\n\n

\n

Example: Using Sign objects as streams:\n\n

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.write('some data to sign');\nsign.end();\n\nconst private_key = getPrivateKeySomehow();\nconsole.log(sign.sign(private_key, 'hex'));\n  // Prints the calculated signature
\n

Example: Using the [sign.update()][] and [sign.sign()][] methods:\n\n

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.update('some data to sign');\n\nconst private_key = getPrivateKeySomehow();\nconsole.log(sign.sign(private_key, 'hex'));\n  // Prints the calculated signature
\n", "methods": [ { "textRaw": "sign.sign(private_key[, output_format])", "type": "method", "name": "sign", "desc": "

Calculates the signature on all the data passed through using either\n[sign.update()][] or [sign.write()][stream-writable-write].\n\n

\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 is interpreted as a hash containing two properties:\n\n

\n\n

The output_format can specify one of 'binary', 'hex' or 'base64'. If\noutput_format is provided a string is returned; otherwise a [Buffer][] is\nreturned.\n\n

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

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] }, { "textRaw": "sign.update(data[, input_encoding])", "type": "method", "name": "update", "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'binary'. 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\n

\n

This can be called many times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "desc": "

The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:\n\n

\n\n

Example: Using Verify objects as streams:\n\n

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.write('some data to sign');\nverify.end();\n\nconst public_key = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(sign.verify(public_key, signature));\n  // Prints true or false
\n

Example: Using the [verify.update()][] and [verify.verify()][] methods:\n\n

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.update('some data to sign');\n\nconst public_key = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(public_key, signature));\n  // Prints true or false
\n", "methods": [ { "textRaw": "verifier.update(data[, input_encoding])", "type": "method", "name": "update", "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'binary'. 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\n

\n

This can be called many times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "verifier.verify(object, signature[, signature_format])", "type": "method", "name": "verify", "desc": "

Verifies the provided data using the given object and signature.\nThe object argument is a string containing a PEM encoded object, which can be\none an RSA public key, a DSA public key, or an X.509 certificate.\nThe signature argument is the previously calculated signature for the data, in\nthe signature_format which can be 'binary', '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\n

\n

Returns true or false depending on the validity of the signature for\nthe data and public key.\n\n

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

\n", "signatures": [ { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "`crypto` module methods and properties", "name": "`crypto`_module_methods_and_properties", "properties": [ { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "desc": "

The default encoding to use for functions that can take either strings\nor [buffers][Buffer]. The default value is 'buffer', which makes methods\ndefault to [Buffer][] objects.\n\n

\n

The crypto.DEFAULT_ENCODING mechanism is provided for backwards compatibility\nwith legacy programs that expect 'binary' to be the default encoding.\n\n

\n

New applications should expect the default to be 'buffer'. This property may\nbecome deprecated in a future Node.js release.\n\n

\n" } ], "methods": [ { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "desc": "

Creates and returns a Cipher object that uses the given algorithm and\npassword.\n\n

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

\n

The password is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'binary' encoded string or a [Buffer][].\n\n

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

\n

In line with OpenSSL's recommendation to use pbkdf2 instead of\n[EVP_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.\n\n

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

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

\n

The key is the raw key used by the algorithm and iv is an\n[initialization vector][]. Both arguments must be 'binary' encoded strings or\n[buffers][Buffer].\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "stability": 0, "stabilityText": "Deprecated: Use [`tls.createSecureContext()`][] instead.", "desc": "

The crypto.createCredentials() method is a deprecated alias for creating\nand returning a tls.SecureContext object. The crypto.createCredentials()\nmethod should not be used.\n\n

\n

The optional details argument is a hash object with keys:\n\n

\n\n

If no 'ca' details are given, Node.js will use Mozilla's default\n[publicly trusted list of CAs][].\n\n

\n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "desc": "

Creates and returns a Decipher object that uses the given algorithm and\npassword (key).\n\n

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

\n

In line with OpenSSL's recommendation to use pbkdf2 instead of\n[EVP_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\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "desc": "

Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).\n\n

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

\n

The key is the raw key used by the algorithm and iv is an\n[initialization vector][]. Both arguments must be 'binary' encoded strings or\n[buffers][Buffer].\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])", "type": "method", "name": "createDiffieHellman", "desc": "

Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.\n\n

\n

The generator argument can be a number, string, or [Buffer][]. If\ngenerator is not specified, the value 2 is used.\n\n

\n

The prime_encoding and generator_encoding arguments can be 'binary',\n'hex', or 'base64'.\n\n

\n

If prime_encoding is specified, prime is expected to be a string; otherwise\na [Buffer][] is expected.\n\n

\n

If generator_encoding is specified, generator is expected to be a string;\notherwise either a number or [Buffer][] is expected.\n\n

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

\n", "signatures": [ { "params": [ { "name": "prime_length" }, { "name": "generator", "optional": true } ] } ] }, { "textRaw": "crypto.createECDH(curve_name)", "type": "method", "name": "createECDH", "desc": "

Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curve_name string. Use\n[crypto.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\n

\n", "signatures": [ { "params": [ { "name": "curve_name" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "desc": "

Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm.\n\n

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

\n

Example: generating the sha256 sum of a file\n\n

\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  var data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});
\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "desc": "

Creates and returns an Hmac object that uses the given algorithm and key.\n\n

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

\n

The key is the HMAC key used to generate the cryptographic HMAC hash.\n\n

\n

Example: generating the sha256 HMAC of a file\n\n

\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  var data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});
\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "desc": "

Creates and returns a Sign object that uses the given algorithm. On\nrecent OpenSSL releases, openssl list-public-key-algorithms will\ndisplay the available signing algorithms. One example is 'RSA-SHA256'.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "desc": "

Creates and returns a Verify object that uses the given algorithm. On\nrecent OpenSSL releases, openssl list-public-key-algorithms will\ndisplay the available signing algorithms. One example is 'RSA-SHA256'.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported cipher algorithms.\n\n

\n

Example:\n\n

\n
const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getCurves()", "type": "method", "name": "getCurves", "desc": "

Returns an array with the names of the supported elliptic curves.\n\n

\n

Example:\n\n

\n
const curves = crypto.getCurves();\nconsole.log(curves); // ['secp256k1', 'secp384r1', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "desc": "

Creates a predefined DiffieHellman key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in\n[RFC 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\n[crypto.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\n

\n

Example (obtaining a shared secret):\n\n

\n
const crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
\n", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "desc": "

Returns an array with the names of the supported hash algorithms.\n\n

\n

Example:\n\n

\n
const hashes = crypto.getHashes();\nconsole.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)", "type": "method", "name": "pbkdf2", "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. If the digest algorithm is not specified,\na default of 'sha1' is used.\n\n

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

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

\n

The salt should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\n[NIST SP 800-132][] for details.\n\n

\n

Example:\n\n

\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'));  // 'c5e478d...1469e50'\n});
\n

An array of supported digest functions can be retrieved using\n[crypto.getHashes()][].\n\n

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])", "type": "method", "name": "pbkdf2Sync", "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. If the digest algorithm is not specified,\na default of 'sha1' is used.\n\n

\n

If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a [Buffer][].\n\n

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

\n

The salt should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\n[NIST SP 800-132][] for details.\n\n

\n

Example:\n\n

\n
const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key.toString('hex'));  // 'c5e478d...1469e50'
\n

An array of supported digest functions can be retrieved using\n[crypto.getHashes()][].\n\n

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest", "optional": true } ] } ] }, { "textRaw": "crypto.privateDecrypt(private_key, buffer)", "type": "method", "name": "privateDecrypt", "desc": "

Decrypts buffer with private_key.\n\n

\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

\n\n

All paddings are defined in the constants module.\n\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.privateEncrypt(private_key, buffer)", "type": "method", "name": "privateEncrypt", "desc": "

Encrypts buffer with private_key.\n\n

\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

\n\n

All paddings are defined in the constants module.\n\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicDecrypt(public_key, buffer)", "type": "method", "name": "publicDecrypt", "desc": "

Decrypts buffer with public_key.\n\n

\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

\n\n

Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.\n\n

\n

All paddings are defined in the constants module.\n\n

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicEncrypt(public_key, buffer)", "type": "method", "name": "publicEncrypt", "desc": "

Encrypts buffer with public_key.\n\n

\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

\n\n

Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.\n\n

\n

All paddings are defined in the constants module.\n\n

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.randomBytes(size[, callback])", "type": "method", "name": "randomBytes", "desc": "

Generates cryptographically strong pseudo-random data. The size argument\nis a number indicating the number of bytes to generate.\n\n

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

\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

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

\n
// Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
\n

The crypto.randomBytes() method will block until there is sufficient entropy.\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\n

\n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.setEngine(engine[, flags])", "type": "method", "name": "setEngine", "desc": "

Load and set the engine for some or all OpenSSL functions (selected by flags).\n\n

\n

engine could be either an id or a path to the engine's shared library.\n\n

\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 the\nconstants module):\n\n

\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][stream]\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'binary' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use [Buffer][] objects by default\ninstead.\n\n

\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.\n[ecdh.setPrivateKey()][] now also validates that the private key is valid for\nthe selected curve.\n\n

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

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

\n

Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.\n\n

\n

Based on the recommendations of [NIST SP 800-131A][]:\n\n

\n\n

See the reference for other recommendations and details.\n\n

\n", "type": "module", "displayName": "Support for weak or compromised algorithms" } ], "type": "module", "displayName": "Notes" } ], "type": "module", "displayName": "Crypto" }, { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "stability": 2, "stabilityText": "Stable", "desc": "

The dgram module provides an implementation of UDP Datagram sockets.\n\n

\n
const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  var 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", "classes": [ { "textRaw": "Class: dgram.Socket", "type": "class", "name": "dgram.Socket", "desc": "

The dgram.Socket object is an [EventEmitter][] that encapsulates the\ndatagram functionality.\n\n

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

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "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\n

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

The 'error' event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.\n\n

\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

The 'listening' event is emitted whenever a socket begins listening for\ndatagram messages. This occurs as soon as UDP sockets are created.\n\n

\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

The 'message' event is emitted when a new datagram is available on a socket.\nThe event handler function is passed two arguments: msg and rinfo. The\nmsg argument is a [Buffer][] and rinfo is an object with the sender's\naddress information provided by the address, family and port properties:\n\n

\n
socket.on('message', (msg, rinfo) => {\n  console.log('Received %d bytes from %s:%d\\n',\n              msg.length, rinfo.address, rinfo.port);\n});
\n" } ], "methods": [ { "textRaw": "socket.addMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "addMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {String} ", "name": "multicastAddress", "type": "String" }, { "textRaw": "`multicastInterface` {String}, Optional ", "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\nusing the IP_ADD_MEMBERSHIP socket option. If the multicastInterface\nargument is not specified, the operating system will try to add membership to\nall valid networking interfaces.\n\n

\n" }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address, family and port\nproperties.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.bind([port][, address][, callback])", "type": "method", "name": "bind", "signatures": [ { "params": [ { "textRaw": "`port` {Number} - Integer, Optional ", "name": "port", "type": "Number", "optional": true, "desc": "Integer" }, { "textRaw": "`address` {String}, Optional ", "name": "address", "type": "String", "optional": true }, { "textRaw": "`callback` {Function} with no parameters, Optional. Called when binding is complete. ", "name": "callback", "type": "Function", "desc": "with no parameters, Optional. 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 messages on a\nnamed port and optional address. If port is not specified, the operating\nsystem will attempt to bind to a random port. If address is not specified,\nthe operating system will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening' event is emitted and the optional callback function\nis called.\n\n

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

\n

A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.\n\n

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

\n

Example of a UDP server listening on port 41234:\n\n

\n
const dgram = require('dgram');\nconst server = dgram.createSocket('udp4');\n\nserver.on('error', (err) => {\n  console.log(`server error:\\n${err.stack}`);\n  server.close();\n});\n\nserver.on('message', (msg, rinfo) => {\n  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);\n});\n\nserver.on('listening', () => {\n  var 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" }, { "textRaw": "socket.bind(options[, callback])", "type": "method", "name": "bind", "signatures": [ { "params": [ { "textRaw": "`options` {Object} - Required. Supports the following properties: ", "options": [ { "textRaw": "`port` {Number} - Required. ", "name": "port", "type": "Number", "desc": "Required." }, { "textRaw": "`address` {String} - Optional. ", "name": "address", "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": "

For UDP sockets, causes the dgram.Socket to listen for datagram messages on a\nnamed port and optional address that are passed as properties of an\noptions object passed as the first argument. If port is not specified, the\noperating system will attempt to bind to a random port. If address is not\nspecified, the operating system will attempt to listen on all addresses. Once\nbinding is complete, a 'listening' event is emitted and the optional\ncallback function is called.\n\n

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

\n

An example socket listening on an exclusive port is shown below.\n\n

\n
socket.bind({\n  address: 'localhost',\n  port: 8000,\n  exclusive: true\n});
\n" }, { "textRaw": "socket.close([callback])", "type": "method", "name": "close", "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\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.dropMembership(multicastAddress[, multicastInterface])", "type": "method", "name": "dropMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` {String} ", "name": "multicastAddress", "type": "String" }, { "textRaw": "`multicastInterface` {String}, Optional ", "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\n

\n

If multicastInterface is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.\n\n

\n" }, { "textRaw": "socket.send(msg, [offset, length,] port, address[, callback])", "type": "method", "name": "send", "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. Optional. Offset in the buffer where the message starts. ", "name": "offset", "type": "Number", "desc": "Integer. Optional. Offset in the buffer where the message starts." }, { "textRaw": "`length` {Number} Integer. Optional. Number of bytes in the message. ", "name": "length", "type": "Number", "desc": "Integer. Optional. Number of bytes in the message." }, { "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. Optional. ", "name": "callback", "type": "Function", "desc": "Called when the message has been sent. Optional.", "optional": true } ] }, { "params": [ { "name": "msg" }, { "name": "offset" }, { "name": "length" }, { "name": "] port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

Broadcasts a datagram on the socket. The destination port and address must\nbe specified.\n\n

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

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

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

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

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

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

\n

Example of sending a UDP packet to a random port on localhost;\n\n

\n
const dgram = require('dgram');\nconst message = new Buffer('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n  client.close();\n});
\n

Example of sending a UDP packet composed of multiple buffers to a random port on localhost;\n\n

\n
const dgram = require('dgram');\nconst buf1 = new Buffer('Some ');\nconst buf2 = new Buffer('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, 'localhost', (err) => {\n  client.close();\n});
\n

Sending multiple buffers might be faster or slower depending on your\napplication and operating system: benchmark it. Usually it is faster.\n\n

\n

A Note about UDP datagram size\n\n

\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

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

\n" }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "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\n

\n" }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "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\n

\n" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "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\n

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

\n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "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\n

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

\n" }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "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\n

\n

Calling socket.ref() multiples times will have no additional effect.\n\n

\n

The socket.ref() method returns a reference to the socket so calls can be\nchained.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "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\n

\n

Calling socket.unref() multiple times will have no addition effect.\n\n

\n

The socket.unref() method returns a reference to the socket so calls can be\nchained.\n\n

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

\n
const s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');
\n

Must be changed to pass a callback function to the [dgram.Socket#bind()][]\nfunction:\n\n

\n
const s = dgram.createSocket('udp4');\ns.bind(1234, () => {\n  s.addMembership('224.0.0.114');\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", "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\n

\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. An optional callback function can be passed specified which is added\nas a listener for 'message' events.\n\n

\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\n[socket.address().address][] and [socket.address().port][].\n\n

\n" }, { "textRaw": "dgram.createSocket(type[, callback])", "type": "method", "name": "createSocket", "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. Optional ", "name": "callback", "type": "Function", "optional": true, "desc": "Attached as a listener to `'message'` events." } ] }, { "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\n

\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\n[socket.address().address][] and [socket.address().port][].\n\n

\n" } ], "type": "module", "displayName": "`dgram` module functions" } ], "type": "module", "displayName": "dgram" }, { "textRaw": "DNS", "name": "dns", "stability": 2, "stabilityText": "Stable", "desc": "

The dns module contains functions belonging to two different categories:\n\n

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

\n

For example, looking up nodejs.org.\n\n

\n
const dns = require('dns');\n\ndns.lookup('nodejs.org', (err, addresses, family) => {\n  console.log('addresses:', addresses);\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\n[dns.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\n

\n

Below is an example that resolves 'nodejs.org' then reverse resolves the IP\naddresses that are returned.\n\n

\n
const dns = require('dns');\n\ndns.resolve4('nodejs.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

There are subtle consequences in choosing one over the other, please consult\nthe [Implementation considerations section][] for more information.\n\n

\n", "methods": [ { "textRaw": "dns.getServers()", "type": "method", "name": "getServers", "desc": "

Returns an array of IP address strings that are being used for name\nresolution.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "dns.lookup(hostname[, options], callback)", "type": "method", "name": "lookup", "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\n

\n

Alternatively, options can be an object containing these properties:\n\n

\n\n

All properties are optional. An example usage of options is shown below.\n\n

\n
{\n  family: 4,\n  hints: dns.ADDRCONFIG | dns.V4MAPPED,\n  all: false\n}
\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\n

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

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

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

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

Resolves the given address and port into a hostname and service using\nthe operating system's underlying getnameinfo implementation.\n\n

\n

The callback has arguments (err, hostname, service). The hostname and\nservice arguments are strings (e.g. 'localhost' and 'http' respectively).\n\n

\n

On error, err is an [Error][] object, where err.code is the error code.\n\n

\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", "signatures": [ { "params": [ { "name": "address" }, { "name": "port" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve(hostname[, rrtype], callback)", "type": "method", "name": "resolve", "desc": "

Uses the DNS protocol to resolve a hostname (e.g. 'nodejs.org') into an\narray of the record types specified by rrtype.\n\n

\n

Valid values for rrtype are:\n\n

\n\n

The callback function has arguments (err, addresses). When successful,\naddresses will be an array. The type of each item in addresses is\ndetermined by the record type, and described in the documentation for the\ncorresponding lookup methods.\n\n

\n

On error, err is an [Error][] object, where err.code is\none of the error codes listed here.\n\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "rrtype", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve4(hostname, callback)", "type": "method", "name": "resolve4", "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

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve6(hostname, callback)", "type": "method", "name": "resolve6", "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

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveCname(hostname, callback)", "type": "method", "name": "resolveCname", "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\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveMx(hostname, callback)", "type": "method", "name": "resolveMx", "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\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNs(hostname, callback)", "type": "method", "name": "resolveNs", "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\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSoa(hostname, callback)", "type": "method", "name": "resolveSoa", "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
{\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", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSrv(hostname, callback)", "type": "method", "name": "resolveSrv", "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
{\n  priority: 10,\n  weight: 5,\n  port: 21223,\n  name: 'service.example.com'\n}
\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveTxt(hostname, callback)", "type": "method", "name": "resolveTxt", "desc": "

Uses the DNS protocol to resolve text queries (TXT records) for the\nhostname. The addresses argument passed to the callback function is\nis a two-dimentional 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\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.reverse(ip, callback)", "type": "method", "name": "reverse", "desc": "

Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of hostnames.\n\n

\n

The callback function has arguments (err, hostnames), where hostnames\nis an array of resolved hostnames for the given ip.\n\n

\n

On error, err is an [Error][] object, where err.code is\none of the [DNS error codes][].\n\n

\n", "signatures": [ { "params": [ { "name": "ip" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.setServers(servers)", "type": "method", "name": "setServers", "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\n

\n

If a port specified on the address it will be removed.\n\n

\n

An error will be thrown if an invalid address is provided.\n\n

\n

The dns.setServers() method must not be called while a DNS query is in\nprogress.\n\n

\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

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

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

\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\n[the official libuv documentation][].\n\n

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

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

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

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

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

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

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

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

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

\n

For example, this is not a good idea:\n\n

\n
// XXX WARNING!  BAD IDEA!\n\nvar 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

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

\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    var 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        var 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 isn't 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      });\n      break;\n    default:\n      res.end('ok');\n  }\n}
\n" }, { "textRaw": "Additions to Error objects", "name": "Additions to Error objects", "type": "misc", "desc": "

Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

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

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

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

\n

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.\n\n

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

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

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

\n

That is possible via explicit binding.\n\n

\n

For example:\n\n

\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    var 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 (er) {\n        console.error('Error sending 500', er, req.url);\n      }\n    });\n  }).listen(1337);\n});
\n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "return: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

Returns a new Domain object.\n\n

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

\n

Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its 'error' event.\n\n

\n", "methods": [ { "textRaw": "domain.run(fn[, arg][, ...])", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} ", "name": "fn", "type": "Function" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] }, { "params": [ { "name": "fn" }, { "name": "arg", "optional": true }, { "name": "...", "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\n

\n

This is the most basic way to use a domain.\n\n

\n

Example:\n\n

\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

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

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

\n

This also works with timers that are returned from [setInterval()][] and\n[setTimeout()][]. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

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

\n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter|Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

The opposite of [domain.add(emitter)][]. Removes domain handling from the\nspecified emitter.\n\n

\n" }, { "textRaw": "domain.bind(callback)", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "return: {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\n

\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" }, { "textRaw": "domain.intercept(callback)", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "return: {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\n

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

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

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

\n

If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.\n\n

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

\n

If there are multiple, nested domains bound to the current execution context,\nexit will exit any domains nested within this domain.\n\n

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

\n

If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.\n\n

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

\n" } ] } ], "type": "module", "displayName": "Domain" }, { "textRaw": "Events", "name": "Events", "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\n

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

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

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

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

\n
const EventEmitter = require('events');\nconst util = require('util');\n\nfunction MyEmitter() {\n  EventEmitter.call(this);\n}\nutil.inherits(MyEmitter, EventEmitter);\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');
\n

Any object can become an EventEmitter through inheritance. The example above\nuses the traditional Node.js style prototypical inheritance using\nthe util.inherits() method. It is, however, possible to use ES6 classes as\nwell:\n\n

\n
const EventEmitter = require('events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n  console.log('an event occurred!');\n});\nmyEmitter.emit('event');
\n", "modules": [ { "textRaw": "Passing arguments and `this` to listeners", "name": "passing_arguments_and_`this`_to_listeners", "desc": "

The eventEmitter.emit() method allows an arbitrary set of arguments to be\npassed to the listener functions. 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\n

\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

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

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  console.log(a, b, this);\n    // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');
\n", "type": "module", "displayName": "Passing arguments and `this` to listeners" }, { "textRaw": "Asynchronous vs. Synchronous", "name": "asynchronous_vs._synchronous", "desc": "

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

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n  setImmediate(() => {\n    console.log('this happens asynchronously');\n  });\n});\nmyEmitter.emit('event', 'a', 'b');
\n", "type": "module", "displayName": "Asynchronous vs. Synchronous" }, { "textRaw": "Handling events only once", "name": "handling_events_only_once", "desc": "

When a listener is registered using the eventEmitter.on() method, that\nlistener will be invoked every time the named event is emitted.\n\n

\n
const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.on('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n  // Prints: 1\nmyEmitter.emit('event');\n  // Prints: 2
\n

Using the eventEmitter.once() method, it is possible to register a listener\nthat is immediately unregistered after it is called.\n\n

\n
const myEmitter = new MyEmitter();\nvar m = 0;\nmyEmitter.once('event', () => {\n  console.log(++m);\n});\nmyEmitter.emit('event');\n  // Prints: 1\nmyEmitter.emit('event');\n  // Ignored
\n", "type": "module", "displayName": "Handling events only once" }, { "textRaw": "Error events", "name": "error_events", "desc": "

When an error occurs within an EventEmitter instance, the typical action is\nfor an 'error' event to be emitted. These are treated as a special case\nwithin Node.js.\n\n

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

\n
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n  // Throws and crashes Node.js
\n

To guard against crashing the Node.js process, developers can either register\na listener for the process.on('uncaughtException') event or use the\n[domain][] module (Note, however, that the domain module has been\ndeprecated).\n\n

\n
const myEmitter = new MyEmitter();\n\nprocess.on('uncaughtException', (err) => {\n  console.log('whoops! there was an error');\n});\n\nmyEmitter.emit('error', new Error('whoops!'));\n  // Prints: whoops! there was an error
\n

As a best practice, developers should always register listeners for the\n'error' event:\n\n

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('error', (err) => {\n  console.log('whoops! there was an error');\n});\nmyEmitter.emit('error', new Error('whoops!'));\n  // Prints: whoops! there was an error
\n", "type": "module", "displayName": "Error events" } ], "classes": [ { "textRaw": "Class: EventEmitter", "type": "class", "name": "EventEmitter", "desc": "

The EventEmitter class is defined and exposed by the events module:\n\n

\n
const EventEmitter = require('events');
\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when a listener is removed.\n\n

\n", "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "params": [], "desc": "

The EventEmitter instance will emit it's own 'newListener' event before\na listener is added to it's internal array of listeners.\n\n

\n

Listeners registered for the 'newListener' event will be passed the event\nname and a reference to the listener being added.\n\n

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

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

The 'removeListener' event is emitted after a listener is removed.\n\n

\n" } ], "methods": [ { "textRaw": "EventEmitter.listenerCount(emitter, eventName)", "type": "method", "name": "listenerCount", "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\n

\n
const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n  // Prints: 2
\n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "eventName" } ] } ] }, { "textRaw": "emitter.addListener(eventName, listener)", "type": "method", "name": "addListener", "desc": "

Alias for emitter.on(eventName, listener).\n\n

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.emit(eventName[, arg1][, arg2][, ...])", "type": "method", "name": "emit", "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\n

\n

Returns true if the event had listeners, false otherwise.\n\n

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "emitter.getMaxListeners()", "type": "method", "name": "getMaxListeners", "desc": "

Returns the current max listener value for the EventEmitter which is either\nset by [emitter.setMaxListeners(n)][] or defaults to\n[EventEmitter.defaultMaxListeners][].\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "emitter.listenerCount(eventName)", "type": "method", "name": "listenerCount", "signatures": [ { "params": [ { "textRaw": "`eventName` {Value} The name of the event being listened for ", "name": "eventName", "type": "Value", "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\n

\n" }, { "textRaw": "emitter.listeners(eventName)", "type": "method", "name": "listeners", "desc": "

Returns a copy of the array of listeners for the event named eventName.\n\n

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n  // Prints: [ [Function] ]
\n", "signatures": [ { "params": [ { "name": "eventName" } ] } ] }, { "textRaw": "emitter.on(eventName, listener)", "type": "method", "name": "on", "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\n

\n
server.on('connection', (stream) => {\n  console.log('someone connected!');\n});
\n

Returns a reference to the EventEmitter so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.once(eventName, listener)", "type": "method", "name": "once", "desc": "

Adds a one time listener function for the event named eventName. This\nlistener is invoked only the next time eventName is triggered, after which\nit is removed.\n\n

\n
server.once('connection', (stream) => {\n  console.log('Ah, we have our first user!');\n});
\n

Returns a reference to the EventEmitter so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeAllListeners([eventName])", "type": "method", "name": "removeAllListeners", "desc": "

Removes all listeners, or those of the specified eventName.\n\n

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

\n

Returns a reference to the EventEmitter so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "eventName", "optional": true } ] } ] }, { "textRaw": "emitter.removeListener(eventName, listener)", "type": "method", "name": "removeListener", "desc": "

Removes the specified listener from the listener array for the event named\neventName.\n\n

\n
var callback = (stream) => {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
\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\n

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

\n
const myEmitter = new MyEmitter();\n\nvar callbackA = () => {\n  console.log('A');\n  myEmitter.removeListener('event', callbackB);\n};\n\nvar 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

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 will means that any copies of the listener array as returned by\nthe emitter.listeners() method will need to be recreated.\n\n

\n

Returns a reference to the EventEmitter so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "eventName" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "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)\nfor to indicate an unlimited number of listeners.\n\n

\n

Returns a reference to the EventEmitter so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "n" } ] } ] } ], "properties": [ { "textRaw": "EventEmitter.defaultMaxListeners", "name": "defaultMaxListeners", "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\n

\n

Take caution when setting the EventEmitter.defaultMaxListeners because the\nchange effects all EventEmitter instances, including those created before\nthe change is made. However, calling [emitter.setMaxListeners(n)][] still has\nprecedence over EventEmitter.defaultMaxListeners.\n\n

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

\n
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n  // do stuff\n  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});
\n" } ] } ] }, { "textRaw": "File System", "name": "fs", "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\n

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

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

\n

Here is an example of the asynchronous version:\n\n

\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

Here is the synchronous version:\n\n

\n
const fs = require('fs');\n\nfs.unlinkSync('/tmp/hello');\nconsole.log('successfully deleted /tmp/hello');
\n

With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

\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

It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

\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

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

\n

The relative path to a filename can be used. Remember, however, that this path\nwill be relative to process.cwd().\n\n

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

\n
$ cat script.js\nfunction bad() {\n  require('fs').readFile('/');\n}\nbad();\n\n$ env NODE_DEBUG=fs node script.js\nfs.js:66\n        throw err;\n              ^\nError: EISDIR, read\n    at rethrow (fs.js:61:21)\n    at maybeCallback (fs.js:79:42)\n    at Object.fs.readFile (fs.js:153:18)\n    at bad (/path/to/script.js:2:17)\n    at Object.<anonymous> (/path/to/script.js:5:1)\n    <etc.>
\n", "classes": [ { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "

Objects returned from fs.watch() are of this type.\n\n

\n", "events": [ { "textRaw": "Event: 'change'", "type": "event", "name": "change", "params": [], "desc": "

Emitted when something changes in a watched directory or file.\nSee more details in [fs.watch()][].\n\n

\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when an error occurs.\n\n

\n" } ], "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "desc": "

Stop watching for changes on the given fs.FSWatcher.\n\n

\n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: fs.ReadStream", "type": "class", "name": "fs.ReadStream", "desc": "

ReadStream is a [Readable Stream][].\n\n

\n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

Emitted when the ReadStream's file is opened.\n\n

\n" } ], "properties": [ { "textRaw": "readStream.path", "name": "path", "desc": "

The path to the file the stream is reading from.\n\n

\n" } ] }, { "textRaw": "Class: fs.Stats", "type": "class", "name": "fs.Stats", "desc": "

Objects returned from [fs.stat()][], [fs.lstat()][] and [fs.fstat()][] and their\nsynchronous counterparts are of this type.\n\n

\n\n

For a regular file [util.inspect(stats)][] would return a string very\nsimilar to this:\n\n

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

Please note that atime, mtime, birthtime, and ctime are\ninstances of [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most general\nuses [getTime()][MDN-Date-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][MDN-Date]\npage.\n\n

\n", "modules": [ { "textRaw": "Stat Time Values", "name": "stat_time_values", "desc": "

The times in the stat object have the following semantics:\n\n

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

\n", "type": "module", "displayName": "Stat Time Values" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "desc": "

WriteStream is a [Writable Stream][].\n\n

\n", "events": [ { "textRaw": "Event: 'open'", "type": "event", "name": "open", "params": [], "desc": "

Emitted when the WriteStream's file is opened.\n\n

\n" } ], "properties": [ { "textRaw": "writeStream.bytesWritten", "name": "bytesWritten", "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

\n" }, { "textRaw": "writeStream.path", "name": "path", "desc": "

The path to the file the stream is writing to.\n\n

\n" } ] } ], "methods": [ { "textRaw": "fs.access(path[, mode], callback)", "type": "method", "name": "access", "desc": "

Tests a user's permissions for the file specified by path. mode is an\noptional integer that specifies the accessibility checks to be performed. The\nfollowing constants define the possible values of mode. It is possible to\ncreate a mask consisting of the bitwise OR of two or more values.\n\n

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

\n
fs.access('/etc/passwd', fs.R_OK | fs.W_OK, (err) => {\n  console.log(err ? 'no access!' : 'can read/write');\n});
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.accessSync(path[, mode])", "type": "method", "name": "accessSync", "desc": "

Synchronous version of [fs.access()][]. This throws if any accessibility checks\nfail, and does nothing otherwise.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.appendFile(file, data[, options], callback)", "type": "method", "name": "appendFile", "signatures": [ { "params": [ { "textRaw": "`file` {String|Number} filename or file descriptor ", "name": "file", "type": "String|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` {Number} default = `0o666` ", "name": "mode", "type": "Number", "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} ", "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\n

\n

Example:\n\n

\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

If options is a string, then it specifies the encoding. Example:\n\n

\n
fs.appendFile('message.txt', 'data to append', 'utf8', callback);
\n

Any specified file descriptor has to have been opened for appending.\n\n

\n

Note: Specified file descriptors will not be closed automatically.\n\n

\n" }, { "textRaw": "fs.appendFileSync(file, data[, options])", "type": "method", "name": "appendFileSync", "desc": "

The synchronous version of [fs.appendFile()][]. Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.chmod(path, mode, callback)", "type": "method", "name": "chmod", "desc": "

Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "desc": "

Synchronous chmod(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.chown(path, uid, gid, callback)", "type": "method", "name": "chown", "desc": "

Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "desc": "

Synchronous chown(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.close(fd, callback)", "type": "method", "name": "close", "desc": "

Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "desc": "

Synchronous close(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.createReadStream(path[, options])", "type": "method", "name": "createReadStream", "desc": "

Returns a new [ReadStream][] object. (See [Readable Stream][]).\n\n

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

\n

options is an object or string with the following defaults:\n\n

\n
{\n  flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0o666,\n  autoClose: true\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 at 0. The encoding can be any one of those accepted by [Buffer][].\n\n

\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 emitted.\nNote that fd should be blocking; non-blocking fds should be passed to\n[net.Socket][].\n\n

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

\n

mode sets the file mode (permission and sticky bits), but only if the\nfile was created.\n\n

\n

An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

\n
fs.createReadStream('sample.txt', {start: 90, end: 99});
\n

If options is a string, then it specifies the encoding.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.createWriteStream(path[, options])", "type": "method", "name": "createWriteStream", "desc": "

Returns a new [WriteStream][] object. (See [Writable Stream][]).\n\n

\n

options is an object or string with the following defaults:\n\n

\n
{\n  flags: 'w',\n  defaultEncoding: 'utf8',\n  fd: null,\n  mode: 0o666,\n  autoClose: true\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 [Buffer][].\n\n

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

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

\n

If options is a string, then it specifies the encoding.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.exists(path, callback)", "type": "method", "name": "exists", "stability": 0, "stabilityText": "Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.", "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\n

\n
fs.exists('/etc/passwd', (exists) => {\n  console.log(exists ? 'it\\'s there' : 'no passwd!');\n});
\n

fs.exists() should not be used to check if a file exists before calling\nfs.open(). Doing so introduces a race condition since other processes may\nchange the file's state between the two calls. Instead, user code should\ncall fs.open() directly and handle the error raised if the file is\nnon-existent.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "stability": 0, "stabilityText": "Deprecated: Use [`fs.statSync()`][] or [`fs.accessSync()`][] instead.", "desc": "

Synchronous version of [fs.exists()][].\nReturns true if the file exists, false otherwise.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.fchmod(fd, mode, callback)", "type": "method", "name": "fchmod", "desc": "

Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "desc": "

Synchronous fchmod(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.fchown(fd, uid, gid, callback)", "type": "method", "name": "fchown", "desc": "

Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "desc": "

Synchronous fchown(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.fdatasync(fd, callback)", "type": "method", "name": "fdatasync", "desc": "

Asynchronous fdatasync(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fdatasyncSync(fd)", "type": "method", "name": "fdatasyncSync", "desc": "

Synchronous fdatasync(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.fstat(fd, callback)", "type": "method", "name": "fstat", "desc": "

Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to [stat()][], except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fstatSync(fd)", "type": "method", "name": "fstatSync", "desc": "

Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.fsync(fd, callback)", "type": "method", "name": "fsync", "desc": "

Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "desc": "

Synchronous fsync(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.ftruncate(fd, len, callback)", "type": "method", "name": "ftruncate", "desc": "

Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "desc": "

Synchronous ftruncate(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" } ] } ] }, { "textRaw": "fs.futimes(fd, atime, mtime, callback)", "type": "method", "name": "futimes", "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "desc": "

Synchronous version of [fs.futimes()][]. Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.lchmod(path, mode, callback)", "type": "method", "name": "lchmod", "desc": "

Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n

Only available on Mac OS X.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "desc": "

Synchronous lchmod(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.lchown(path, uid, gid, callback)", "type": "method", "name": "lchown", "desc": "

Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "desc": "

Synchronous lchown(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.link(srcpath, dstpath, callback)", "type": "method", "name": "link", "desc": "

Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.linkSync(srcpath, dstpath)", "type": "method", "name": "linkSync", "desc": "

Synchronous link(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" } ] } ] }, { "textRaw": "fs.lstat(path, callback)", "type": "method", "name": "lstat", "desc": "

Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lstatSync(path)", "type": "method", "name": "lstatSync", "desc": "

Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.mkdir(path[, mode], callback)", "type": "method", "name": "mkdir", "desc": "

Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0o777.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.mkdirSync(path[, mode])", "type": "method", "name": "mkdirSync", "desc": "

Synchronous mkdir(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.mkdtemp(prefix, callback)", "type": "method", "name": "mkdtemp", "desc": "

Creates a unique temporary directory.\n\n

\n

Generates six random characters to be appended behind a required\nprefix to create a unique temporary directory.\n\n

\n

The created folder path is passed as a string to the callback's second\nparameter.\n\n

\n

Example:\n\n

\n
fs.mkdtemp('/tmp/foo-', (err, folder) => {\n  console.log(folder);\n    // Prints: /tmp/foo-itXde2\n});
\n", "signatures": [ { "params": [ { "name": "prefix" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.mkdtempSync(template)", "type": "method", "name": "mkdtempSync", "desc": "

The synchronous version of [fs.mkdtemp()][]. Returns the created\nfolder path.\n\n

\n", "signatures": [ { "params": [ { "name": "template" } ] } ] }, { "textRaw": "fs.open(path, flags[, mode], callback)", "type": "method", "name": "open", "desc": "

Asynchronous file open. See open(2). flags can be:\n\n

\n\n

mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666, readable and writable.\n\n

\n

The callback gets two arguments (err, fd).\n\n

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

\n

flags can also be a number as documented by open(2); commonly used constants\nare available from require('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\n

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

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.openSync(path, flags[, mode])", "type": "method", "name": "openSync", "desc": "

Synchronous version of [fs.open()][]. Returns an integer representing the file\ndescriptor.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.read(fd, buffer, offset, length, position, callback)", "type": "method", "name": "read", "desc": "

Read data from the file specified by fd.\n\n

\n

buffer is the buffer that the data will be written to.\n\n

\n

offset is the offset in the buffer to start writing at.\n\n

\n

length is an integer specifying the number of bytes to read.\n\n

\n

position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

\n

The callback is given the three arguments, (err, bytesRead, buffer).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readdir(path, callback)", "type": "method", "name": "readdir", "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\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readdirSync(path)", "type": "method", "name": "readdirSync", "desc": "

Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.readFile(file[, options], callback)", "type": "method", "name": "readFile", "signatures": [ { "params": [ { "textRaw": "`file` {String | Integer} filename or file descriptor ", "name": "file", "type": "String | 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} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "file" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously reads the entire contents of a file. Example:\n\n

\n
fs.readFile('/etc/passwd', (err, data) => {\n  if (err) throw err;\n  console.log(data);\n});
\n

The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

\n

If no encoding is specified, then the raw buffer is returned.\n\n

\n

If options is a string, then it specifies the encoding. Example:\n\n

\n
fs.readFile('/etc/passwd', 'utf8', callback);
\n

Any specified file descriptor has to support reading.\n\n

\n

Note: Specified file descriptors will not be closed automatically.\n\n

\n" }, { "textRaw": "fs.readFileSync(file[, options])", "type": "method", "name": "readFileSync", "desc": "

Synchronous version of [fs.readFile][]. Returns the contents of the file.\n\n

\n

If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.\n\n

\n", "signatures": [ { "params": [ { "name": "file" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.readlink(path, callback)", "type": "method", "name": "readlink", "desc": "

Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readlinkSync(path)", "type": "method", "name": "readlinkSync", "desc": "

Synchronous readlink(2). Returns the symbolic link's string value.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path[, cache], callback)", "type": "method", "name": "realpath", "desc": "

Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

\n

Example:\n\n

\n
var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, (err, resolvedPath) => {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readSync(fd, buffer, offset, length, position)", "type": "method", "name": "readSync", "desc": "

Synchronous version of [fs.read()][]. Returns the number of bytesRead.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.realpathSync(path[, cache])", "type": "method", "name": "realpathSync", "desc": "

Synchronous realpath(2). Returns the resolved path. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true } ] } ] }, { "textRaw": "fs.rename(oldPath, newPath, callback)", "type": "method", "name": "rename", "desc": "

Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "desc": "

Synchronous rename(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ] }, { "textRaw": "fs.rmdir(path, callback)", "type": "method", "name": "rmdir", "desc": "

Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "desc": "

Synchronous rmdir(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.stat(path, callback)", "type": "method", "name": "stat", "desc": "

Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a [fs.Stats][] object. See the [fs.Stats][] section for more\ninformation.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.statSync(path)", "type": "method", "name": "statSync", "desc": "

Synchronous stat(2). Returns an instance of [fs.Stats][].\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.symlink(target, path[, type], callback)", "type": "method", "name": "symlink", "desc": "

Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\nThe type argument can be set to 'dir', 'file', or 'junction' (default\nis 'file') and is only available on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the target argument will automatically be normalized to absolute path.\n\n

\n

Here is an example below:\n\n

\n
fs.symlink('./foo', './new-port');
\n

It creates a symbolic link named "new-port" that points to "foo".\n\n

\n", "signatures": [ { "params": [ { "name": "target" }, { "name": "path" }, { "name": "type", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.symlinkSync(target, path[, type])", "type": "method", "name": "symlinkSync", "desc": "

Synchronous symlink(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "target" }, { "name": "path" }, { "name": "type", "optional": true } ] } ] }, { "textRaw": "fs.truncate(path, len, callback)", "type": "method", "name": "truncate", "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\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.truncateSync(path, len)", "type": "method", "name": "truncateSync", "desc": "

Synchronous truncate(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" } ] } ] }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "desc": "

Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "desc": "

Synchronous unlink(2). Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.unwatchFile(filename[, listener])", "type": "method", "name": "unwatchFile", "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\n

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

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

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.utimes(path, atime, mtime, callback)", "type": "method", "name": "utimes", "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n

Note: the arguments atime and mtime of the following related functions does\nfollow the below rules:\n\n

\n\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.utimesSync(path, atime, mtime)", "type": "method", "name": "utimesSync", "desc": "

Synchronous version of [fs.utimes()][]. Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.watch(filename[, options][, listener])", "type": "method", "name": "watch", "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a [fs.FSWatcher][].\n\n

\n

The second argument is optional. The options if provided should be an object.\nThe supported boolean members are persistent and recursive. persistent\nindicates whether the process should continue to run as long as files are being\nwatched. recursive indicates whether all subdirectories should be watched, or\nonly the current directory. This applies when a directory is specified, and only\non supported platforms (See [Caveats][]).\n\n

\n

The default is { persistent: true, recursive: false }.\n\n

\n

The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

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

\n

The recursive option is only supported on OS X and Windows.\n\n

\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

\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 on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

\n

You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

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

\n
fs.watch('somedir', (event, filename) => {\n  console.log(`event is: ${event}`);\n  if (filename) {\n    console.log(`filename provided: ${filename}`);\n  } else {\n    console.log('filename not provided');\n  }\n});
\n" } ] } ], "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.watchFile(filename[, options], listener)", "type": "method", "name": "watchFile", "desc": "

Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

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

\n

The listener gets two arguments the current stat object and the previous\nstat object:\n\n

\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

These stat objects are instances of fs.Stat.\n\n

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

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

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

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener" } ] } ] }, { "textRaw": "fs.write(fd, buffer, offset, length[, position], callback)", "type": "method", "name": "write", "desc": "

Write buffer to the file specified by fd.\n\n

\n

offset and length determine the part of the buffer to be written.\n\n

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

\n

The callback will be given three arguments (err, written, buffer) where\nwritten specifies how many bytes were written from buffer.\n\n

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

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

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.write(fd, data[, position[, encoding]], callback)", "type": "method", "name": "write", "desc": "

Write data to the file specified by fd. If data is not a Buffer instance\nthen the value will be coerced to a string.\n\n

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

\n

encoding is the expected string encoding.\n\n

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

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

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

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

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "data" }, { "name": "position" }, { "name": "encoding", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.writeFile(file, data[, options], callback)", "type": "method", "name": "writeFile", "signatures": [ { "params": [ { "textRaw": "`file` {String | Integer} filename or file descriptor ", "name": "file", "type": "String | 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` {Number} default = `0o666` ", "name": "mode", "type": "Number", "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} ", "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\n

\n

The encoding option is ignored if data is a buffer. It defaults\nto 'utf8'.\n\n

\n

Example:\n\n

\n
fs.writeFile('message.txt', 'Hello Node.js', (err) => {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
\n

If options is a string, then it specifies the encoding. Example:\n\n

\n
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
\n

Any specified file descriptor has to support writing.\n\n

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

\n

Note: Specified file descriptors will not be closed automatically.\n\n

\n" }, { "textRaw": "fs.writeFileSync(file, data[, options])", "type": "method", "name": "writeFileSync", "desc": "

The synchronous version of [fs.writeFile()][]. Returns undefined.\n\n

\n", "signatures": [ { "params": [ { "name": "file" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.writeSync(fd, buffer, offset, length[, position])", "type": "method", "name": "writeSync", "desc": "

Synchronous versions of [fs.write()][]. Returns the number of bytes written.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "data" }, { "name": "position" }, { "name": "encoding", "optional": true } ] }, { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position", "optional": true } ] } ] }, { "textRaw": "fs.writeSync(fd, data[, position[, encoding]])", "type": "method", "name": "writeSync", "desc": "

Synchronous versions of [fs.write()][]. Returns the number of bytes written.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "data" }, { "name": "position" }, { "name": "encoding", "optional": true } ] } ] } ], "type": "module", "displayName": "fs" }, { "textRaw": "HTTP", "name": "http", "stability": 2, "stabilityText": "Stable", "desc": "

To use the HTTP server and client one must require('http').\n\n

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

\n

HTTP message headers are represented by an object like this:\n\n

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'host': 'mysite.com',\n  'accept': '*/*' }
\n

Keys are lowercased. Values are not modified.\n\n

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

\n

See [message.headers][] for details on how duplicate headers are handled.\n\n

\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

\n
[ 'ConTent-Length', '123456',\n  'content-LENGTH', '123',\n  'content-type', 'text/plain',\n  'CONNECTION', 'keep-alive',\n  'Host', 'mysite.com',\n  'accepT', '*/*' ]
\n", "classes": [ { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "desc": "

The HTTP Agent is used for pooling sockets used in HTTP client\nrequests.\n\n

\n

The HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a\nsocket to become free the socket is closed. This means that Node.js's\npool has the benefit of keep-alive when under load but still does not\nrequire developers to manually close the HTTP clients using\nKeepAlive.\n\n

\n

If you opt into using HTTP KeepAlive, you can create an Agent object\nwith that flag set to true. (See the [constructor options][].)\nThen, the Agent will keep unused sockets in a pool for later use. They\nwill be explicitly marked so as to not keep the Node.js process running.\nHowever, it is still a good idea to explicitly [destroy()][] KeepAlive\nagents when they are no longer in use, so that the Sockets will be shut\ndown.\n\n

\n

Sockets are removed from the agent's pool when the socket emits either\na 'close' event or a special '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\n

\n
http.get(options, (res) => {\n  // Do stuff\n}).on('socket', (socket) => {\n  socket.emit('agentRemove');\n});
\n

Alternatively, you could just opt out of pooling entirely using\nagent:false:\n\n

\n
http.get({\n  hostname: 'localhost',\n  port: 80,\n  path: '/',\n  agent: false  // create a new agent just for this one request\n}, (res) => {\n  // Do stuff with response\n})
\n", "methods": [ { "textRaw": "agent.createConnection(options[, callback])", "type": "method", "name": "createConnection", "desc": "

Produces a socket/stream to be used for HTTP requests.\n\n

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

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

\n

callback has a signature of (err, stream).\n\n

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "agent.destroy()", "type": "method", "name": "destroy", "desc": "

Destroy any sockets that are currently in use by the agent.\n\n

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "agent.getName(options)", "type": "method", "name": "getName", "desc": "

Get a unique name for a set of request options, to determine whether a\nconnection can be reused. In the http agent, this returns\nhost:port:localAddress. In the https agent, the name includes the\nCA, cert, ciphers, and other HTTPS/TLS-specific options that determine\nsocket reusability.\n\n

\n", "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "properties": [ { "textRaw": "agent.freeSockets", "name": "freeSockets", "desc": "

An object which contains arrays of sockets currently awaiting use by\nthe Agent when HTTP KeepAlive is used. Do not modify.\n\n

\n" }, { "textRaw": "agent.maxFreeSockets", "name": "maxFreeSockets", "desc": "

By default set to 256. For Agents supporting HTTP KeepAlive, this\nsets the maximum number of sockets that will be left open in the free\nstate.\n\n

\n" }, { "textRaw": "agent.maxSockets", "name": "maxSockets", "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\n

\n" }, { "textRaw": "agent.requests", "name": "requests", "desc": "

An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.\n\n

\n" }, { "textRaw": "agent.sockets", "name": "sockets", "desc": "

An object which contains arrays of sockets currently in use by the\nAgent. Do not modify.\n\n

\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 in a pool to be used by other requests in the future. Default = `false` ", "name": "keepAlive", "type": "Boolean", "desc": "Keep sockets around in a pool to be used by other requests in the future. Default = `false`" }, { "textRaw": "`keepAliveMsecs` {Integer} When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = `1000`. Only relevant if `keepAlive` is set to `true`. ", "name": "keepAliveMsecs", "type": "Integer", "desc": "When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = `1000`. Only relevant if `keepAlive` is set to `true`." }, { "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\n

\n

To configure any of them, you must create your own [http.Agent][] object.\n\n

\n
const http = require('http');\nvar keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);
\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\n

\n

To configure any of them, you must create your own [http.Agent][] object.\n\n

\n
const http = require('http');\nvar keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);
\n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "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\n

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

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.\n\n

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

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

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'abort'", "type": "event", "name": "abort", "desc": "

function () { }\n\n

\n

Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().\n\n

\n", "params": [] }, { "textRaw": "Event: 'checkExpectation'", "type": "event", "name": "checkExpectation", "desc": "

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect header is received, where the\nvalue is not 100-continue. If this event isn't listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.\n\n

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the 'connect' event.\n\n

\n
const http = require('http');\nconst net = require('net');\nconst url = require('url');\n\n// Create an HTTP tunneling proxy\nvar 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  var srvUrl = url.parse(`http://${req.url}`);\n  var 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  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    method: 'CONNECT',\n    path: 'www.google.com:80'\n  };\n\n  var 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", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "desc": "

function () { }\n\n

\n

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

\n", "params": [] }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "desc": "

function (response) { }\n\n

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of [http.IncomingMessage][].\n\n

\n

Options:\n\n

\n\n", "params": [] }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "desc": "

function (socket) { }\n\n

\n

Emitted after a socket is assigned to this request.\n\n

\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the 'upgrade' event.\n\n

\n
const http = require('http');\n\n// Create an HTTP server\nvar 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  var options = {\n    port: 1337,\n    hostname: '127.0.0.1',\n    headers: {\n      'Connection': 'Upgrade',\n      'Upgrade': 'websocket'\n    }\n  };\n\n  var 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", "params": [] } ], "methods": [ { "textRaw": "request.abort()", "type": "method", "name": "abort", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.end([data][, encoding][, callback])", "type": "method", "name": "end", "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\n

\n

If data is specified, it is equivalent to calling\n[response.write(data, encoding)][] followed by request.end(callback).\n\n

\n

If callback is specified, it will be called when the request stream\nis finished.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.flushHeaders()", "type": "method", "name": "flushHeaders", "desc": "

Flush the request headers.\n\n

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

\n

That's usually what you want (it saves a TCP round-trip) but not when the first\ndata isn't sent until possibly much later. request.flushHeaders() lets you bypass\nthe optimization and kickstart the request.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable][, initialDelay])", "type": "method", "name": "setSocketKeepAlive", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "request.setTimeout(timeout[, callback])", "type": "method", "name": "setTimeout", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

\n\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "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\n

\n

The chunk argument should be a [Buffer][] or a string.\n\n

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n

\n

The callback argument is optional and will be called when this chunk of data\nis flushed.\n\n

\n

Returns request.\n\n

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] } ] }, { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "desc": "

This class inherits from [net.Server][] and has the following additional events:\n\n

\n", "events": [ { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "desc": "

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

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

\n

Note that when this event is emitted and handled, the 'request' event will\nnot be emitted.\n\n

\n", "params": [] }, { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

function (exception, socket) { }\n\n

\n

If a client connection emits an 'error' event, it will be forwarded here.\n\n

\n

socket is the [net.Socket][] object that the error originated from.\n\n

\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Emitted when the server closes.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

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

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "desc": "

function (socket) { }\n\n

\n

When a new TCP stream is established. socket is an object of type\n[net.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\n

\n", "params": [] }, { "textRaw": "Event: 'request'", "type": "event", "name": "request", "desc": "

function (request, response) { }\n\n

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of [http.IncomingMessage][] and response is\nan instance of [http.ServerResponse][].\n\n

\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

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

\n", "params": [] } ], "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle[, callback])", "type": "method", "name": "listen", "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\n

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

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen()][].\n\n

\n

Returns server.\n\n

\n" }, { "textRaw": "server.listen(path[, callback])", "type": "method", "name": "listen", "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen(path)][].\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(port[, hostname][, backlog][, callback])", "type": "method", "name": "listen", "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. A\nport value of zero will assign a random port.\n\n

\n

To listen to a unix socket, supply a filename instead of port and hostname.\n\n

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

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event. See also [net.Server.listen(port)][].\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "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\n

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

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

\n

Returns server.\n\n

\n" } ], "properties": [ { "textRaw": "server.listening", "name": "listening", "desc": "

A Boolean indicating whether or not the server is listening for\nconnections.\n\n

\n" }, { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n

\n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "type": "Number", "name": "timeout", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.\n\n

\n

Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.\n\n

\n

Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.\n\n

\n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

\n

The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Indicates that the underlying connection was terminated before\n[response.end()][] was called or able to flush.\n\n

\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

function () { }\n\n

\n

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

\n

After this event, no more events will be emitted on the response object.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

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

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

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});\nresponse.end();
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.\n\n

\n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data][, encoding][, callback])", "type": "method", "name": "end", "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\n

\n

If data is specified, it is equivalent to calling\n[response.write(data, encoding)][] followed by response.end(callback).\n\n

\n

If callback is specified, it will be called when the response stream\nis finished.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

\n

Example:\n\n

\n
var contentType = response.getHeader('content-type');
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "desc": "

Removes a header that's queued for implicit sending.\n\n

\n

Example:\n\n

\n
response.removeHeader('Content-Encoding');
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "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\n

\n

Example:\n\n

\n
response.setHeader('Content-Type', 'text/html');
\n

or\n\n

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.\n\n

\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\n[response.writeHead()][] given precedence.\n\n

\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", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "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\n

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

\n

Returns response.\n\n

\n" }, { "textRaw": "response.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "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\n

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

\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'. The last parameter callback\nwill be called when this chunk of data is flushed.\n\n

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

\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\n[response.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\n

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

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode[, statusMessage][, headers])", "type": "method", "name": "writeHead", "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\n

\n

Example:\n\n

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
\n

This method must only be called once on a message and it must\nbe called before [response.end()][] is called.\n\n

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

\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\n[response.writeHead()][] given precedence.\n\n

\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

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

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a [TypeError][] being thrown.\n\n

\n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "statusMessage", "optional": true }, { "name": "headers", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.finished", "name": "finished", "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After [response.end()][] executes, the value will be true.\n\n

\n" }, { "textRaw": "response.headersSent", "name": "headersSent", "desc": "

Boolean (read-only). True if headers were sent, false otherwise.\n\n

\n" }, { "textRaw": "response.sendDate", "name": "sendDate", "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\n

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

\n" }, { "textRaw": "response.statusCode", "name": "statusCode", "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\n

\n

Example:\n\n

\n
response.statusCode = 404;
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

\n" }, { "textRaw": "response.statusMessage", "name": "statusMessage", "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\n

\n

Example:\n\n

\n
response.statusMessage = 'Not found';
\n

After response header was sent to the client, this property indicates the\nstatus message which was sent out.\n\n

\n" } ] }, { "textRaw": "Class: http.IncomingMessage", "type": "class", "name": "http.IncomingMessage", "desc": "

An IncomingMessage object is created by [http.Server][] or\n[http.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\n

\n

It implements the [Readable Stream][] interface, as well as the\nfollowing additional events, methods, and properties.\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () { }\n\n

\n

Indicates that the underlying connection was closed.\nJust like 'end', this event occurs only once per response.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "message.headers", "name": "headers", "desc": "

The request/response headers object.\n\n

\n

Key-value pairs of header names and values. Header names are lower-cased.\nExample:\n\n

\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

Duplicates in raw headers are handled in the following ways, depending on the\nheader name:\n\n

\n\n" }, { "textRaw": "message.httpVersion", "name": "httpVersion", "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\n

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.\n\n

\n" }, { "textRaw": "message.method", "name": "method", "desc": "

Only valid for request obtained from [http.Server][].\n\n

\n

The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n

\n" }, { "textRaw": "message.rawHeaders", "name": "rawHeaders", "desc": "

The raw request/response headers list exactly as they were received.\n\n

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

\n

Header names are not lowercased, and duplicates are not merged.\n\n

\n
// Prints something like:\n//\n// [ 'user-agent',\n//   'this is invalid because there can be only one',\n//   'User-Agent',\n//   'curl/7.22.0',\n//   'Host',\n//   '127.0.0.1:8000',\n//   'ACCEPT',\n//   '*/*' ]\nconsole.log(request.rawHeaders);
\n" }, { "textRaw": "message.rawTrailers", "name": "rawTrailers", "desc": "

The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.\n\n

\n" }, { "textRaw": "message.statusCode", "name": "statusCode", "desc": "

Only valid for response obtained from [http.ClientRequest][].\n\n

\n

The 3-digit HTTP response status code. E.G. 404.\n\n

\n" }, { "textRaw": "message.statusMessage", "name": "statusMessage", "desc": "

Only valid for response obtained from [http.ClientRequest][].\n\n

\n

The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.\n\n

\n" }, { "textRaw": "message.socket", "name": "socket", "desc": "

The [net.Socket][] object associated with the connection.\n\n

\n

With HTTPS support, use [request.socket.getPeerCertificate()][] to obtain the\nclient's authentication details.\n\n

\n" }, { "textRaw": "message.trailers", "name": "trailers", "desc": "

The request/response trailers object. Only populated at the 'end' event.\n\n

\n" }, { "textRaw": "message.url", "name": "url", "desc": "

Only valid for request obtained from [http.Server][].\n\n

\n

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\n

Then request.url will be:\n\n

\n
'/status?name=ryan'
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

\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

If you would like to extract the params 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\n

\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" } ], "methods": [ { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "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\n

\n

Returns message.\n\n

\n" } ] } ], "properties": [ { "textRaw": "`METHODS` {Array} ", "type": "Array", "name": "METHODS", "desc": "

A list of the HTTP methods that are supported by the parser.\n\n

\n" }, { "textRaw": "`STATUS_CODES` {Object} ", "type": "Object", "name": "STATUS_CODES", "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\n

\n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.\n\n

\n" } ], "methods": [ { "textRaw": "http.createClient([port][, host])", "type": "method", "name": "createClient", "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\n

\n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "

Returns a new instance of [http.Server][].\n\n

\n

The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

\n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.get(options[, callback])", "type": "method", "name": "get", "desc": "

Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and [http.request()][]\nis that it sets the method to GET and calls req.end() automatically.\n\n

\n

Example:\n\n

\n
http.get('http://www.google.com/index.html', (res) => {\n  console.log(`Got response: ${res.statusCode}`);\n  // consume response body\n  res.resume();\n}).on('error', (e) => {\n  console.log(`Got error: ${e.message}`);\n});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "http.request(options[, callback])", "type": "method", "name": "request", "desc": "

Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Options:\n\n

\n\n

The optional callback parameter will be added as a one time listener for\nthe 'response' event.\n\n

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

\n

Example:\n\n

\n
var postData = querystring.stringify({\n  'msg' : 'Hello World!'\n});\n\nvar 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': postData.length\n  }\n};\n\nvar 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

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

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

\n

There are a few special headers that should be noted.\n\n

\n\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] } ], "type": "module", "displayName": "HTTP" }, { "textRaw": "HTTPS", "name": "https", "stability": 2, "stabilityText": "Stable", "desc": "

HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.\n\n

\n", "classes": [ { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "desc": "

An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n

\n" }, { "textRaw": "Class: https.Server", "type": "class", "name": "https.Server", "desc": "

This class is a subclass of tls.Server and emits events same as\n[http.Server][]. See [http.Server][] for more information.\n\n

\n", "methods": [ { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "desc": "

See [http.Server#setTimeout()][].\n\n

\n", "signatures": [ { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "server.timeout", "name": "timeout", "desc": "

See [http.Server#timeout][].\n\n

\n" } ] } ], "methods": [ { "textRaw": "https.createServer(options[, requestListener])", "type": "method", "name": "createServer", "desc": "

Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

\n

Example:\n\n

\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

Or\n\n

\n
const https = require('https');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, (req, res) => {\n  res.writeHead(200);\n  res.end('hello world\\n');\n}).listen(8000);
\n", "methods": [ { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

See [http.close()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path[, callback])", "type": "method", "name": "listen", "desc": "

See [http.listen()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(port[, host][, backlog][, callback])", "type": "method", "name": "listen", "desc": "

See [http.listen()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "options" }, { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "https.get(options, callback)", "type": "method", "name": "get", "desc": "

Like [http.get()][] but for HTTPS.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Example:\n\n

\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", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "https.request(options, callback)", "type": "method", "name": "request", "desc": "

Makes a request to a secure web server.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

All options from [http.request()][] are valid.\n\n

\n

Example:\n\n

\n
const https = require('https');\n\nvar options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET'\n};\n\nvar 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});\nreq.end();\n\nreq.on('error', (e) => {\n  console.error(e);\n});
\n

The options argument has the following options\n\n

\n\n

The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

\n\n

In order to specify these options, use a custom [Agent][].\n\n

\n

Example:\n\n

\n
var 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\nvar req = https.request(options, (res) => {\n  ...\n}
\n

Alternatively, opt out of connection pooling by not using an Agent.\n\n

\n

Example:\n\n

\n
var 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\nvar req = https.request(options, (res) => {\n  ...\n}
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "https.globalAgent", "name": "globalAgent", "desc": "

Global instance of [https.Agent][] for all HTTPS client requests.\n\n

\n" } ], "type": "module", "displayName": "HTTPS" }, { "textRaw": "Modules", "name": "module", "stability": 3, "stabilityText": "Locked", "desc": "

Node.js has a simple module loading system. In Node.js, files and modules are\nin one-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

\n

The contents of foo.js:\n\n

\n
const circle = require('./circle.js');\nconsole.log( `The area of a circle of radius 4 is ${circle.area(4)}`);
\n

The contents of circle.js:\n\n

\n
const PI = Math.PI;\n\nexports.area = (r) => PI * r * r;\n\nexports.circumference = (r) => 2 * PI * r;
\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\n

\n

Variables local to the module will be private, as though the module was wrapped\nin a function. In this example the variable PI is private to circle.js.\n\n

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

\n

Below, bar.js makes use of the square module, which exports a constructor:\n\n

\n
const square = require('./square.js');\nvar mySquare = square(2);\nconsole.log(`The area of my square is ${mySquare.area()}`);
\n

The square module is defined in square.js:\n\n

\n
// assigning to exports will not modify module, must use module.exports\nmodule.exports = (width) => {\n  return {\n    area: () => width * width\n  };\n}
\n

The module system is implemented in the require("module") module.\n\n

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

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

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

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

\n

Below we give a suggested directory structure that could work:\n\n

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

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

\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

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

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

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

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

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

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

\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 './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. 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_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)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n4. If X/index.node is a file, load X/index.node as binary addon.  STOP\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   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n5. return DIRS
\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\n

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

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

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

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

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

\n

The core modules are defined within Node.js's source and are located in the\nlib/ folder.\n\n

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

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

\n

Consider this situation:\n\n

\n

a.js:\n\n

\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

b.js:\n\n

\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

main.js:\n\n

\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

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

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

\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

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

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

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

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

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

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

\n

If the given path does not exist, require() will throw an [Error][] with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

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

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

\n
{ "name" : "some-library",\n  "main" : "./lib/some-library.js" }
\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\n

\n

This is the extent of Node.js's awareness of package.json files.\n\n

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

\n
Error: Cannot find module 'some-library'
\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

\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 native module,\nand does not begin with '/', '../', or './', then Node.js starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location. Node will not append\nnode_modules to a path already ending in node_modules.\n\n

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

\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

\n\n

This allows programs to localize their dependencies, so that they do not\nclash.\n\n

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

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

\n

NODE_PATH was originally created to support loading modules from\nvarying paths before the current [module resolution][] algorithm was frozen.\n\n

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

\n

Additionally, Node.js will search in the following locations:\n\n

\n\n

Where $HOME is the user's home directory, and $PREFIX is Node.js's\nconfigured node_prefix.\n\n

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

\n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "type": "var", "desc": "

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 isn't actually\na global but rather local to each module.\n\n

\n", "properties": [ { "textRaw": "`children` {Array} ", "type": "Array", "name": "children", "desc": "

The module objects required by this one.\n\n

\n" }, { "textRaw": "`exports` {Object} ", "type": "Object", "name": "exports", "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\n

\n

For example suppose we were making a module called a.js\n\n

\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

Then in another file we could do\n\n

\n
const a = require('./a');\na.on('ready', () => {\n  console.log('module a is ready');\n});
\n

Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

\n

x.js:\n\n

\n
setTimeout(() => {\n  module.exports = { a: 'hello' };\n}, 0);
\n

y.js:\n\n

\n
const x = require('./x');\nconsole.log(x.a);
\n", "modules": [ { "textRaw": "exports alias", "name": "exports_alias", "desc": "

The exports variable that is available within a module starts as a reference\nto module.exports. As with any variable, if you assign a new value to it, it\nis no longer bound to the previous value.\n\n

\n

To illustrate the behavior, imagine this hypothetical implementation of\nrequire():\n\n

\n
function require(...) {\n  // ...\n  ((module, exports) => {\n    // Your module code here\n    exports = some_func;        // re-assigns exports, exports is no longer\n                                // a shortcut, and nothing is exported.\n    module.exports = some_func; // makes your module export 0\n  })(module, module.exports);\n  return module;\n}
\n

As a guideline, if the relationship between exports and module.exports\nseems like magic to you, ignore exports and only use module.exports.\n\n

\n", "type": "module", "displayName": "exports alias" } ] }, { "textRaw": "`filename` {String} ", "type": "String", "name": "filename", "desc": "

The fully resolved filename to the module.\n\n

\n" }, { "textRaw": "`id` {String} ", "type": "String", "name": "id", "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.\n\n

\n" }, { "textRaw": "`loaded` {Boolean} ", "type": "Boolean", "name": "loaded", "desc": "

Whether or not the module is done loading, or is in the process of\nloading.\n\n

\n" }, { "textRaw": "`parent` {Object} Module object ", "type": "Object", "name": "parent", "desc": "

The module that first required this one.\n\n

\n", "shortDesc": "Module object" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "signatures": [ { "return": { "textRaw": "Return: {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\n

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

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

\n", "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "desc": "

This class is used to create a TCP or local server.\n\n

\n

net.Server is an [EventEmitter][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "params": [], "desc": "

Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when an error occurs. The ['close'][] event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "desc": "

Emitted when the server has been bound after calling server.listen.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n

Example:\n\n

\n
var 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  address = server.address();\n  console.log('opened server on %j', address);\n});
\n

Don't call server.address() until the 'listening' event has been emitted.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "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\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.getConnections(callback)", "type": "method", "name": "getConnections", "desc": "

Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.\n\n

\n

Callback should take two arguments err and count.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "server.listen(handle[, backlog][, callback])", "type": "method", "name": "listen", "signatures": [ { "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\n

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

\n

Listening on a file descriptor is not supported on Windows.\n\n

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

\n

The parameter backlog behaves the same as in\n[server.listen(port[, hostname][, backlog][, callback])][server.listen(port, host, backlog, callback)].\n\n

\n" }, { "textRaw": "server.listen(options[, callback])", "type": "method", "name": "listen", "signatures": [ { "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\n[server.listen(port[, hostname][, backlog][, callback])][server.listen(port, host, backlog, callback)].\nAlternatively, the path option can be used to specify a UNIX socket.\n\n

\n

If exclusive is false (default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive is true, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.\n\n

\n
server.listen({\n  host: 'localhost',\n  port: 80,\n  exclusive: true\n});
\n" }, { "textRaw": "server.listen(path[, backlog][, callback])", "type": "method", "name": "listen", "signatures": [ { "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\n

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

\n

On UNIX, the local domain is usually known as the UNIX domain. The path is a\nfilesystem path name. It is subject to the same naming conventions and\npermissions checks as would be done on file creation, will be visible in the\nfilesystem, and will persist until unlinked.\n\n

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

\n
net.createServer().listen(\n    path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'))
\n

The parameter backlog behaves the same as in\n[server.listen(port[, hostname][, backlog][, callback])][server.listen(port, host, backlog, callback)].\n\n

\n" }, { "textRaw": "server.listen(port[, hostname][, backlog][, callback])", "type": "method", "name": "listen", "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. A\nport value of zero will assign a random port.\n\n

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

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

\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. This can be done with\n\n

\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

(Note: All sockets in Node.js set SO_REUSEADDR already)\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.ref()", "type": "method", "name": "ref", "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\n

\n

Returns server.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.unref()", "type": "method", "name": "unref", "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\n

\n

Returns server.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "stability": 0, "stabilityText": "Deprecated: Use [`server.getConnections()`][] instead.", "desc": "

The number of concurrent connections on the server.\n\n

\n

This becomes null when sending a socket to a child with\n[child_process.fork()][]. To poll forks and get current number of active\nconnections use asynchronous server.getConnections instead.\n\n

\n" }, { "textRaw": "server.listening", "name": "listening", "desc": "

A Boolean indicating whether or not the server is listening for\nconnections.\n\n

\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.\n\n

\n

It is not recommended to use this option once a socket has been sent to a child\nwith [child_process.fork()][].\n\n

\n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "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\n

\n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "desc": "

Construct a new socket object.\n\n

\n

options is an object with the following defaults:\n\n

\n
{\n  fd: null,\n  allowHalfOpen: false,\n  readable: false,\n  writable: false\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 createServer() and 'end' event.\n\n

\n

net.Socket instances are [EventEmitter][] with the following events:\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.connect(options[, connectListener])", "type": "method", "name": "connect", "desc": "

Opens the connection for a given socket.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n\n

For local domain sockets, options argument should be an object which\nspecifies:\n\n

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

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

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path[, connectListener])", "type": "method", "name": "connect", "desc": "

As [socket.connect(options\\[, connectListener\\])][socket.connect(options, connectListener)],\nwith options either as either {port: port, host: host} or {path: path}.\n\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", "desc": "

As [socket.connect(options\\[, connectListener\\])][socket.connect(options, connectListener)],\nwith options either as either {port: port, host: host} or {path: path}.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.destroy()", "type": "method", "name": "destroy", "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.end([data][, encoding])", "type": "method", "name": "end", "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.pause()", "type": "method", "name": "pause", "desc": "

Pauses the reading of data. That is, ['data'][] events will not be emitted.\nUseful to throttle back an upload.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.ref()", "type": "method", "name": "ref", "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\n

\n

Returns socket.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.resume()", "type": "method", "name": "resume", "desc": "

Resumes reading after a call to [pause()][].\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "

Set the encoding for the socket as a [Readable Stream][]. See\n[stream.setEncoding()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.setKeepAlive([enable][, initialDelay])", "type": "method", "name": "setKeepAlive", "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\n

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

\n

Returns socket.\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "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\n

\n

Returns socket.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "socket.setTimeout(timeout[, callback])", "type": "method", "name": "setTimeout", "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

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

\n

If timeout is 0, then the existing idle timeout is disabled.\n\n

\n

The optional callback parameter will be added as a one time listener for the\n['timeout'][] event.\n\n

\n

Returns socket.\n\n

\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "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\n

\n

Returns socket.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.write(data[, encoding][, callback])", "type": "method", "name": "write", "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

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

\n

The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] } ], "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "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\n

\n" }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "desc": "

Emitted when a socket connection is successfully established.\nSee [connect()][].\n\n

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

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

\n" }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

\n

See also: the return values of socket.write()\n\n

\n", "params": [] }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

Emitted when the other end of the socket sends a FIN packet.\n\n

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

\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

\n" }, { "textRaw": "Event: 'lookup'", "type": "event", "name": "lookup", "desc": "

Emitted after resolving the hostname but before connecting.\nNot applicable to UNIX sockets.\n\n

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

\n

See also: [socket.setTimeout()][]\n\n

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

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

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with [pause()][] and [resume()][].\n\n

\n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "desc": "

The amount of received bytes.\n\n

\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "

The amount of bytes sent.\n\n

\n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "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\n

\n" }, { "textRaw": "socket.localPort", "name": "localPort", "desc": "

The numeric representation of the local port. For example,\n80 or 21.\n\n

\n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "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\n

\n" }, { "textRaw": "socket.remoteFamily", "name": "remoteFamily", "desc": "

The string representation of the remote IP family. 'IPv4' or 'IPv6'.\n\n

\n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example,\n80 or 21.\n\n

\n" } ] } ], "methods": [ { "textRaw": "net.connect(options[, connectListener])", "type": "method", "name": "connect", "desc": "

A factory function, which returns a new [net.Socket][] and automatically\nconnects with the supplied options.\n\n

\n

The options are passed to both the [net.Socket][] constructor and the\n[socket.connect][] method.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n

Here is an example of a client of the previously described echo server:\n\n

\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

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
const client = net.connect({path: '/tmp/echo.sock'});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path[, connectListener])", "type": "method", "name": "connect", "desc": "

A factory function, which returns a new unix [net.Socket][] and automatically\nconnects to the supplied path.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port[, host][, connectListener])", "type": "method", "name": "connect", "desc": "

A factory function, which returns a new [net.Socket][] and automatically\nconnects to the supplied port and host.\n\n

\n

If host is omitted, 'localhost' will be assumed.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options[, connectListener])", "type": "method", "name": "createConnection", "desc": "

A factory function, which returns a new [net.Socket][] and automatically\nconnects with the supplied options.\n\n

\n

The options are passed to both the [net.Socket][] constructor and the\n[socket.connect][] method.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n

Here is an example of a client of the previously described echo server:\n\n

\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

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
const client = net.connect({path: '/tmp/echo.sock'});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path[, connectListener])", "type": "method", "name": "createConnection", "desc": "

A factory function, which returns a new unix [net.Socket][] and automatically\nconnects to the supplied path.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port[, host][, connectListener])", "type": "method", "name": "createConnection", "desc": "

A factory function, which returns a new [net.Socket][] and automatically\nconnects to the supplied port and host.\n\n

\n

If host is omitted, 'localhost' will be assumed.\n\n

\n

The connectListener parameter will be added as a listener for the\n['connect'][] event once.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createServer([options][, connectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

\n

options is an object with the following defaults:\n\n

\n
{\n  allowHalfOpen: false,\n  pauseOnConnect: false\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\n

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

\n

Here is an example of an echo server which listens for connections\non port 8124:\n\n

\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

Test this by using telnet:\n\n

\n
telnet localhost 8124
\n

To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

\n
server.listen('/tmp/echo.sock', () => {\n  console.log('server bound');\n});
\n

Use nc to connect to a UNIX domain socket server:\n\n

\n
nc -U /tmp/echo.sock
\n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "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\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "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", "stability": 2, "stabilityText": "Stable", "desc": "

Provides a few basic operating-system related utility functions.\n\n

\n

Use require('os') to access this module.\n\n

\n", "properties": [ { "textRaw": "os.EOL", "name": "EOL", "desc": "

A constant defining the appropriate End-of-line marker for the operating\nsystem.\n\n

\n" } ], "methods": [ { "textRaw": "os.arch()", "type": "method", "name": "arch", "desc": "

Returns the operating system CPU architecture. Possible values are 'x64',\n'arm' and 'ia32'. Returns the value of [process.arch][].\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.cpus()", "type": "method", "name": "cpus", "desc": "

Returns an array of objects containing information about each CPU/core\ninstalled: model, speed (in MHz), and times (an object containing the number of\nmilliseconds the CPU/core spent in: user, nice, sys, idle, and irq).\n\n

\n

Example inspection of os.cpus:\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  { 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  { 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  { 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  { 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  { 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  { 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  { 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

Note that since nice values are UNIX centric in Windows the nice values of\nall processors are always 0.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.endianness()", "type": "method", "name": "endianness", "desc": "

Returns the endianness of the CPU. Possible values are 'BE' for big endian\nor 'LE' for little endian.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.freemem()", "type": "method", "name": "freemem", "desc": "

Returns the amount of free system memory in bytes.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.homedir()", "type": "method", "name": "homedir", "desc": "

Returns the home directory of the current user.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.hostname()", "type": "method", "name": "hostname", "desc": "

Returns the hostname of the operating system.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.loadavg()", "type": "method", "name": "loadavg", "desc": "

Returns an array containing the 1, 5, and 15 minute load averages.\n\n

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

\n

The load average is a very UNIX-y concept; there is no real equivalent on\nWindows platforms. That is why this function always returns [0, 0, 0] on\nWindows.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.networkInterfaces()", "type": "method", "name": "networkInterfaces", "desc": "

Get a list of network interfaces:\n\n

\n
{ lo:\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     { 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  eth0:\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     { 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

Note that due to the underlying implementation this will only return network\ninterfaces that have been assigned an address.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.platform()", "type": "method", "name": "platform", "desc": "

Returns the operating system platform. Possible values are 'darwin',\n'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of\n[process.platform][].\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.release()", "type": "method", "name": "release", "desc": "

Returns the operating system release.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.tmpdir()", "type": "method", "name": "tmpdir", "desc": "

Returns the operating system's default directory for temporary files.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.totalmem()", "type": "method", "name": "totalmem", "desc": "

Returns the total amount of system memory in bytes.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.type()", "type": "method", "name": "type", "desc": "

Returns the operating system name. For example 'Linux' on Linux, 'Darwin'\non OS X and 'Windows_NT' on Windows.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.uptime()", "type": "method", "name": "uptime", "desc": "

Returns the system uptime in seconds.\n\n

\n", "signatures": [ { "params": [] } ] } ], "type": "module", "displayName": "OS" }, { "textRaw": "Path", "name": "path", "stability": 2, "stabilityText": "Stable", "desc": "

This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

\n

Use require('path') to use this module. The following methods are provided:\n\n

\n", "methods": [ { "textRaw": "path.basename(p[, ext])", "type": "method", "name": "basename", "desc": "

Return the last portion of a path. Similar to the Unix basename command.\n\n

\n

Example:\n\n

\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", "signatures": [ { "params": [ { "name": "p" }, { "name": "ext", "optional": true } ] } ] }, { "textRaw": "path.dirname(p)", "type": "method", "name": "dirname", "desc": "

Return the directory name of a path. Similar to the Unix dirname command.\n\n

\n

Example:\n\n

\n
path.dirname('/foo/bar/baz/asdf/quux')\n// returns '/foo/bar/baz/asdf'
\n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.extname(p)", "type": "method", "name": "extname", "desc": "

Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

\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", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.format(pathObject)", "type": "method", "name": "format", "desc": "

Returns a path string from an object. This is the opposite of [path.parse][].\n\n

\n

If pathObject has dir and base properties, the returned string will\nbe a concatenation of the dir property, the platform-dependent path separator,\nand the base property.\n\n

\n

If the dir property is not supplied, the root property will be used as the\ndir property. However, it will be assumed that the root property already\nends with the platform-dependent path separator. In this case, the returned\nstring will be the concatenation fo the root property and the base property.\n\n

\n

If both the dir and the root properties are not supplied, then the returned\nstring will be the contents of the base property.\n\n

\n

If the base property is not supplied, a concatenation of the name property\nand the ext property will be used as the base property.\n\n

\n

An example on Posix systems:\n\n

\n
path.format({\n    root : "/",\n    dir : "/home/user/dir",\n    base : "file.txt",\n    ext : ".txt",\n    name : "file"\n});\n// returns '/home/user/dir/file.txt'
\n

An example on Windows:\n\n

\n
path.format({\n    root : "C:\\\\",\n    dir : "C:\\\\path\\\\dir",\n    base : "file.txt",\n    ext : ".txt",\n    name : "file"\n})\n// returns 'C:\\\\path\\\\dir\\\\file.txt'
\n", "signatures": [ { "params": [ { "name": "pathObject" } ] } ] }, { "textRaw": "path.isAbsolute(path)", "type": "method", "name": "isAbsolute", "desc": "

Determines whether path is an absolute path. An absolute path will always\nresolve to the same location, regardless of the working directory.\n\n

\n

Posix examples:\n\n

\n
path.isAbsolute('/foo/bar') // true\npath.isAbsolute('/baz/..')  // true\npath.isAbsolute('qux/')     // false\npath.isAbsolute('.')        // false
\n

Windows examples:\n\n

\n
path.isAbsolute('//server')  // true\npath.isAbsolute('C:/foo/..') // true\npath.isAbsolute('bar\\\\baz')  // false\npath.isAbsolute('.')         // false
\n

Note: If the path string passed as parameter is a zero-length string, unlike\n other path module functions, it will be used as-is and false will be\n returned.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "path.join([path1][, path2][, ...])", "type": "method", "name": "join", "desc": "

Join all arguments together and normalize the resulting path.\n\n

\n

Arguments must be strings. In v0.8, non-string arguments were\nsilently ignored. In v0.10 and up, an exception is thrown.\n\n

\n

Example:\n\n

\n
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// throws exception\nTypeError: Arguments to path.join must be strings
\n

Note: If the arguments to join have zero-length strings, unlike other path\n module functions, they will be ignored. If the joined path string is a\n zero-length string then '.' will be returned, which represents the\n current working directory.\n\n

\n", "signatures": [ { "params": [ { "name": "path1", "optional": true }, { "name": "path2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "path.normalize(p)", "type": "method", "name": "normalize", "desc": "

Normalize a string path, taking care of '..' and '.' parts.\n\n

\n

When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn Windows backslashes are used.\n\n

\n

Example:\n\n

\n
path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns '/foo/bar/baz/asdf'
\n

Note: If the path string passed as argument is a zero-length string then '.'\n will be returned, which represents the current working directory.\n\n

\n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.parse(pathString)", "type": "method", "name": "parse", "desc": "

Returns an object from a path string.\n\n

\n

An example on *nix:\n\n

\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

An example on Windows:\n\n

\n
path.parse('C:\\\\path\\\\dir\\\\index.html')\n// returns\n// {\n//    root : "C:\\\\",\n//    dir : "C:\\\\path\\\\dir",\n//    base : "index.html",\n//    ext : ".html",\n//    name : "index"\n// }
\n", "signatures": [ { "params": [ { "name": "pathString" } ] } ] }, { "textRaw": "path.relative(from, to)", "type": "method", "name": "relative", "desc": "

Solve the relative path from from to to.\n\n

\n

At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

\n
path.resolve(from, path.relative(from, to)) == path.resolve(to)
\n

Examples:\n\n

\n
path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns '..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns '../../impl/bbb'
\n

Note: If the arguments to relative have zero-length strings then the current\n working directory will be used instead of the zero-length strings. If\n both the paths are the same then a zero-length string will be returned.\n\n

\n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] }, { "textRaw": "path.resolve([from ...], to)", "type": "method", "name": "resolve", "desc": "

Resolves to to an absolute path.\n\n

\n

If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path\ngets resolved to the root directory. Non-string from arguments are ignored.\n\n

\n

Another way to think of it is as a sequence of cd commands in a shell.\n\n

\n
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
\n

Is similar to:\n\n

\n
cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
\n

The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

\n

Examples:\n\n

\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 currently in /home/myself/node, it returns\n// '/home/myself/node/wwwroot/static_files/gif/image.gif'
\n

Note: If the arguments to resolve have zero-length strings then the current\n working directory will be used instead of them.\n\n

\n", "signatures": [ { "params": [ { "name": "from ...", "optional": true }, { "name": "to" } ] } ] } ], "properties": [ { "textRaw": "path.delimiter", "name": "delimiter", "desc": "

The platform-specific path delimiter, ; or ':'.\n\n

\n

An example on *nix:\n\n

\n
console.log(process.env.PATH)\n// '/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

An example on Windows:\n\n

\n
console.log(process.env.PATH)\n// 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'\n\nprocess.env.PATH.split(path.delimiter)\n// returns ['C:\\\\Windows\\\\system32', 'C:\\\\Windows', 'C:\\\\Program Files\\\\node\\\\']
\n" }, { "textRaw": "path.posix", "name": "posix", "desc": "

Provide access to aforementioned path methods but always interact in a posix\ncompatible way.\n\n

\n" }, { "textRaw": "path.sep", "name": "sep", "desc": "

The platform-specific file separator. '\\\\' or '/'.\n\n

\n

An example on *nix:\n\n

\n
'foo/bar/baz'.split(path.sep)\n// returns ['foo', 'bar', 'baz']
\n

An example on Windows:\n\n

\n
'foo\\\\bar\\\\baz'.split(path.sep)\n// returns ['foo', 'bar', 'baz']
\n" }, { "textRaw": "path.win32", "name": "win32", "desc": "

Provide access to aforementioned path methods but always interact in a win32\ncompatible way.\n\n

\n" } ], "type": "module", "displayName": "Path" }, { "textRaw": "punycode", "name": "punycode", "stability": 2, "stabilityText": "Stable", "desc": "

[Punycode.js][] is bundled with Node.js v0.6.2+. Use require('punycode') to\naccess it. (To use it with other Node.js versions, use npm to install the\npunycode module first.)\n\n

\n", "methods": [ { "textRaw": "punycode.decode(string)", "type": "method", "name": "decode", "desc": "

Converts a Punycode string of ASCII-only symbols to a string of Unicode symbols.\n\n

\n
// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.encode(string)", "type": "method", "name": "encode", "desc": "

Converts a string of Unicode symbols to a Punycode string of ASCII-only symbols.\n\n

\n
// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.toASCII(domain)", "type": "method", "name": "toASCII", "desc": "

Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

\n
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
\n", "signatures": [ { "params": [ { "name": "domain" } ] } ] }, { "textRaw": "punycode.toUnicode(domain)", "type": "method", "name": "toUnicode", "desc": "

Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

\n
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
\n", "signatures": [ { "params": [ { "name": "domain" } ] } ] } ], "properties": [ { "textRaw": "punycode.ucs2", "name": "ucs2", "modules": [ { "textRaw": "punycode.ucs2.decode(string)", "name": "punycode.ucs2.decode(string)", "desc": "

Creates an array containing the numeric code point values of each Unicode\nsymbol in the string. While [JavaScript uses UCS-2 internally][], this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

\n
punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
\n", "type": "module", "displayName": "punycode.ucs2.decode(string)" }, { "textRaw": "punycode.ucs2.encode(codePoints)", "name": "punycode.ucs2.encode(codepoints)", "desc": "

Creates a string based on an array of numeric code point values.\n\n

\n
punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
\n", "type": "module", "displayName": "punycode.ucs2.encode(codePoints)" } ] }, { "textRaw": "punycode.version", "name": "version", "desc": "

A string representing the current Punycode.js version number.\n\n

\n" } ], "type": "module", "displayName": "punycode" }, { "textRaw": "Query String", "name": "querystring", "stability": 2, "stabilityText": "Stable", "desc": "

This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

\n", "properties": [ { "textRaw": "querystring.escape", "name": "escape", "desc": "

The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

\n" }, { "textRaw": "querystring.unescape", "name": "unescape", "desc": "

The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n\n

\n

It will try to use decodeURIComponent in the first place,\nbut if that fails it falls back to a safer equivalent that\ndoesn't throw on malformed URLs.\n\n

\n" } ], "methods": [ { "textRaw": "querystring.parse(str[, sep][, eq][, options])", "type": "method", "name": "parse", "desc": "

Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

\n

Options object may contain decodeURIComponent property (querystring.unescape by default),\nit can be used to decode a non-utf8 encoding string if necessary.\n\n

\n

Example:\n\n

\n
querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' }\n\n// Suppose gbkDecodeURIComponent function already exists,\n// it can decode `gbk` encoding string\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n  { decodeURIComponent: gbkDecodeURIComponent })\n// returns { w: '中文', foo: 'bar' }
\n", "signatures": [ { "params": [ { "name": "str" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "querystring.stringify(obj[, sep][, eq][, options])", "type": "method", "name": "stringify", "desc": "

Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Options object may contain encodeURIComponent property (querystring.escape by default),\nit can be used to encode string with non-utf8 encoding if necessary.\n\n

\n

Example:\n\n

\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// Suppose gbkEncodeURIComponent function already exists,\n// it can encode string with `gbk` encoding\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n  { encodeURIComponent: gbkEncodeURIComponent })\n// returns 'w=%D6%D0%CE%C4&foo=bar'
\n", "signatures": [ { "params": [ { "name": "obj" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "querystring" }, { "textRaw": "Readline", "name": "readline", "stability": 2, "stabilityText": "Stable", "desc": "

To use this module, do require('readline'). Readline allows reading of a\nstream (such as [process.stdin][]) on a line-by-line basis.\n\n

\n

Note that once you've invoked this module, your Node.js program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

\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", "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "desc": "

The class that represents a readline interface with an input and output\nstream.\n\n

\n", "methods": [ { "textRaw": "rl.close()", "type": "method", "name": "close", "desc": "

Closes the Interface instance, relinquishing control on the input and\noutput streams. The 'close' event will also be emitted.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "desc": "

Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

\n

Note that this doesn't immediately pause the stream of events. Several events may\nbe emitted after calling pause, including line.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "desc": "

Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

\n

This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

\n

If output is set to null or undefined when calling createInterface, the\nprompt is not written.\n\n

\n", "signatures": [ { "params": [ { "name": "preserveCursor", "optional": true } ] } ] }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "desc": "

Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

\n

This will also resume the input stream used with createInterface if\nit has been paused.\n\n

\n

If output is set to null or undefined when calling createInterface,\nnothing is displayed.\n\n

\n

Example usage:\n\n

\n
rl.question('What is your favorite food?', (answer) => {\n  console.log(`Oh, so your favorite food is ${answer}`);\n});
\n", "signatures": [ { "params": [ { "name": "query" }, { "name": "callback" } ] } ] }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "desc": "

Resumes the readline input stream.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.setPrompt(prompt)", "type": "method", "name": "setPrompt", "desc": "

Sets the prompt, for example when you run node on the command line, you see\n> , which is Node.js's prompt.\n\n

\n", "signatures": [ { "params": [ { "name": "prompt" } ] } ] }, { "textRaw": "rl.write(data[, key])", "type": "method", "name": "write", "desc": "

Writes data to output stream, unless output is set to null or\nundefined when calling createInterface. key is an object literal to\nrepresent a key sequence; available if the terminal is a TTY.\n\n

\n

This will also resume the input stream if it has been paused.\n\n

\n

Example:\n\n

\n
rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "key", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "Events", "name": "events", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () {}\n\n

\n

Emitted when close() is called.\n\n

\n

Also emitted when the input stream receives its 'end' event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

\n

This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

\n", "params": [] }, { "textRaw": "Event: 'line'", "type": "event", "name": "line", "desc": "

function (line) {}\n\n

\n

Emitted whenever the input stream receives an end of line (\\n, \\r, or\n\\r\\n), usually received when the user hits enter, or return. This is a good\nhook to listen for user input.\n\n

\n

Example of listening for 'line':\n\n

\n
rl.on('line', (cmd) => {\n  console.log(`You just typed: ${cmd}`);\n});
\n", "params": [] }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is paused.\n\n

\n

Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

\n

Example of listening for 'pause':\n\n

\n
rl.on('pause', () => {\n  console.log('Readline paused.');\n});
\n", "params": [] }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is resumed.\n\n

\n

Example of listening for 'resume':\n\n

\n
rl.on('resume', () => {\n  console.log('Readline resumed.');\n});
\n", "params": [] }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

\n

Example of listening for SIGCONT:\n\n

\n
rl.on('SIGCONT', () => {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
\n", "params": [] }, { "textRaw": "Event: 'SIGINT'", "type": "event", "name": "SIGINT", "desc": "

function () {}\n\n

\n

Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

\n

Example of listening for SIGINT:\n\n

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

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

\n

When the program is resumed with fg, the 'pause' and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

\n

The 'pause' and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

\n

Example of listening for SIGTSTP:\n\n

\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

Example: Tiny CLI

\n

Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

\n
const readline = require('readline');\nconst rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\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

Example: Read File Stream Line-by-Line

\n

A common case for readline's input option is to pass a filesystem readable\nstream to it. This is how one could craft line-by-line parsing of a file:\n\n

\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", "params": [] } ], "type": "module", "displayName": "Events" } ], "methods": [ { "textRaw": "readline.clearLine(stream, dir)", "type": "method", "name": "clearLine", "desc": "

Clears current line of given TTY stream in a specified direction.\ndir should have one of following values:\n\n

\n\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "dir" } ] } ] }, { "textRaw": "readline.clearScreenDown(stream)", "type": "method", "name": "clearScreenDown", "desc": "

Clears the screen from the current position of the cursor down.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" } ] } ] }, { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "desc": "

Creates a readline Interface instance. Accepts an options Object that takes\nthe following values:\n\n

\n\n

The completer function is given the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

\n
    \n
  1. An Array with matching entries for the completion.

    \n
  2. \n
  3. The substring that was used for the matching.

    \n
  4. \n
\n

Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

\n

Example:\n\n

\n
function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter((c) => { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
\n

Also completer can be run in async mode if it accepts two arguments:\n\n

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
\n

createInterface is commonly used with [process.stdin][] and\n[process.stdout][] in order to accept user input:\n\n

\n
const readline = require('readline');\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
\n

Once you have a readline instance, you most commonly listen for the\n'line' event.\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 fires\na 'resize' event on the output if/when the columns ever change\n([process.stdout][] does this automatically when it is a TTY).\n\n

\n", "signatures": [ { "params": [ { "name": "options" } ] } ] }, { "textRaw": "readline.cursorTo(stream, x, y)", "type": "method", "name": "cursorTo", "desc": "

Move cursor to the specified position in a given TTY stream.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "x" }, { "name": "y" } ] } ] }, { "textRaw": "readline.moveCursor(stream, dx, dy)", "type": "method", "name": "moveCursor", "desc": "

Move cursor relative to it's current position in a given TTY stream.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "dx" }, { "name": "dy" } ] } ] } ], "type": "module", "displayName": "Readline" }, { "textRaw": "REPL", "name": "repl", "stability": 2, "stabilityText": "Stable", "desc": "

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

\n

By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

\n
$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n...   console.log(v);\n...   });\n1\n2\n3
\n

For advanced line-editors, start Node.js with the environmental 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\n

\n

For example, you could add this to your bashrc file:\n\n

\n
alias node="env NODE_NO_READLINE=1 rlwrap node"
\n", "modules": [ { "textRaw": "Environment Variable Options", "name": "environment_variable_options", "desc": "

The built-in repl (invoked by running node or node -i) may be controlled\nvia the following environment variables:\n\n

\n\n", "type": "module", "displayName": "Environment Variable Options" }, { "textRaw": "Persistent History", "name": "persistent_history", "desc": "

By default, the REPL will persist history between node REPL sessions by saving\nto a .node_repl_history file in the user's home directory. This can be\ndisabled by setting the environment variable NODE_REPL_HISTORY="".\n\n

\n", "modules": [ { "textRaw": "NODE_REPL_HISTORY_FILE", "name": "node_repl_history_file", "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 your REPL history will\nautomatically be converted to using plain text. The new file will be saved to\neither your home directory, or a directory defined by the NODE_REPL_HISTORY\nvariable, as documented here.\n\n

\n", "type": "module", "displayName": "NODE_REPL_HISTORY_FILE" } ], "type": "module", "displayName": "Persistent History" } ], "miscs": [ { "textRaw": "REPL Features", "name": "REPL Features", "type": "misc", "desc": "

Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

\n

Core modules will be loaded on-demand into the environment. For example,\naccessing fs will require() the fs module as global.fs.\n\n

\n

The special variable _ (underscore) contains the result of the last expression.\n\n

\n
> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
\n

The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

\n
// repl_test.js\nconst repl = require('repl');\nvar msg = 'message';\n\nrepl.start('> ').context.m = msg;
\n

Things in the context object appear as local within the REPL:\n\n

\n
$ node repl_test.js\n> m\n'message'
\n

There are a few special REPL commands:\n\n

\n\n

The following key combinations in the REPL have these special effects:\n\n

\n\n", "miscs": [ { "textRaw": "Customizing Object displays in the REPL", "name": "customizing_object_displays_in_the_repl", "desc": "

The REPL module internally uses\n[util.inspect()][], when printing values. However, util.inspect delegates the\n call to the object's inspect() function, if it has one. You can read more\n about this delegation [here][].\n\n

\n

For example, if you have defined an inspect() function on an object, like this:\n\n

\n
> var obj = {foo: 'this will not show up in the inspect() output'};\nundefined\n> obj.inspect = () => {\n...   return {bar: 'baz'};\n... };\n[Function]
\n

and try to print obj in REPL, it will invoke the custom inspect() function:\n\n

\n
> obj\n{bar: 'baz'}
\n", "type": "misc", "displayName": "Customizing Object displays in the REPL" } ] } ], "classes": [ { "textRaw": "Class: REPLServer", "type": "class", "name": "REPLServer", "desc": "

This inherits from [Readline Interface][] with the following events:\n\n

\n", "events": [ { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

function () {}\n\n

\n

Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal 'end' on the input stream.\n\n

\n

Example of listening for exit:\n\n

\n
replServer.on('exit', () => {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
\n", "params": [] }, { "textRaw": "Event: 'reset'", "type": "event", "name": "reset", "desc": "

function (context) {}\n\n

\n

Emitted when the REPL's context is reset. This happens when you type .clear.\nIf you start the repl with { useGlobal: true } then this event will never\nbe emitted.\n\n

\n

Example of listening for reset:\n\n

\n
// Extend the initial repl context.\nvar replServer = repl.start({ options ... });\nsomeExtension.extend(r.context);\n\n// When a new context is created extend it as well.\nreplServer.on('reset', (context) => {\n  console.log('repl has a new context');\n  someExtension.extend(context);\n});
\n", "params": [] } ], "methods": [ { "textRaw": "replServer.defineCommand(keyword, cmd)", "type": "method", "name": "defineCommand", "signatures": [ { "params": [ { "textRaw": "`keyword` {String} ", "name": "keyword", "type": "String" }, { "textRaw": "`cmd` {Object|Function} ", "name": "cmd", "type": "Object|Function" } ] }, { "params": [ { "name": "keyword" }, { "name": "cmd" } ] } ], "desc": "

Makes a command available in the REPL. The command is invoked by typing a .\nfollowed by the keyword. The cmd is an object with the following values:\n\n

\n\n

If a function is provided instead of an object for cmd, it is treated as the\naction.\n\n

\n

Example of defining a command:\n\n

\n
// repl_test.js\nconst repl = require('repl');\n\nvar replServer = repl.start();\nreplServer.defineCommand('sayhello', {\n  help: 'Say hello',\n  action: function(name) {\n    this.write(`Hello, ${name}!\\n`);\n    this.displayPrompt();\n  }\n});
\n

Example of invoking that command from the REPL:\n\n

\n
> .sayhello Node.js User\nHello, Node.js User!
\n" }, { "textRaw": "replServer.displayPrompt([preserveCursor])", "type": "method", "name": "displayPrompt", "signatures": [ { "params": [ { "textRaw": "`preserveCursor` {Boolean} ", "name": "preserveCursor", "type": "Boolean", "optional": true } ] }, { "params": [ { "name": "preserveCursor", "optional": true } ] } ], "desc": "

Like [readline.prompt][] except also adding indents with ellipses when inside\nblocks. The preserveCursor argument is passed to [readline.prompt][]. This is\nused primarily with defineCommand. It's also used internally to render each\nprompt line.\n\n

\n" } ] } ], "methods": [ { "textRaw": "repl.start([options])", "type": "method", "name": "start", "desc": "

Returns and starts a REPLServer instance, that inherits from\n[Readline Interface][]. Accepts an "options" Object that takes\nthe following values:\n\n

\n\n

You can use your own eval function if it has following signature:\n\n

\n
function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
\n

On tab completion, eval will be called with .scope as an input string. It\nis expected to return an array of scope names to be used for the auto-completion.\n\n

\n

Multiple REPLs may be started against the same running instance of Node.js. Each\nwill share the same global object but will have unique I/O.\n\n

\n

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

\n
const net = require('net');\nconst repl = require('repl');\nvar 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

Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

\n

By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running Node.js process without restarting it.\n\n

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

\n

For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "REPL" }, { "textRaw": "Stream", "name": "stream", "stability": 2, "stabilityText": "Stable", "desc": "

A stream is an abstract interface implemented by various objects in\nNode.js. For example a [request to an HTTP server][http-incoming-message] is a\nstream, as is [process.stdout][]. Streams are readable, writable, or both. All\nstreams are instances of [EventEmitter][].\n\n

\n

You can load the Stream base classes by doing require('stream').\nThere are base classes provided for [Readable][] streams, [Writable][]\nstreams, [Duplex][] streams, and [Transform][] streams.\n\n

\n

This document is split up into 3 sections:\n\n

\n
    \n
  1. The first section explains the parts of the API that you need to be\naware of to use streams in your programs.
  2. \n
  3. The second section explains the parts of the API that you need to\nuse if you implement your own custom streams yourself. The API is designed to\nmake this easy for you to do.
  4. \n
  5. The third section goes into more depth about how streams work,\nincluding some of the internal mechanisms and functions that you\nshould probably not modify unless you definitely know what you are\ndoing.
  6. \n
\n", "classes": [ { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces.\n\n

\n

Examples of Duplex streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

\n

A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

\n

Readable streams have two "modes": a flowing mode and a paused\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In paused mode, you\nmust explicitly call [stream.read()][stream-read] to get chunks of data out.\nStreams start out in paused mode.\n\n

\n

Note: If no data event handlers are attached, and there are no\n[stream.pipe()][] destinations, and the stream is switched into flowing\nmode, then data will be lost.\n\n

\n

You can switch to flowing mode by doing any of the following:\n\n

\n\n

You can switch back to paused mode by doing either of the following:\n\n

\n\n

Note that, for backwards compatibility reasons, removing ['data'][]\nevent handlers will not automatically pause the stream. Also, if\nthere are piped destinations, then calling [stream.pause()][stream-pause] will\nnot guarantee that the stream will remain paused once those\ndestinations drain and ask for more data.\n\n

\n

Examples of readable streams include:\n\n

\n\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the stream and any of its underlying resources (a file\ndescriptor, for example) have been closed. The event indicates that\nno more events will be emitted, and no further computation will occur.\n\n

\n

Not all streams will emit the 'close' event.\n\n

\n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

Attaching a 'data' event listener to a stream that has not been\nexplicitly paused will switch the stream into flowing mode. Data will\nthen be passed as soon as it is available.\n\n

\n

If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n});
\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

This event fires when there will be no more data to read.\n\n

\n

Note that the 'end' event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling [stream.read()][stream-read] repeatedly until you get to the\nend.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n});\nreadable.on('end', () => {\n  console.log('there will be no more data.');\n});
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error receiving data.\n\n

\n" }, { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

\n

In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  // there is some data to read now\n});
\n

Once the internal buffer is drained, a 'readable' event will fire\nagain when more data is available.\n\n

\n

The 'readable' event is not emitted in the "flowing" mode with the\nsole exception of the last one, on end-of-stream.\n\n

\n

The 'readable' event indicates that the stream has new information:\neither new data is available or the end of the stream has been reached.\nIn the former case, [stream.read()][stream-read] will return that data. In the\nlatter case, [stream.read()][stream-read] will return null. For instance, in\nthe following example, foo.txt is an empty file:\n\n

\n
const fs = require('fs');\nvar rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n  console.log('readable:', rr.read());\n});\nrr.on('end', () => {\n  console.log('end');\n});
\n

The output of running this script is:\n\n

\n
$ node test.js\nreadable: null\nend
\n", "params": [] } ], "methods": [ { "textRaw": "readable.isPaused()", "type": "method", "name": "isPaused", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [] }, { "params": [] } ], "desc": "

This method returns whether or not the readable has been explicitly\npaused by client code (using [stream.pause()][stream-pause] without a\ncorresponding [stream.resume()][stream-resume]).\n\n

\n
var readable = new stream.Readable\n\nreadable.isPaused() // === false\nreadable.pause()\nreadable.isPaused() // === true\nreadable.resume()\nreadable.isPaused() // === false
\n" }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [] }, { "params": [] } ], "desc": "

This method will cause a stream in flowing mode to stop emitting\n['data'][] events, switching out of flowing mode. Any data that becomes\navailable will remain in the internal buffer.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(() => {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n});
\n" }, { "textRaw": "readable.pipe(destination[, options])", "type": "method", "name": "pipe", "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. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

\n

Multiple destinations can be piped to safely.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
\n

This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

\n
var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
\n

For example, emulating the Unix cat command:\n\n

\n
process.stdin.pipe(process.stdout);
\n

By default [stream.end()][stream-end] is called on the destination when the\nsource stream emits ['end'][], so that destination is no longer writable.\nPass { end: false } as options to keep the destination stream open.\n\n

\n

This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

\n
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});
\n

Note that [process.stderr][] and [process.stdout][] are never closed until\nthe process exits, regardless of the specified options.\n\n

\n" }, { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {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 read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

\n

If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null,\nunless we've ended, in which case it will return the data remaining\nin the buffer.\n\n

\n

If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

\n

This method should only be called in paused mode. In flowing mode,\nthis method is called automatically until the internal buffer is\ndrained.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
\n

If this method returns a data chunk, then it will also trigger the\nemission of a ['data'][] event.\n\n

\n

Note that calling [stream.read([size])][stream-read] after the ['end'][]\nevent has been triggered will return null. No runtime error will be raised.\n\n

\n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [] }, { "params": [] } ], "desc": "

This method will cause the readable stream to resume emitting ['data'][]\nevents.\n\n

\n

This method will switch the stream into flowing mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits ['end'][] event, you can call [stream.resume()][stream-resume] to open\nthe flow of data.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', () => {\n  console.log('got to the end, but did not read anything');\n});
\n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Call this function to cause the stream to return strings of the specified\nencoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be interpreted as\nUTF-8 data, and returned as strings. If you do readable.setEncoding('hex'),\nthen the data will be encoded in hexadecimal string format.\n\n

\n

This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled [buf.toString(encoding)][] on them. If you want to read the data\nas strings, always use this method.\n\n

\n

Also you can disable any encoding at all with readable.setEncoding(null).\nThis approach is very useful if you deal with binary data or with large\nmulti-byte strings spread out over multiple chunks.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n});
\n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "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": "

This method will remove the hooks set up for a previous [stream.pipe()][]\ncall.\n\n

\n

If the destination is not specified, then all pipes are removed.\n\n

\n

If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(() => {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
\n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "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": "

This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

\n

Note that stream.unshift(chunk) cannot be called after the ['end'][] event\nhas been triggered; a runtime error will be raised.\n\n

\n

If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See [API\nfor Stream Implementors][].)\n\n

\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  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\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

Note that, unlike [stream.push(chunk)][stream-push], stream.unshift(chunk)\nwill not end the reading process by resetting the internal reading state of the\nstream. This can cause unexpected results if unshift() is called during a\nread (i.e. from within a [stream._read()][stream-_read] implementation on a\ncustom stream). Following the call to unshift() with an immediate\n[stream.push('')][stream-push] will reset the reading state appropriately,\nhowever it is best to simply avoid calling unshift() while in the process of\nperforming a read.\n\n

\n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "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 Streams API as it is today. (See [Compatibility][] for\nmore information.)\n\n

\n

If you are using an older Node.js library that emits ['data'][] events and\nhas a [stream.pause()][stream-pause] method that is advisory only, then you\ncan use the wrap() method to create a [Readable][] stream that uses the old\nstream as its data source.\n\n

\n

You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node.js programs and libraries.\n\n

\n

For example:\n\n

\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" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces.\n\n

\n

Examples of Transform streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

\n

Examples of writable streams include:\n\n

\n\n", "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

If a [stream.write(chunk)][stream-write] call returns false, then the\n'drain' event will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

\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  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\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", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error when writing or piping data.\n\n

\n" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

When the [stream.end()][stream-end] method has been called, and all data has\nbeen flushed to the underlying system, this event is emitted.\n\n

\n
var writer = getWritableStreamSomehow();\nfor (var 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", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

This is emitted whenever the [stream.pipe()][] method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar 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" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

This is emitted whenever the [stream.unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar 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" } ], "methods": [ { "textRaw": "writable.cork()", "type": "method", "name": "cork", "desc": "

Forces buffering of all writes.\n\n

\n

Buffered data will be flushed either at [stream.uncork()][] or at\n[stream.end()][stream-end] call.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.end([chunk][, encoding][, callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String|Buffer} Optional data to write ", "name": "chunk", "type": "String|Buffer", "desc": "Optional data to write", "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": "

Call this method when no more data will be written to the stream. If supplied,\nthe callback is attached as a listener on the ['finish'][] event.\n\n

\n

Calling [stream.write()][stream-write] after calling\n[stream.end()][stream-end] will raise an error.\n\n

\n
// write 'hello, ' and then end with 'world!'\nvar file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!
\n" }, { "textRaw": "writable.setDefaultEncoding(encoding)", "type": "method", "name": "setDefaultEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The new default encoding ", "name": "encoding", "type": "String", "desc": "The new default encoding" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Sets the default encoding for a writable stream.\n\n

\n" }, { "textRaw": "writable.uncork()", "type": "method", "name": "uncork", "desc": "

Flush all data, buffered since [stream.cork()][] call.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} `true` if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "`true` if the data was handled completely." }, "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": "

This method writes some data to the underlying system, 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 detect write errors, listen for the 'error' event.\n\n

\n

The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

\n

This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe ['drain'][] event before writing more data.\n\n\n

\n" } ] } ], "miscs": [ { "textRaw": "API for Stream Consumers", "name": "API for Stream Consumers", "type": "misc", "desc": "

Streams can be either [Readable][], [Writable][], or both ([Duplex][]).\n\n

\n

All streams are EventEmitters, but they also have other custom methods\nand properties depending on whether they are Readable, Writable, or\nDuplex.\n\n

\n

If a stream is both Readable and Writable, then it implements all of\nthe methods and events. So, a [Duplex][] or [Transform][] stream is\nfully described by this API, though their implementation may be\nsomewhat different.\n\n

\n

It is not necessary to implement Stream interfaces in order to consume\nstreams in your programs. If you are implementing streaming\ninterfaces in your own program, please also refer to\n[API for Stream Implementors][].\n\n

\n

Almost all Node.js programs, no matter how simple, use Streams in some\nway. Here is an example of using Streams in an Node.js program:\n\n

\n
const http = require('http');\n\nvar 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  var body = '';\n  // we want to get the data as utf8 strings\n  // If you don't set an encoding, then you'll get Buffer objects\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 tells you that you have entire body\n  req.on('end', () => {\n    try {\n      var data = JSON.parse(body);\n    } catch (er) {\n      // uh oh!  bad json!\n      res.statusCode = 400;\n      return res.end(`error: ${er.message}`);\n    }\n\n    // write back something interesting to the user:\n    res.write(typeof data);\n    res.end();\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
\n", "classes": [ { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces.\n\n

\n

Examples of Duplex streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

\n

A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

\n

Readable streams have two "modes": a flowing mode and a paused\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In paused mode, you\nmust explicitly call [stream.read()][stream-read] to get chunks of data out.\nStreams start out in paused mode.\n\n

\n

Note: If no data event handlers are attached, and there are no\n[stream.pipe()][] destinations, and the stream is switched into flowing\nmode, then data will be lost.\n\n

\n

You can switch to flowing mode by doing any of the following:\n\n

\n\n

You can switch back to paused mode by doing either of the following:\n\n

\n\n

Note that, for backwards compatibility reasons, removing ['data'][]\nevent handlers will not automatically pause the stream. Also, if\nthere are piped destinations, then calling [stream.pause()][stream-pause] will\nnot guarantee that the stream will remain paused once those\ndestinations drain and ask for more data.\n\n

\n

Examples of readable streams include:\n\n

\n\n", "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the stream and any of its underlying resources (a file\ndescriptor, for example) have been closed. The event indicates that\nno more events will be emitted, and no further computation will occur.\n\n

\n

Not all streams will emit the 'close' event.\n\n

\n", "params": [] }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "params": [], "desc": "

Attaching a 'data' event listener to a stream that has not been\nexplicitly paused will switch the stream into flowing mode. Data will\nthen be passed as soon as it is available.\n\n

\n

If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n});
\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

This event fires when there will be no more data to read.\n\n

\n

Note that the 'end' event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling [stream.read()][stream-read] repeatedly until you get to the\nend.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n});\nreadable.on('end', () => {\n  console.log('there will be no more data.');\n});
\n", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error receiving data.\n\n

\n" }, { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "desc": "

When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

\n

In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  // there is some data to read now\n});
\n

Once the internal buffer is drained, a 'readable' event will fire\nagain when more data is available.\n\n

\n

The 'readable' event is not emitted in the "flowing" mode with the\nsole exception of the last one, on end-of-stream.\n\n

\n

The 'readable' event indicates that the stream has new information:\neither new data is available or the end of the stream has been reached.\nIn the former case, [stream.read()][stream-read] will return that data. In the\nlatter case, [stream.read()][stream-read] will return null. For instance, in\nthe following example, foo.txt is an empty file:\n\n

\n
const fs = require('fs');\nvar rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n  console.log('readable:', rr.read());\n});\nrr.on('end', () => {\n  console.log('end');\n});
\n

The output of running this script is:\n\n

\n
$ node test.js\nreadable: null\nend
\n", "params": [] } ], "methods": [ { "textRaw": "readable.isPaused()", "type": "method", "name": "isPaused", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [] }, { "params": [] } ], "desc": "

This method returns whether or not the readable has been explicitly\npaused by client code (using [stream.pause()][stream-pause] without a\ncorresponding [stream.resume()][stream-resume]).\n\n

\n
var readable = new stream.Readable\n\nreadable.isPaused() // === false\nreadable.pause()\nreadable.isPaused() // === true\nreadable.resume()\nreadable.isPaused() // === false
\n" }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [] }, { "params": [] } ], "desc": "

This method will cause a stream in flowing mode to stop emitting\n['data'][] events, switching out of flowing mode. Any data that becomes\navailable will remain in the internal buffer.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(() => {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n});
\n" }, { "textRaw": "readable.pipe(destination[, options])", "type": "method", "name": "pipe", "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. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

\n

Multiple destinations can be piped to safely.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
\n

This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

\n
var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
\n

For example, emulating the Unix cat command:\n\n

\n
process.stdin.pipe(process.stdout);
\n

By default [stream.end()][stream-end] is called on the destination when the\nsource stream emits ['end'][], so that destination is no longer writable.\nPass { end: false } as options to keep the destination stream open.\n\n

\n

This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

\n
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});
\n

Note that [process.stderr][] and [process.stdout][] are never closed until\nthe process exits, regardless of the specified options.\n\n

\n" }, { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {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 read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

\n

If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null,\nunless we've ended, in which case it will return the data remaining\nin the buffer.\n\n

\n

If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

\n

This method should only be called in paused mode. In flowing mode,\nthis method is called automatically until the internal buffer is\ndrained.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
\n

If this method returns a data chunk, then it will also trigger the\nemission of a ['data'][] event.\n\n

\n

Note that calling [stream.read([size])][stream-read] after the ['end'][]\nevent has been triggered will return null. No runtime error will be raised.\n\n

\n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [] }, { "params": [] } ], "desc": "

This method will cause the readable stream to resume emitting ['data'][]\nevents.\n\n

\n

This method will switch the stream into flowing mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits ['end'][] event, you can call [stream.resume()][stream-resume] to open\nthe flow of data.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', () => {\n  console.log('got to the end, but did not read anything');\n});
\n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "return": { "textRaw": "Return: `this` ", "name": "return", "desc": "`this`" }, "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Call this function to cause the stream to return strings of the specified\nencoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be interpreted as\nUTF-8 data, and returned as strings. If you do readable.setEncoding('hex'),\nthen the data will be encoded in hexadecimal string format.\n\n

\n

This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled [buf.toString(encoding)][] on them. If you want to read the data\nas strings, always use this method.\n\n

\n

Also you can disable any encoding at all with readable.setEncoding(null).\nThis approach is very useful if you deal with binary data or with large\nmulti-byte strings spread out over multiple chunks.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n});
\n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "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": "

This method will remove the hooks set up for a previous [stream.pipe()][]\ncall.\n\n

\n

If the destination is not specified, then all pipes are removed.\n\n

\n

If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(() => {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
\n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "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": "

This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

\n

Note that stream.unshift(chunk) cannot be called after the ['end'][] event\nhas been triggered; a runtime error will be raised.\n\n

\n

If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See [API\nfor Stream Implementors][].)\n\n

\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  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\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

Note that, unlike [stream.push(chunk)][stream-push], stream.unshift(chunk)\nwill not end the reading process by resetting the internal reading state of the\nstream. This can cause unexpected results if unshift() is called during a\nread (i.e. from within a [stream._read()][stream-_read] implementation on a\ncustom stream). Following the call to unshift() with an immediate\n[stream.push('')][stream-push] will reset the reading state appropriately,\nhowever it is best to simply avoid calling unshift() while in the process of\nperforming a read.\n\n

\n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "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 Streams API as it is today. (See [Compatibility][] for\nmore information.)\n\n

\n

If you are using an older Node.js library that emits ['data'][] events and\nhas a [stream.pause()][stream-pause] method that is advisory only, then you\ncan use the wrap() method to create a [Readable][] stream that uses the old\nstream as its data source.\n\n

\n

You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node.js programs and libraries.\n\n

\n

For example:\n\n

\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" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces.\n\n

\n

Examples of Transform streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

\n

Examples of writable streams include:\n\n

\n\n", "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

If a [stream.write(chunk)][stream-write] call returns false, then the\n'drain' event will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

\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  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\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", "params": [] }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error when writing or piping data.\n\n

\n" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

When the [stream.end()][stream-end] method has been called, and all data has\nbeen flushed to the underlying system, this event is emitted.\n\n

\n
var writer = getWritableStreamSomehow();\nfor (var 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", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

This is emitted whenever the [stream.pipe()][] method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar 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" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

This is emitted whenever the [stream.unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar 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" } ], "methods": [ { "textRaw": "writable.cork()", "type": "method", "name": "cork", "desc": "

Forces buffering of all writes.\n\n

\n

Buffered data will be flushed either at [stream.uncork()][] or at\n[stream.end()][stream-end] call.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.end([chunk][, encoding][, callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String|Buffer} Optional data to write ", "name": "chunk", "type": "String|Buffer", "desc": "Optional data to write", "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": "

Call this method when no more data will be written to the stream. If supplied,\nthe callback is attached as a listener on the ['finish'][] event.\n\n

\n

Calling [stream.write()][stream-write] after calling\n[stream.end()][stream-end] will raise an error.\n\n

\n
// write 'hello, ' and then end with 'world!'\nvar file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!
\n" }, { "textRaw": "writable.setDefaultEncoding(encoding)", "type": "method", "name": "setDefaultEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The new default encoding ", "name": "encoding", "type": "String", "desc": "The new default encoding" } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Sets the default encoding for a writable stream.\n\n

\n" }, { "textRaw": "writable.uncork()", "type": "method", "name": "uncork", "desc": "

Flush all data, buffered since [stream.cork()][] call.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "writable.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} `true` if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "`true` if the data was handled completely." }, "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": "

This method writes some data to the underlying system, 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 detect write errors, listen for the 'error' event.\n\n

\n

The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

\n

This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe ['drain'][] event before writing more data.\n\n\n

\n" } ] } ] }, { "textRaw": "API for Stream Implementors", "name": "API for Stream Implementors", "type": "misc", "desc": "

To implement any sort of stream, the pattern is the same:\n\n

\n
    \n
  1. Extend the appropriate parent class in your own subclass. (The\n[util.inherits()][] method is particularly helpful for this.)
  2. \n
  3. Call the appropriate parent class constructor in your constructor,\nto be sure that the internal mechanisms are set up properly.
  4. \n
  5. Implement one or more specific methods, as detailed below.
  6. \n
\n

The class to extend and the method(s) to implement depend on the sort\nof stream class you are writing:\n\n

\n\n \n \n \n \n \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][stream-_read]

\n
\n

Writing only

\n
\n

Writable

\n
\n

[_write][stream-_write], [_writev][stream-_writev]

\n
\n

Reading and writing

\n
\n

Duplex

\n
\n

[_read][stream-_read], [_write][stream-_write], [_writev][stream-_writev]

\n
\n

Operate on written data, then read the result

\n
\n

Transform

\n
\n

[_transform][stream-_transform], [_flush][stream-_flush]

\n
\n\n

In your implementation code, it is very important to never call the methods\ndescribed in [API for Stream Consumers][]. Otherwise, you can potentially cause\nadverse side effects in programs that consume your streaming interfaces.\n\n

\n", "classes": [ { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

A "duplex" stream is one that is both Readable and Writable, such as a TCP\nsocket connection.\n\n

\n

Note that stream.Duplex is an abstract class designed to be extended\nwith an underlying implementation of the [stream._read(size)][stream-_read]\nand [stream._write(chunk, encoding, callback)][stream-_write] methods as you\nwould with a Readable or Writable stream class.\n\n

\n

Since JavaScript doesn't have multiple prototypal inheritance, this class\nprototypally inherits from Readable, and then parasitically from Writable. It is\nthus up to the user to implement both the low-level\n[stream._read(n)][stream-_read] method as well as the low-level\n[stream._write(chunk, encoding, callback)][stream-_write] method on extension\nduplex classes.\n\n

\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} Default = `true`. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa. ", "name": "allowHalfOpen", "type": "Boolean", "desc": "Default = `true`. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa." }, { "textRaw": "`readableObjectMode` {Boolean} Default = `false`. Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. ", "name": "readableObjectMode", "type": "Boolean", "desc": "Default = `false`. Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`writableObjectMode` {Boolean} Default = `false`. Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. ", "name": "writableObjectMode", "type": "Boolean", "desc": "Default = `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": "

In classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

\n" } ] }, { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "

This is a trivial implementation of a [Transform][] stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy as a building block for novel sorts of streams.\n\n

\n" }, { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [stream._read(size)][stream-_read] method.\n\n

\n

Please see [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

\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 to store in the internal buffer before ceasing to read from the underlying resource. Default = `16384` (16kb), or `16` for `objectMode` streams ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default = `16384` (16kb), or `16` for `objectMode` streams" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default = `null` ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default = `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. Default = `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. Default = `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": "

In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\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: Implement this method, but do NOT call it directly.\n\n

\n

This method is prefixed with an underscore because it is internal to the\nclass that defines it and should only be called by the internal Readable\nclass methods. All Readable stream implementations must provide a _read\nmethod to fetch data from the underlying resource.\n\n

\n

When _read() is called, if data is available from the resource, the _read()\nimplementation should start pushing that data into the read queue by calling\n[this.push(dataChunk)][stream-push]. _read() should continue reading from\nthe resource and pushing data until push returns false, at which point it\nshould stop reading from the resource. Only when _read() is called again after\nit has stopped should it start reading more data from the resource and pushing\nthat data onto the queue.\n\n

\n

Note: once the _read() method is called, it will not be called again until\nthe [stream.push()][stream-push] method is called.\n\n

\n

The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][stream-push].\n\n

\n" } ], "examples": [ { "textRaw": "readable.push(chunk[, encoding])", "type": "example", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "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 } ] } ], "desc": "

Note: This method should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

\n

If a value other than null is passed, The push() method adds a chunk of data\ninto the queue for subsequent stream processors to consume. If null is\npassed, it signals the end of the stream (EOF), after which no more data\ncan be written.\n\n

\n

The data added with push() can be pulled out by calling the\n[stream.read()][stream-read] method when the ['readable'][] event fires.\n\n

\n

This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

\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\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = (chunk) => {\n    // if push() returns false, then we need to stop reading from source\n    if (!this.push(chunk))\n      this._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signaling `null` chunk\n  this._source.onend = () => {\n    this.push(null);\n  };\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.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
\n

Example: A Counting Stream

\n

This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

\n
const Readable = require('stream').Readable;\nconst util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
\n

Example: SimpleProtocol v1 (Sub-optimal)

\n

This is similar to the parseHeader function described\nhere, but implemented as a custom stream.\nAlso, note that this implementation does not convert the incoming data to a\nstring.\n\n

\n

However, this would be better implemented as a [Transform][] stream. See\n[SimpleProtocol v2][] for a better implementation.\n\n

\n
// A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal. See the\n// alternative example below under the Transform section.\n\nconst Readable = require('stream').Readable;\nconst util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  source.on('end', () => {\n    this.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', () => {\n    this.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n      // calling unshift by itself does not reset the reading state\n      // of the stream; since we're inside _read, doing an additional\n      // push('') will reset the state appropriately.\n      this.push('');\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
\n" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

A "transform" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a [zlib][] stream or a\n[crypto][] stream.\n\n

\n

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

\n

Rather than implement the [stream._read()][stream-_read] and\n[stream._write()][stream-_write] methods, Transform classes must implement the\n[stream._transform()][stream-_transform] method, and may optionally\nalso implement the [stream._flush()][stream-_flush] method. (See below.)\n\n

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

In classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

\n" }, { "textRaw": "transform.\\_flush(callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done flushing any remaining data." } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called directly. It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\n

\n

In some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a Zlib compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\n

\n

In those cases, you can implement a _flush() method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting ['end'][] to signal the end of the readable side. Just\nlike with [stream._transform()][stream-_transform], call\ntransform.push(chunk) zero or more times, as appropriate, and call callback\nwhen the flush operation is complete.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\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} Call this function (optionally with an error argument and data) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument and data) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\n

\n

All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output.\n\n

\n

_transform() should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\n

\n

Call transform.push(outputChunk) 0 or more times to generate output\nfrom this input chunk, depending on how much data you want to output\nas a result of this chunk.\n\n

\n

Call the callback function only when the current chunk is completely\nconsumed. Note that there may or may not be output as a result of any\nparticular input chunk. If you supply a second argument to the callback\nit will be passed to the push method. In other words the following are\nequivalent:\n\n

\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

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\n

Example: SimpleProtocol parser v2

\n

The example here of a simple\nprotocol parser can be implemented simply by using the higher level\n[Transform][] stream class, similar to the parseHeader and SimpleProtocol\nv1 examples.\n\n

\n

In this example, rather than providing the input as an argument, it\nwould be piped into the parser, which is a more idiomatic Node.js stream\napproach.\n\n

\n
const util = require('util');\nconst Transform = require('stream').Transform;\nutil.inherits(SimpleProtocol, Transform);\n\nfunction SimpleProtocol(options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(options);\n\n  Transform.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._transform = function(chunk, encoding, done) {\n  if (!this._inBody) {\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n\n      // now, because we got some extra data, emit this first.\n      this.push(chunk.slice(split));\n    }\n  } else {\n    // from there on, just provide the data to our consumer as-is.\n    this.push(chunk);\n  }\n  done();\n};\n\n// Usage:\n// var parser = new SimpleProtocol();\n// source.pipe(parser)\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
\n" } ], "modules": [ { "textRaw": "Events: 'finish' and 'end'", "name": "events:_'finish'_and_'end'", "desc": "

The ['finish'][] and ['end'][] events are from the parent Writable\nand Readable classes respectively. The 'finish' event is fired after\n[stream.end()][stream-end] is called and all chunks have been processed by\n[stream._transform()][stream-_transform], 'end' is fired after all data has\nbeen output which is after the callback in [stream._flush()][stream-_flush]\nhas been called.\n\n

\n", "type": "module", "displayName": "Events: 'finish' and 'end'" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

stream.Writable is an abstract class designed to be extended with an\nunderlying implementation of the\n[stream._write(chunk, encoding, callback)][stream-_write] method.\n\n

\n

Please see [API for Stream Consumers][] for how to consume\nwritable streams in your programs. What follows is an explanation of\nhow to implement Writable streams in your programs.\n\n

\n", "methods": [ { "textRaw": "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`. Default = `16384` (16kb), or `16` for `objectMode` streams. ", "name": "highWaterMark", "type": "Number", "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`. Default = `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]. Default = `true` ", "name": "decodeStrings", "type": "Boolean", "desc": "Whether or not to decode strings into Buffers before passing them to [`stream._write()`][stream-_write]. Default = `true`" }, { "textRaw": "`objectMode` {Boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. If set you can write arbitrary data instead of only `Buffer` / `String` data. Default = `false` ", "name": "objectMode", "type": "Boolean", "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. If set you can write arbitrary data instead of only `Buffer` / `String` data. Default = `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": "

In classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\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 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} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

All Writable stream implementations must provide a\n[stream._write()][stream-_write] method to send data to the underlying\nresource.\n\n

\n

Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n

\n

Call the callback using the standard callback(error) pattern to\nsignal that the write completed successfully or with an error.\n\n

\n

If the decodeStrings flag is set in the constructor options, then\nchunk may be a string rather than a Buffer, and encoding will\nindicate the sort of string that it is. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If you do not explicitly set the decodeStrings\noption to false, then you can safely ignore the encoding argument,\nand assume that chunk will always be a Buffer.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\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} Call this function (optionally with an error argument) when you are done processing the supplied chunks. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunks." } ] }, { "params": [ { "name": "chunks" }, { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called directly. It may be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n

\n

This function is completely optional to implement. In most cases it is\nunnecessary. If implemented, it will be called with all the chunks\nthat are buffered in the write queue.\n\n\n

\n" } ] } ] }, { "textRaw": "Simplified Constructor API", "name": "Simplified Constructor API", "type": "misc", "desc": "

In simple cases there is now the added benefit of being able to construct a\nstream without inheritance.\n\n

\n

This can be done by passing the appropriate methods as constructor options:\n\n

\n

Examples:\n\n

\n", "miscs": [ { "textRaw": "Duplex", "name": "duplex", "desc": "
var duplex = new stream.Duplex({\n  read: function(n) {\n    // sets this._read under the hood\n\n    // push data onto the read queue, passing null\n    // will signal the end of the stream (EOF)\n    this.push(chunk);\n  },\n  write: function(chunk, encoding, next) {\n    // sets this._write under the hood\n\n    // An optional error can be passed as the first argument\n    next()\n  }\n});\n\n// or\n\nvar duplex = new stream.Duplex({\n  read: function(n) {\n    // sets this._read under the hood\n\n    // push data onto the read queue, passing null\n    // will signal the end of the stream (EOF)\n    this.push(chunk);\n  },\n  writev: function(chunks, next) {\n    // sets this._writev under the hood\n\n    // An optional error can be passed as the first argument\n    next()\n  }\n});
\n", "type": "misc", "displayName": "Duplex" }, { "textRaw": "Readable", "name": "readable", "desc": "
var readable = new stream.Readable({\n  read: function(n) {\n    // sets this._read under the hood\n\n    // push data onto the read queue, passing null\n    // will signal the end of the stream (EOF)\n    this.push(chunk);\n  }\n});
\n", "type": "misc", "displayName": "Readable" }, { "textRaw": "Transform", "name": "transform", "desc": "
var transform = new stream.Transform({\n  transform: function(chunk, encoding, next) {\n    // sets this._transform under the hood\n\n    // generate output as many times as needed\n    // this.push(chunk);\n\n    // call when the current chunk is consumed\n    next();\n  },\n  flush: function(done) {\n    // sets this._flush under the hood\n\n    // generate output as many times as needed\n    // this.push(chunk);\n\n    done();\n  }\n});
\n", "type": "misc", "displayName": "Transform" }, { "textRaw": "Writable", "name": "writable", "desc": "
var writable = new stream.Writable({\n  write: function(chunk, encoding, next) {\n    // sets this._write under the hood\n\n    // An optional error can be passed as the first argument\n    next()\n  }\n});\n\n// or\n\nvar writable = new stream.Writable({\n  writev: function(chunks, next) {\n    // sets this._writev under the hood\n\n    // An optional error can be passed as the first argument\n    next()\n  }\n});
\n", "type": "misc", "displayName": "Writable" } ] }, { "textRaw": "Streams: Under the Hood", "name": "Streams: Under the Hood", "type": "misc", "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

Both Writable and Readable streams will buffer data on an internal\nobject which can be retrieved from _writableState.getBuffer() or\n_readableState.buffer, respectively.\n\n

\n

The amount of data that will potentially be buffered depends on the\nhighWaterMark option which is passed into the constructor.\n\n

\n

Buffering in Readable streams happens when the implementation calls\n[stream.push(chunk)][stream-push]. If the consumer of the Stream does not\ncall [stream.read()][stream-read], then the data will sit in the internal\nqueue until it is consumed.\n\n

\n

Buffering in Writable streams happens when the user calls\n[stream.write(chunk)][stream-write] repeatedly, even when it returns false.\n\n

\n

The purpose of streams, especially with the [stream.pipe()][] method, is to\nlimit the buffering of data to acceptable levels, so that sources and\ndestinations of varying speed will not overwhelm the available memory.\n\n

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

\n\n

In Node.js v0.10, the [Readable][] class was added.\nFor backwards compatibility with older Node.js programs, Readable streams\nswitch into "flowing mode" when a ['data'][] event handler is added, or\nwhen the [stream.resume()][stream-resume] method is called. The effect is\nthat, even if you are not using the new [stream.read()][stream-read] method\nand ['readable'][] event, you no longer have to worry about losing\n['data'][] chunks.\n\n

\n

Most programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n

\n\n

For example, consider the following code:\n\n

\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('I got your message (but didnt read it)\\n');\n  });\n\n}).listen(1337);
\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,\nthe socket will remain paused forever.\n\n

\n

The workaround in this situation is to call the\n[stream.resume()][stream-resume] method to start the flow of data:\n\n

\n
// Workaround\nnet.createServer((socket) => {\n\n  socket.on('end', () => {\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n  // start the flow of data, discarding it.\n  socket.resume();\n\n}).listen(1337);
\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\n[stream.wrap()][] method.\n\n\n

\n" }, { "textRaw": "Object Mode", "name": "Object Mode", "type": "misc", "desc": "

Normally, Streams operate on Strings and Buffers exclusively.\n\n

\n

Streams that are in object mode can emit generic JavaScript values\nother than Buffers and Strings.\n\n

\n

A Readable stream in object mode will always return a single item from\na call to [stream.read(size)][stream-read], regardless of what the size\nargument is.\n\n

\n

A Writable stream in object mode will always ignore the encoding\nargument to [stream.write(data, encoding)][stream-write].\n\n

\n

The special value null still retains its special value for object\nmode streams. That is, for object mode readable streams, null as a\nreturn value from [stream.read()][stream-read] indicates that there is no more\ndata, and [stream.push(null)][stream-push] will signal the end of stream data\n(EOF).\n\n

\n

No streams in Node.js core are object mode streams. This pattern is only\nused by userland streaming libraries.\n\n

\n

You should set objectMode in your stream child class constructor on\nthe options object. Setting objectMode mid-stream is not safe.\n\n

\n

For Duplex streams objectMode can be set exclusively for readable or\nwritable side with readableObjectMode and writableObjectMode\nrespectively. These options can be used to implement parsers and\nserializers with Transform streams.\n\n

\n
const util = require('util');\nconst StringDecoder = require('string_decoder').StringDecoder;\nconst Transform = require('stream').Transform;\nutil.inherits(JSONParseStream, Transform);\n\n// Gets \\n-delimited JSON string data, and emits the parsed objects\nfunction JSONParseStream() {\n  if (!(this instanceof JSONParseStream))\n    return new JSONParseStream();\n\n  Transform.call(this, { readableObjectMode : true });\n\n  this._buffer = '';\n  this._decoder = new StringDecoder('utf8');\n}\n\nJSONParseStream.prototype._transform = function(chunk, encoding, cb) {\n  this._buffer += this._decoder.write(chunk);\n  // split on newlines\n  var lines = this._buffer.split(/\\r?\\n/);\n  // keep the last partial line buffered\n  this._buffer = lines.pop();\n  for (var l = 0; l < lines.length; l++) {\n    var line = lines[l];\n    try {\n      var obj = JSON.parse(line);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};\n\nJSONParseStream.prototype._flush = function(cb) {\n  // Just handle any leftover\n  var rem = this._buffer.trim();\n  if (rem) {\n    try {\n      var obj = JSON.parse(rem);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};
\n" }, { "textRaw": "`stream.read(0)`", "name": "`stream.read(0)`", "desc": "

There are some cases where you want to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In that case, you can call stream.read(0), which will always\nreturn null.\n\n

\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()][stream-_read] call.\n\n

\n

There is almost never a need to do this. However, you will see some\ncases in Node.js's internals where this is done, particularly in the\nReadable stream class internals.\n\n

\n", "type": "misc", "displayName": "`stream.read(0)`" }, { "textRaw": "`stream.push('')`", "name": "`stream.push('')`", "desc": "

Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an\ninteresting side effect. Because it is a call to\n[stream.push()][stream-push], it will end the reading process. However, it\ndoes not add any data to the readable buffer, so there's nothing for\na user to consume.\n\n

\n

Very rarely, there are cases where you have no data to provide now,\nbut the consumer of your stream (or, perhaps, another bit of your own\ncode) will know when to check again, by calling [stream.read(0)][stream-read].\nIn those cases, you may call stream.push('').\n\n

\n

So far, the only use case for this functionality is in the\n[tls.CryptoStream][] class, which is deprecated in Node.js/io.js v1.0. If you\nfind that you have to use stream.push(''), please consider another\napproach, because it almost certainly indicates that something is\nhorribly wrong.\n\n

\n", "type": "misc", "displayName": "`stream.push('')`" } ] } ], "type": "module", "displayName": "Stream" }, { "textRaw": "StringDecoder", "name": "stringdecoder", "stability": 2, "stabilityText": "Stable", "desc": "

To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

\n
const StringDecoder = require('string_decoder').StringDecoder;\nconst decoder = new StringDecoder('utf8');\n\nconst cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nconst euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
\n", "classes": [ { "textRaw": "Class: StringDecoder", "type": "class", "name": "StringDecoder", "desc": "

Accepts a single argument, encoding which defaults to 'utf8'.\n\n

\n", "methods": [ { "textRaw": "decoder.end()", "type": "method", "name": "end", "desc": "

Returns any trailing bytes that were left in the buffer.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "decoder.write(buffer)", "type": "method", "name": "write", "desc": "

Returns a decoded string.\n\n

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] } ] } ], "type": "module", "displayName": "StringDecoder" }, { "textRaw": "Timers", "name": "timers", "stability": 3, "stabilityText": "Locked", "desc": "

All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

\n", "methods": [ { "textRaw": "clearImmediate(immediateObject)", "type": "method", "name": "clearImmediate", "desc": "

Stops an immediateObject, as created by [setImmediate][], from triggering.\n\n

\n", "signatures": [ { "params": [ { "name": "immediateObject" } ] } ] }, { "textRaw": "clearInterval(intervalObject)", "type": "method", "name": "clearInterval", "desc": "

Stops an intervalObject, as created by [setInterval][], from triggering.\n\n

\n", "signatures": [ { "params": [ { "name": "intervalObject" } ] } ] }, { "textRaw": "clearTimeout(timeoutObject)", "type": "method", "name": "clearTimeout", "desc": "

Prevents a timeoutObject, as created by [setTimeout][], from triggering.\n\n

\n", "signatures": [ { "params": [ { "name": "timeoutObject" } ] } ] }, { "textRaw": "ref()", "type": "method", "name": "ref", "desc": "

If a timer was previously unref()d, then ref() can be called to explicitly\nrequest the timer hold the program open. If the timer is already refd calling\nref again will have no effect.\n\n

\n

Returns the timer.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "setImmediate(callback[, arg][, ...])", "type": "method", "name": "setImmediate", "desc": "

Schedules "immediate" execution of callback after I/O events'\ncallbacks and before timers set by [setTimeout][] and [setInterval][] are\ntriggered. Returns an immediateObject for possible use with\n[clearImmediate][]. Additional optional arguments may be passed to the\ncallback.\n\n

\n

Callbacks for immediates are queued in the order in which they were created.\nThe entire callback queue is processed every event loop iteration. If an\nimmediate is queued from inside an executing callback, that immediate won't fire\nuntil the next event loop iteration.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "setInterval(callback, delay[, arg][, ...])", "type": "method", "name": "setInterval", "desc": "

Schedules repeated execution of callback every delay milliseconds.\nReturns a intervalObject for possible use with [clearInterval][]. Additional\noptional arguments may be passed to the callback.\n\n

\n

To follow browser behavior, when using delays larger than 2147483647\nmilliseconds (approximately 25 days) or less than 1, Node.js will use 1 as the\ndelay.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "setTimeout(callback, delay[, arg][, ...])", "type": "method", "name": "setTimeout", "desc": "

Schedules execution of a one-time callback after delay milliseconds.\nReturns a timeoutObject for possible use with [clearTimeout][]. Additional\noptional arguments may be passed to the callback.\n\n

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

\n

To follow browser behavior, when using delays larger than 2147483647\nmilliseconds (approximately 25 days) or less than 1, the timeout is executed\nimmediately, as if the delay was set to 1.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "unref()", "type": "method", "name": "unref", "desc": "

The opaque value returned by [setTimeout][] and [setInterval][] also has the\nmethod timer.unref() which allows the creation of a timer that is active but\nif it is the only item left in the event loop, it won't keep the program\nrunning. If the timer is already unrefd calling unref again will have no\neffect.\n\n

\n

In the case of [setTimeout][], unref creates a separate timer that will\nwakeup the event loop, creating too many of these may adversely effect event\nloop performance -- use wisely.\n\n

\n

Returns the timer.\n\n

\n", "signatures": [ { "params": [] } ] } ], "type": "module", "displayName": "Timers" }, { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 2, "stabilityText": "Stable", "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this:\n\n

\n
openssl genrsa -out ryans-key.pem 2048
\n

All servers and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

\n
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
\n

To create a self-signed certificate with the CSR, do this:\n\n

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\n

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

For Perfect Forward Secrecy, it is required to generate Diffie-Hellman\nparameters:\n\n

\n
openssl dhparam -outform PEM -out dhparam.pem 2048
\n

To create a .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n      -certfile ca-cert.pem -out agent5.pfx
\n\n", "miscs": [ { "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

\n\n" }, { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportionate amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiation is limited to three times every 10 minutes. An\nerror is emitted on the [tls.TLSSocket][] instance when the threshold is\nexceeded. These limits are configurable:\n\n

\n\n

Do not change the defaults without a full understanding of the implications.\n\n

\n

To test the server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (i.e., the letter R followed by a carriage return) a few\ntimes.\n\n

\n" }, { "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. Practically it means that even if\nthe private key of a server is compromised, communication can only be\ndecrypted by eavesdroppers if they manage to obtain the key-pair specifically\ngenerated for each session.\n\n

\n

This is achieved by randomly generating a key pair for key-agreement on every\nhandshake (in contrast to using the same key for all sessions). Methods\nimplementing this technique, thus offering Perfect Forward Secrecy, are\ncalled "ephemeral".\n\n

\n

Currently two methods are commonly used to achieve Perfect Forward Secrecy (note\nthe character "E" appended to the traditional abbreviations):\n\n

\n\n

Ephemeral methods may have some performance drawbacks, because key generation\nis expensive.\n\n

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

\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

This default can be overriden 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\n

\n
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"
\n

Note that 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 should by used only if\nabsolutely necessary.\n\n

\n", "type": "module", "displayName": "Modifying the Default TLS Cipher suite" } ], "classes": [ { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "

This is an encrypted stream.\n\n

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

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

Returned by tls.createSecurePair.\n\n

\n", "events": [ { "textRaw": "Event: 'secure'", "type": "event", "name": "secure", "desc": "

This event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

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

\n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting only raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

\n", "events": [ { "textRaw": "Event: 'clientError'", "type": "event", "name": "clientError", "desc": "

function (exception, tlsSocket) { }\n\n

\n

When a client connection emits an 'error' event before a secure connection is\nestablished it will be forwarded here.\n\n

\n

tlsSocket is the [tls.TLSSocket][] that the error originated from.\n\n

\n", "params": [] }, { "textRaw": "Event: 'newSession'", "type": "event", "name": "newSession", "desc": "

function (sessionId, sessionData, callback) { }\n\n

\n

Emitted on creation of a TLS session. May be used to store sessions in external\nstorage. callback must be invoked eventually, otherwise no data will be\nsent or received from the secure connection.\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "desc": "

function (certificate, issuer, callback) { }\n\n

\n

Emitted when the client sends a certificate status request. The server's\ncurrent certificate can be parsed to obtain the OCSP URL and certificate ID;\nafter obtaining an OCSP response callback(null, resp) is then invoked, where\nresp is a Buffer instance. Both certificate and issuer are Buffer\nDER-representations of the primary and issuer's certificates. They can be used\nto obtain the OCSP certificate ID and OCSP endpoint URL.\n\n

\n

Alternatively, callback(null, null) may be called, meaning that there was no\nOCSP response.\n\n

\n

Calling callback(err) will result in a socket.destroy(err) call.\n\n

\n

Typical flow:\n\n

\n
    \n
  1. Client connects to the server and sends an 'OCSPRequest' to it (via status\ninfo extension in ClientHello).
  2. \n
  3. Server receives the request and invokes the 'OCSPRequest' event listener\nif present.
  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: issuer could be null if the certificate is self-signed or if the\nissuer is not in the root certificates list. (An issuer may be provided via the\nca option.)\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n

NOTE: An npm module like [asn1.js] may be used to parse the certificates.\n\n

\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "desc": "

function (sessionId, callback) { }\n\n

\n

Emitted when the client wants to resume the previous TLS session. The event\nlistener may perform a lookup in external storage using the given sessionId\nand invoke callback(null, sessionData) once finished. If the session can't be\nresumed (i.e., doesn't exist in storage) one may call callback(null, null).\nCalling callback(err) will terminate incoming connection and destroy the\nsocket.\n\n

\n

NOTE: adding this event listener will only have an effect on connections\nestablished after the addition of the event listener.\n\n

\n

Here's an example for using TLS session resumption:\n\n

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

function (tlsSocket) {}\n\n

\n

This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The argument is an instance of [tls.TLSSocket][] and\nhas all the common stream methods and events.\n\n

\n

socket.authorized is a boolean value which indicates if the\nclient has been verified by one of the supplied certificate authorities for the\nserver. If socket.authorized is false, then socket.authorizationError is\nset to describe how authorization failed. Implied but worth mentioning:\ndepending on the settings of the TLS server, unauthorized connections may\nbe accepted.\n\n

\n

socket.npnProtocol is a string containing the selected NPN protocol\nand socket.alpnProtocol is a string containing the selected ALPN\nprotocol. When both NPN and ALPN extensions are received, ALPN takes\nprecedence over NPN and the next protocol is selected by ALPN. When\nALPN has no selected protocol, this returns false.\n\n

\n

socket.servername is a string containing the server name requested with\nSNI.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.addContext(hostname, context)", "type": "method", "name": "addContext", "desc": "

Add secure context that will be used if the client request's SNI hostname\nmatches the supplied hostname (wildcards can be used). context can contain\nkey, cert, ca or any other properties from\n[tls.createSecureContext()][] options argument.\n\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "context" } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close' event.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.getTicketKeys()", "type": "method", "name": "getTicketKeys", "desc": "

Returns a Buffer instance holding the keys currently used for\nencryption/decryption of the [TLS Session Tickets][]\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.listen(port[, hostname][, callback])", "type": "method", "name": "listen", "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. A\nport value of zero will assign a random port.\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTicketKeys(keys)", "type": "method", "name": "setTicketKeys", "desc": "

Updates the keys for encryption/decryption of the [TLS Session Tickets][].\n\n

\n

NOTE: the buffer should be 48 bytes long. See ticketKeys option in\ntls.createServer for\nmore information on how it is used.\n\n

\n

NOTE: the change is effective only for future server connections. Existing\nor currently pending server connections will use the previous keys.\n\n

\n", "signatures": [ { "params": [ { "name": "keys" } ] } ] } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "desc": "

The number of concurrent connections on the server.\n\n

\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count\nexceeds the specified threshold.\n\n\n

\n" } ] }, { "textRaw": "Class: tls.TLSSocket", "type": "class", "name": "tls.TLSSocket", "desc": "

This is a wrapped version of [net.Socket][] that does transparent encryption\nof written data and all required TLS negotiation.\n\n

\n

This instance implements the duplex [Stream][] interface. It has all the\ncommon stream methods and events.\n\n

\n

Methods that return TLS connection metadata (e.g.\n[tls.TLSSocket.getPeerCertificate()][] will only return data while the\nconnection is open.\n\n

\n", "methods": [ { "textRaw": "new tls.TLSSocket(socket[, options])", "type": "method", "name": "TLSSocket", "desc": "

Construct a new TLSSocket object from an existing TCP socket.\n\n

\n

socket is an instance of [net.Socket][]\n\n

\n

options is an optional object that might contain following properties:\n\n

\n\n", "signatures": [ { "params": [ { "name": "socket" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "tlsSocket.address()", "type": "method", "name": "address", "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\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getCipher()", "type": "method", "name": "getCipher", "desc": "

Returns an object representing the cipher name and the SSL/TLS protocol version\nthat first defined the cipher.\n\n

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttps://www.openssl.org/docs/manmaster/ssl/SSL_CIPHER_get_name.html for more\ninformation.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getEphemeralKeyInfo()", "type": "method", "name": "getEphemeralKeyInfo", "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, it returns null\nif called on a server socket. The supported types are 'DH' and 'ECDH'. The\nname property is only available in 'ECDH'.\n\n

\n

Example:\n\n

\n
{ type: 'ECDH', name: 'prime256v1', size: 256 }
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getPeerCertificate([ detailed ])", "type": "method", "name": "getPeerCertificate", "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate. If the\ndetailed argument is true the full chain with the issuer property will be\nreturned, if false only the top certificate without the issuer property.\n\n

\n

Example:\n\n

\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  issuerInfo:\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   { ... another certificate ... },\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

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

\n", "signatures": [ { "params": [ { "name": "detailed", "optional": true } ] } ] }, { "textRaw": "tlsSocket.getProtocol()", "type": "method", "name": "getProtocol", "desc": "

Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. 'unknown' will be returned for connected sockets that have\nnot completed the handshaking process. null will be returned for server\nsockets or disconnected client sockets.\n\n

\n

Examples:\n

\n
'SSLv3'\n'TLSv1'\n'TLSv1.1'\n'TLSv1.2'\n'unknown'
\n

See https://www.openssl.org/docs/manmaster/ssl/SSL_get_version.html for more\ninformation.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "desc": "

Returns the ASN.1 encoded TLS session or undefined if none was negotiated.\nCould be used to speed up handshake establishment when reconnecting to the\nserver.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getTLSTicket()", "type": "method", "name": "getTLSTicket", "desc": "

NOTE: Works only with client TLS sockets. Useful only for debugging, for\nsession reuse provide session option to [tls.connect()][].\n\n

\n

Returns the TLS session ticket or undefined if none was negotiated.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.renegotiate(options, callback)", "type": "method", "name": "renegotiate", "desc": "

Initiate TLS renegotiation process. The options object may contain the\nfollowing fields: rejectUnauthorized, requestCert. (See [tls.createServer\n()][] for details.) callback(err) will be executed with null as err,\nonce the renegotiation is successfully completed.\n\n

\n

NOTE: Can be used to request peer's certificate after the secure connection\nhas been established.\n\n

\n

ANOTHER NOTE: When running as the server, socket will be destroyed\nwith an error after handshakeTimeout timeout.\n\n

\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "tlsSocket.setMaxSendFragment(size)", "type": "method", "name": "setMaxSendFragment", "desc": "

Set maximum TLS fragment size (default and maximum value is: 16384, minimum\nis: 512). Returns true on success, false otherwise.\n\n

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

\n", "signatures": [ { "params": [ { "name": "size" } ] } ] } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "desc": "

function (response) { }\n\n

\n

This event will be emitted if the requestOCSP option was set. response is a\nBuffer containing the server's OCSP response.\n\n

\n

Traditionally, the response is a signed object from the server's CA that\ncontains information about server's certificate revocation status.\n\n

\n", "params": [] }, { "textRaw": "Event: 'secureConnect'", "type": "event", "name": "secureConnect", "desc": "

This event is emitted after the handshaking process for a new connection has\nsuccessfully completed. The listener will be called regardless of whether or not\nthe server's certificate has been authorized. It is the user's responsibility to\ntest tlsSocket.authorized to see if the server certificate was signed by one\nof the specified CAs. If tlsSocket.authorized === false then the error can be\nfound in tlsSocket.authorizationError. Also, if either ALPN or NPN was used\ntlsSocket.alpnProtocol or tlsSocket.npnProtocol can be checked for the\nnegotiated protocol.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "tlsSocket.authorized", "name": "authorized", "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false.\n\n

\n" }, { "textRaw": "tlsSocket.authorizationError", "name": "authorizationError", "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when tlsSocket.authorized === false.\n\n

\n" }, { "textRaw": "tlsSocket.encrypted", "name": "encrypted", "desc": "

Static boolean value, always true. May be used to distinguish TLS sockets\nfrom regular ones.\n\n

\n" }, { "textRaw": "tlsSocket.localAddress", "name": "localAddress", "desc": "

The string representation of the local IP address.\n\n

\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "desc": "

The numeric representation of the local port.\n\n

\n" }, { "textRaw": "tlsSocket.remoteAddress", "name": "remoteAddress", "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" }, { "textRaw": "tlsSocket.remoteFamily", "name": "remoteFamily", "desc": "

The string representation of the remote IP family. 'IPv4' or 'IPv6'.\n\n

\n" }, { "textRaw": "tlsSocket.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" } ] } ], "methods": [ { "textRaw": "tls.connect(options[, callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [tls.TLSSocket][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar 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

Or\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar 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", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port[, host][, options][, callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [tls.TLSSocket][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar 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

Or\n\n

\n
const tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar 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", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecureContext(options)", "type": "method", "name": "createSecureContext", "desc": "

Creates a credentials object; the options object may contain the following\nfields:\n\n

\n\n

If no 'CA' details are given, then Node.js will use the default\npublicly trusted list of CAs as given in\n

\n

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n

\n", "signatures": [ { "params": [ { "name": "options" } ] } ] }, { "textRaw": "tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])", "type": "method", "name": "createSecurePair", "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\n

\n\n

tls.createSecurePair() returns a SecurePair object with cleartext and\nencrypted stream properties.\n\n

\n

NOTE: cleartext has the same API as [tls.TLSSocket][]\n\n

\n", "signatures": [ { "params": [ { "name": "context", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "tls.createServer(options[, secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the ['secureConnection'][] event. The\noptions object may contain the following fields:\n\n

\n\n

Here is a simple example echo server:\n\n

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

Or\n\n

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

You can test this server by connecting to it with openssl s_client:\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported SSL ciphers.\n\n

\n

Example:\n\n

\n
var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
\n", "signatures": [ { "params": [] } ] } ], "type": "module", "displayName": "TLS (SSL)" }, { "textRaw": "TTY", "name": "tty", "stability": 2, "stabilityText": "Stable", "desc": "

The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

\n

When Node.js detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if Node.js is being run\nin a TTY context is to check process.stdout.isTTY:\n\n

\n
$ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
\n", "classes": [ { "textRaw": "Class: ReadStream", "type": "class", "name": "ReadStream", "desc": "

A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nNode.js program (only when isatty(0) is true).\n\n

\n", "properties": [ { "textRaw": "rs.isRaw", "name": "isRaw", "desc": "

A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

\n" } ], "methods": [ { "textRaw": "rs.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n

\n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ] }, { "textRaw": "Class: WriteStream", "type": "class", "name": "WriteStream", "desc": "

A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

\n", "events": [ { "textRaw": "Event: 'resize'", "type": "event", "name": "resize", "desc": "

function () {}\n\n

\n

Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

\n
process.stdout.on('resize', () => {\n  console.log('screen size has changed!');\n  console.log(`${process.stdout.columns}x${process.stdout.rows}`);\n});
\n", "params": [] } ], "properties": [ { "textRaw": "ws.columns", "name": "columns", "desc": "

A Number that gives the number of columns the TTY currently has. This property\ngets updated on 'resize' events.\n\n

\n" }, { "textRaw": "ws.rows", "name": "rows", "desc": "

A Number that gives the number of rows the TTY currently has. This property\ngets updated on 'resize' events.\n\n

\n" } ] } ], "methods": [ { "textRaw": "tty.isatty(fd)", "type": "method", "name": "isatty", "desc": "

Returns true or false depending on if the fd is associated with a\nterminal.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "tty.setRawMode(mode)", "type": "method", "name": "setRawMode", "stability": 0, "stabilityText": "Deprecated: Use [tty.ReadStream#setRawMode][] (i.e. process.stdin.setRawMode) instead.", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ], "type": "module", "displayName": "TTY" }, { "textRaw": "URL", "name": "url", "stability": 2, "stabilityText": "Stable", "desc": "

This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

\n", "modules": [ { "textRaw": "URL Parsing", "name": "url_parsing", "desc": "

Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

\n

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

\n\n", "modules": [ { "textRaw": "Escaped Characters", "name": "escaped_characters", "desc": "

Spaces (' ') and the following characters will be automatically escaped in the\nproperties of URL objects:\n\n

\n
< > " ` \\r \\n \\t { } | \\ ^ '
\n
\n

The following methods are provided by the URL module:\n\n

\n", "type": "module", "displayName": "Escaped Characters" } ], "type": "module", "displayName": "URL Parsing" } ], "methods": [ { "textRaw": "url.format(urlObj)", "type": "method", "name": "format", "desc": "

Take a parsed URL object, and return a formatted URL string.\n\n

\n

Here's how the formatting process works:\n\n

\n\n", "signatures": [ { "params": [ { "name": "urlObj" } ] } ] }, { "textRaw": "url.parse(urlStr[, parseQueryString][, slashesDenoteHost])", "type": "method", "name": "parse", "desc": "

Take a URL string, and return an object.\n\n

\n

Pass true as the second argument to also parse the query string using the\nquerystring module. If true then the query property will always be\nassigned an object, and the search property will always be a (possibly\nempty) string. If false then the query property will not be parsed or\ndecoded. Defaults to false.\n\n

\n

Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

\n", "signatures": [ { "params": [ { "name": "urlStr" }, { "name": "parseQueryString", "optional": true }, { "name": "slashesDenoteHost", "optional": true } ] } ] }, { "textRaw": "url.resolve(from, to)", "type": "method", "name": "resolve", "desc": "

Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag. Examples:\n\n

\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", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] } ], "type": "module", "displayName": "URL" }, { "textRaw": "util", "name": "util", "stability": 2, "stabilityText": "Stable", "desc": "

These functions are in the module 'util'. Use require('util') to\naccess them.\n\n

\n

The util module is primarily designed to support the needs of Node.js's\ninternal APIs. Many of these utilities are useful for your own\nprograms. If you find that these functions are lacking for your\npurposes, however, you are encouraged to write your own utilities. We\nare not interested in any future additions to the util module that\nare unnecessary for Node.js's internal functionality.\n\n

\n", "methods": [ { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "stability": 0, "stabilityText": "Deprecated: Use [`console.error()`][] instead.", "desc": "

Deprecated predecessor of console.error.\n\n

\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.debuglog(section)", "type": "method", "name": "debuglog", "signatures": [ { "return": { "textRaw": "Returns: {Function} The logging function ", "name": "return", "type": "Function", "desc": "The logging function" }, "params": [ { "textRaw": "`section` {String} The section of the program to be debugged ", "name": "section", "type": "String", "desc": "The section of the program to be debugged" } ] }, { "params": [ { "name": "section" } ] } ], "desc": "

This is used to create a function which conditionally writes to stderr\nbased on the existence of a NODE_DEBUG environment variable. If the\nsection name appears in that environment variable, then the returned\nfunction will be similar to console.error(). If not, then the\nreturned function is a no-op.\n\n

\n

For example:\n\n

\n
var debuglog = util.debuglog('foo');\n\nvar bar = 123;\ndebuglog('hello from foo [%d]', bar);
\n

If this program is run with NODE_DEBUG=foo in the environment, then\nit will output something like:\n\n

\n
FOO 3245: hello from foo [123]
\n

where 3245 is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.\n\n

\n

You may separate multiple NODE_DEBUG environment variables with a\ncomma. For example, NODE_DEBUG=fs,net,tls.\n\n

\n" }, { "textRaw": "util.deprecate(function, string)", "type": "method", "name": "deprecate", "desc": "

Marks that a method should not be used any more.\n\n

\n
const util = require('util');\n\nexports.puts = util.deprecate(() => {\n  for (var i = 0, len = arguments.length; i < len; ++i) {\n    process.stdout.write(arguments[i] + '\\n');\n  }\n}, 'util.puts: Use console.log instead');
\n

It returns a modified function which warns once by default.\n\n

\n

If --no-deprecation is set then this function is a NO-OP. Configurable\nat run-time through the process.noDeprecation boolean (only effective\nwhen set before a module is loaded.)\n\n

\n

If --trace-deprecation is set, a warning and a stack trace are logged\nto the console the first time the deprecated API is used. Configurable\nat run-time through the process.traceDeprecation boolean.\n\n

\n

If --throw-deprecation is set then the application throws an exception\nwhen the deprecated API is used. Configurable at run-time through the\nprocess.throwDeprecation boolean.\n\n

\n

process.throwDeprecation takes precedence over process.traceDeprecation.\n\n

\n", "signatures": [ { "params": [ { "name": "function" }, { "name": "string" } ] } ] }, { "textRaw": "util.error([...])", "type": "method", "name": "error", "stability": 0, "stabilityText": "Deprecated: Use [`console.error()`][] instead.", "desc": "

Deprecated predecessor of console.error.\n\n

\n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.format(format[, ...])", "type": "method", "name": "format", "desc": "

Returns a formatted string using the first argument as a printf-like format.\n\n

\n

The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

\n\n

If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

\n
util.format('%s:%s', 'foo'); // 'foo:%s'
\n

If there are more arguments than placeholders, the extra arguments are\ncoerced to strings (for objects and symbols, util.inspect() is used)\nand then concatenated, delimited by a space.\n\n

\n
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
\n

If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

\n
util.format(1, 2, 3); // '1 2 3'
\n", "signatures": [ { "params": [ { "name": "format" }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.inherits(constructor, superConstructor)", "type": "method", "name": "inherits", "desc": "

Inherit the prototype methods from one [constructor][] into another. The\nprototype of constructor will be set to a new object created from\nsuperConstructor.\n\n

\n

As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

\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\nvar 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", "signatures": [ { "params": [ { "name": "constructor" }, { "name": "superConstructor" } ] } ] }, { "textRaw": "util.inspect(object[, options])", "type": "method", "name": "inspect", "desc": "

Return a string representation of object, which is useful for debugging.\n\n

\n

An optional options object may be passed that alters certain aspects of the\nformatted string:\n\n

\n\n

Example of inspecting all properties of the util object:\n\n

\n
const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));
\n

Values may supply their own custom inspect(depth, opts) functions, when\ncalled they receive the current depth in the recursive inspection, as well as\nthe options object passed to util.inspect().\n\n

\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 util.inspect.styles and util.inspect.colors objects.\n\n

\n

util.inspect.styles is a map assigning each style a color\nfrom util.inspect.colors.\nHighlighted styles and their default values are:\n number (yellow)\n boolean (yellow)\n string (green)\n date (magenta)\n regexp (red)\n null (bold)\n undefined (grey)\n special - only function at this time (cyan)\n * name (intentionally no styling)\n\n

\n

Predefined color codes are: white, grey, black, blue, cyan,\ngreen, magenta, red and yellow.\nThere are also bold, italic, underline and inverse codes.\n\n

\n" }, { "textRaw": "Custom `inspect()` function on Objects", "name": "Custom `inspect()` function on Objects", "type": "misc", "desc": "

Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

\n
const util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return `{${this.name}}`;\n};\n\nutil.inspect(obj);\n  // "{nate}"
\n

You may also return another Object entirely, and the returned String will be\nformatted according to the returned Object. This is similar to how\nJSON.stringify() works:\n\n

\n
var 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  // "{ bar: 'baz' }"
\n" } ], "signatures": [ { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "util.isArray(object)", "type": "method", "name": "isArray", "stability": 0, "stabilityText": "Deprecated", "desc": "

Internal alias for [Array.isArray][].\n\n

\n

Returns true if the given "object" is an Array. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isBoolean(object)", "type": "method", "name": "isBoolean", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a Boolean. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isBoolean(1)\n  // false\nutil.isBoolean(0)\n  // false\nutil.isBoolean(false)\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isBuffer(object)", "type": "method", "name": "isBuffer", "stability": 0, "stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.", "desc": "

Returns true if the given "object" is a Buffer. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isBuffer({ length: 0 })\n  // false\nutil.isBuffer([])\n  // false\nutil.isBuffer(new Buffer('hello world'))\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isDate(object)", "type": "method", "name": "isDate", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a Date. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isError(object)", "type": "method", "name": "isError", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is an [Error][]. Otherwise, returns\nfalse.\n\n

\n
const util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
\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\n

\n
// This example requires the `--harmony-tostring` flag\nconst util = require('util');\nconst obj = { name: 'Error', message: 'an error occurred' };\n\nutil.isError(obj);\n  // false\nobj[Symbol.toStringTag] = 'Error';\nutil.isError(obj);\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isFunction(object)", "type": "method", "name": "isFunction", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a Function. Otherwise, returns\nfalse.\n\n

\n
const util = require('util');\n\nfunction Foo() {}\nvar Bar = function() {};\n\nutil.isFunction({})\n  // false\nutil.isFunction(Foo)\n  // true\nutil.isFunction(Bar)\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isNull(object)", "type": "method", "name": "isNull", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is strictly null. Otherwise, returns\nfalse.\n\n

\n
const util = require('util');\n\nutil.isNull(0)\n  // false\nutil.isNull(undefined)\n  // false\nutil.isNull(null)\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isNullOrUndefined(object)", "type": "method", "name": "isNullOrUndefined", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is null or undefined. Otherwise,\nreturns false.\n\n

\n
const util = require('util');\n\nutil.isNullOrUndefined(0)\n  // false\nutil.isNullOrUndefined(undefined)\n  // true\nutil.isNullOrUndefined(null)\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isNumber(object)", "type": "method", "name": "isNumber", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a Number. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isNumber(false)\n  // false\nutil.isNumber(Infinity)\n  // true\nutil.isNumber(0)\n  // true\nutil.isNumber(NaN)\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isObject(object)", "type": "method", "name": "isObject", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is strictly an Object and not a\nFunction. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isObject(5)\n  // false\nutil.isObject(null)\n  // false\nutil.isObject({})\n  // true\nutil.isObject(function(){})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isPrimitive(object)", "type": "method", "name": "isPrimitive", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a primitive type. Otherwise, returns\nfalse.\n\n

\n
const util = require('util');\n\nutil.isPrimitive(5)\n  // true\nutil.isPrimitive('foo')\n  // true\nutil.isPrimitive(false)\n  // true\nutil.isPrimitive(null)\n  // true\nutil.isPrimitive(undefined)\n  // true\nutil.isPrimitive({})\n  // false\nutil.isPrimitive(function() {})\n  // false\nutil.isPrimitive(/^$/)\n  // false\nutil.isPrimitive(new Date())\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isRegExp(object)", "type": "method", "name": "isRegExp", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a RegExp. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isString(object)", "type": "method", "name": "isString", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a String. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isString('')\n  // true\nutil.isString('foo')\n  // true\nutil.isString(String('foo'))\n  // true\nutil.isString(5)\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isSymbol(object)", "type": "method", "name": "isSymbol", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is a Symbol. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nutil.isSymbol(5)\n  // false\nutil.isSymbol('foo')\n  // false\nutil.isSymbol(Symbol('foo'))\n  // true
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isUndefined(object)", "type": "method", "name": "isUndefined", "stability": 0, "stabilityText": "Deprecated", "desc": "

Returns true if the given "object" is undefined. Otherwise, returns false.\n\n

\n
const util = require('util');\n\nvar foo;\nutil.isUndefined(5)\n  // false\nutil.isUndefined(foo)\n  // true\nutil.isUndefined(null)\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.log(string)", "type": "method", "name": "log", "desc": "

Output with timestamp on stdout.\n\n

\n
require('util').log('Timestamped message.');
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.print([...])", "type": "method", "name": "print", "stability": 0, "stabilityText": "Deprecated: Use [`console.log()`][] instead.", "desc": "

Deprecated predecessor of console.log.\n\n

\n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.pump(readableStream, writableStream[, callback])", "type": "method", "name": "pump", "stability": 0, "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", "desc": "

Deprecated predecessor of stream.pipe().\n\n

\n", "signatures": [ { "params": [ { "name": "readableStream" }, { "name": "writableStream" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "util.puts([...])", "type": "method", "name": "puts", "stability": 0, "stabilityText": "Deprecated: Use [`console.log()`][] instead.", "desc": "

Deprecated predecessor of console.log.\n\n

\n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] } ], "type": "module", "displayName": "util" }, { "textRaw": "V8", "name": "v8", "stability": 2, "stabilityText": "Stable", "desc": "

This module exposes events and interfaces specific to the version of [V8][]\nbuilt with Node.js. These interfaces are subject to change by upstream and are\ntherefore not covered under the stability index.\n\n

\n", "methods": [ { "textRaw": "getHeapStatistics()", "type": "method", "name": "getHeapStatistics", "desc": "

Returns an object with the following properties\n\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", "signatures": [ { "params": [] } ] }, { "textRaw": "getHeapSpaceStatistics()", "type": "method", "name": "getHeapSpaceStatistics", "desc": "

Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Order of heap spaces nor availability of a heap space can be\nguaranteed as the statistics are provided via the V8 GetHeapSpaceStatistics\nfunction.\n\n

\n

Example result:\n\n

\n
[\n  {\n    "space_name": "new_space",\n    "space_size": 2063872,\n    "space_used_size": 951112,\n    "space_available_size": 80824,\n    "physical_space_size": 2063872\n  },\n  {\n    "space_name": "old_space",\n    "space_size": 3090560,\n    "space_used_size": 2493792,\n    "space_available_size": 0,\n    "physical_space_size": 3090560\n  },\n  {\n    "space_name": "code_space",\n    "space_size": 1260160,\n    "space_used_size": 644256,\n    "space_available_size": 960,\n    "physical_space_size": 1260160\n  },\n  {\n    "space_name": "map_space",\n    "space_size": 1094160,\n    "space_used_size": 201608,\n    "space_available_size": 0,\n    "physical_space_size": 1094160\n  },\n  {\n    "space_name": "large_object_space",\n    "space_size": 0,\n    "space_used_size": 0,\n    "space_available_size": 1490980608,\n    "physical_space_size": 0\n  }\n]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "setFlagsFromString(string)", "type": "method", "name": "setFlagsFromString", "desc": "

Set additional V8 command line flags. Use 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\n

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

\n

Usage:\n\n

\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", "signatures": [ { "params": [ { "name": "string" } ] } ] } ], "type": "module", "displayName": "V8" }, { "textRaw": "Executing JavaScript", "name": "vm", "stability": 2, "stabilityText": "Stable", "desc": "

You can access this module with:\n\n

\n
const vm = require('vm');
\n

JavaScript code can be compiled and run immediately or compiled, saved, and run\nlater.\n\n

\n", "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "desc": "

A class for holding precompiled scripts, and running them in specific sandboxes.\n\n

\n", "methods": [ { "textRaw": "new vm.Script(code, options)", "type": "method", "name": "Script", "desc": "

Creating a new Script compiles code but does not run it. Instead, the\ncreated vm.Script object represents this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run.\n\n

\n

The options when creating a script are:\n\n

\n\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "options" } ] } ] }, { "textRaw": "script.runInContext(contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "desc": "

Similar to [vm.runInContext()][] but a method of a precompiled Script\nobject. script.runInContext() runs script's compiled code in\ncontextifiedSandbox and returns the result. Running code does not have access\nto local scope.\n\n

\n

script.runInContext() takes the same options as\n[script.runInThisContext()][].\n\n

\n

Example: compile code that increments a global variable and sets one, then\nexecute the code multiple times. These globals are contained in the sandbox.\n\n

\n
const util = require('util');\nconst vm = require('vm');\n\nvar sandbox = {\n  animal: 'cat',\n  count: 2\n};\n\nvar context = new vm.createContext(sandbox);\nvar script = new vm.Script('count += 1; name = "kitty"');\n\nfor (var 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

Note that running untrusted code is a tricky business requiring great care.\nscript.runInContext() is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n", "signatures": [ { "params": [ { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "script.runInNewContext([sandbox][, options])", "type": "method", "name": "runInNewContext", "desc": "

Similar to [vm.runInNewContext()][] but a method of a precompiled Script\nobject. script.runInNewContext() contextifies sandbox if passed or creates a\nnew contextified sandbox if it's omitted, and then runs script's compiled code\nwith the sandbox as the global object and returns the result. Running code does\nnot have access to local scope.\n\n

\n

script.runInNewContext() takes the same options as\n[script.runInThisContext()][].\n\n

\n

Example: compile code that sets a global variable, then execute the code\nmultiple times in different contexts. These globals are set on and contained in\nthe sandboxes.\n\n

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandboxes = [{}, {}, {}];\n\nconst script = new vm.Script('globalVar = "set"');\n\nsandboxes.forEach((sandbox) => {\n  script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
\n

Note that running untrusted code is a tricky business requiring great care.\nscript.runInNewContext() is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n", "signatures": [ { "params": [ { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "script.runInThisContext([options])", "type": "method", "name": "runInThisContext", "desc": "

Similar to vm.runInThisContext() but a method of a precompiled Script\nobject. script.runInThisContext() runs script's compiled code and returns\nthe result. Running code does not have access to local scope, but does have\naccess to the current global object.\n\n

\n

Example of using script.runInThisContext() to compile code once and run it\nmultiple times:\n\n

\n
const vm = require('vm');\n\nglobal.globalVar = 0;\n\nconst script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });\n\nfor (var i = 0; i < 1000; ++i) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
\n

The options for running a script are:\n\n

\n\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ] } ], "methods": [ { "textRaw": "vm.createContext([sandbox])", "type": "method", "name": "createContext", "desc": "

If given a sandbox object, will "contextify" that sandbox so that it can be\nused in calls to [vm.runInContext()][] or [script.runInContext()][]. Inside\nscripts run as such, sandbox will be the global object, retaining all its\nexisting properties but also having the built-in objects and functions any\nstandard [global object][] has. Outside of scripts run by the vm module,\nsandbox will be unchanged.\n\n

\n

If not given a sandbox object, returns a new, empty contextified sandbox object\nyou can use.\n\n

\n

This function is useful for creating a sandbox that can be used to run multiple\nscripts, e.g. if you were emulating a web browser it could be used to create a\nsingle sandbox representing a window's global object, then run all <script>\ntags together inside that sandbox.\n\n

\n", "signatures": [ { "params": [ { "name": "sandbox", "optional": true } ] } ] }, { "textRaw": "vm.isContext(sandbox)", "type": "method", "name": "isContext", "desc": "

Returns whether or not a sandbox object has been contextified by calling\n[vm.createContext()][] on it.\n\n

\n", "signatures": [ { "params": [ { "name": "sandbox" } ] } ] }, { "textRaw": "vm.runInContext(code, contextifiedSandbox[, options])", "type": "method", "name": "runInContext", "desc": "

vm.runInContext() compiles code, then runs it in contextifiedSandbox and\nreturns the result. Running code does not have access to local scope. The\ncontextifiedSandbox object must have been previously contextified via\n[vm.createContext()][]; it will be used as the global object for code.\n\n

\n

vm.runInContext() takes the same options as [vm.runInThisContext()][].\n\n

\n

Example: compile and execute different scripts in a single existing context.\n\n

\n
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nfor (var i = 0; i < 10; ++i) {\n    vm.runInContext('globalVar *= 2;', sandbox);\n}\nconsole.log(util.inspect(sandbox));\n\n// { globalVar: 1024 }
\n

Note that running untrusted code is a tricky business requiring great care.\nvm.runInContext() is quite useful, but safely running untrusted code requires\na separate process.\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "contextifiedSandbox" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "vm.runInDebugContext(code)", "type": "method", "name": "runInDebugContext", "desc": "

vm.runInDebugContext() compiles and executes code inside the V8 debug\ncontext. The primary use case is to get access to the V8 debug object:\n\n

\n
const Debug = vm.runInDebugContext('Debug');\nDebug.scripts().forEach(function(script) { console.log(script.name); });
\n

Note that the debug context and object are intrinsically tied to V8's debugger\nimplementation and may change (or even get removed) without prior warning.\n\n

\n

The debug object can also be exposed with the --expose_debug_as= switch.\n\n

\n", "signatures": [ { "params": [ { "name": "code" } ] } ] }, { "textRaw": "vm.runInNewContext(code[, sandbox][, options])", "type": "method", "name": "runInNewContext", "desc": "

vm.runInNewContext() compiles code, contextifies sandbox if passed or\ncreates a new contextified sandbox if it's omitted, and then runs the code with\nthe sandbox as the global object and returns the result.\n\n

\n

vm.runInNewContext() takes the same options as [vm.runInThisContext()][].\n\n

\n

Example: compile and execute code that increments a global variable and sets a\nnew one. These globals are contained in the sandbox.\n\n

\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

Note that running untrusted code is a tricky business requiring great care.\nvm.runInNewContext() is quite useful, but safely running untrusted code requires\na separate process.\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "vm.runInThisContext(code[, options])", "type": "method", "name": "runInThisContext", "desc": "

vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope, but does have access to the current\nglobal object.\n\n

\n

Example of using vm.runInThisContext() and [eval()][] to run the same code:\n\n

\n
const vm = require('vm');\nvar 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

vm.runInThisContext() does not have access to the local scope, so localVar\nis unchanged. [eval()][] does have access to the local scope, so localVar is\nchanged.\n\n

\n

In this way vm.runInThisContext() is much like an [indirect eval() call][],\ne.g. (0,eval)('code'). However, it also has the following additional options:\n\n

\n\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "vm" }, { "textRaw": "Zlib", "name": "zlib", "stability": 2, "stabilityText": "Stable", "desc": "

You can access this module with:\n\n

\n
const zlib = require('zlib');
\n

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

\n

Examples

\n

Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

\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

Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

\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 = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, (err, buffer) => {\n  if (!err) {\n    console.log(buffer.toString());\n  } else {\n    // handle error\n  }\n});
\n

To use this module in an HTTP client or server, use the [accept-encoding][]\non requests, and the [content-encoding][] header on responses.\n\n

\n

Note: these examples are drastically simplified to show\nthe basic concept. 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\n

\n
// client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', (response) => {\n  var output = fs.createWriteStream('izs.me_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  var raw = fs.createReadStream('index.html');\n  var 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", "miscs": [ { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

From zlib/zconf.h, modified to node.js's usage:\n\n

\n

The memory requirements for deflate are (in bytes):\n\n

\n
(1 << (windowBits+2)) +  (1 << (memLevel+9))
\n

that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

\n

For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

\n
{ windowBits: 14, memLevel: 7 }
\n

Of course this will generally degrade compression (there's no free lunch).\n\n

\n

The memory requirements for inflate are (in bytes)\n\n

\n
1 << windowBits
\n

that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

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

\n

In general, greater memory usage options will mean that node.js has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

\n" }, { "textRaw": "Constants", "name": "Constants", "type": "misc", "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the\n[zlib documentation][]. See http://zlib.net/manual.html#Constants for more\ndetails.\n\n

\n

Allowed flush values.\n\n

\n\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

\n\n

Compression levels.\n\n

\n\n

Compression strategy.\n\n

\n\n

Possible values of the data_type field.\n\n

\n\n

The deflate compression method (the only one supported in this version).\n\n

\n\n

For initializing zalloc, zfree, opaque.\n\n

\n\n" }, { "textRaw": "Class Options", "name": "Class Options", "type": "misc", "desc": "

Each class takes an options object. All options are optional.\n\n

\n

Note that some options are only relevant when compressing, and are\nignored by the decompression classes.\n\n

\n\n

See the description of deflateInit2 and inflateInit2 at\n

\n

http://zlib.net/manual.html#Advanced for more information on these.\n\n

\n" }, { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

All of these take a [Buffer][] or string as the first argument, an optional second\nargument to supply options to the zlib classes and will call the supplied\ncallback with callback(error, result).\n\n

\n

Every method has a *Sync counterpart, which accept the same arguments, but\nwithout a callback.\n\n

\n", "methods": [ { "textRaw": "zlib.deflate(buf[, options], callback)", "type": "method", "name": "deflate", "desc": "

Compress a Buffer or string with Deflate.\n\n

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

Compress a Buffer or string with Deflate.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflateRaw(buf[, options], callback)", "type": "method", "name": "deflateRaw", "desc": "

Compress a Buffer or string with DeflateRaw.\n\n

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

Compress a Buffer or string with DeflateRaw.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gunzip(buf[, options], callback)", "type": "method", "name": "gunzip", "desc": "

Decompress a Buffer or string with Gunzip.\n\n

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

Decompress a Buffer or string with Gunzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gzip(buf[, options], callback)", "type": "method", "name": "gzip", "desc": "

Compress a Buffer or string with Gzip.\n\n

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

Compress a Buffer or string with Gzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflate(buf[, options], callback)", "type": "method", "name": "inflate", "desc": "

Decompress a Buffer or string with Inflate.\n\n

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

Decompress a Buffer or string with Inflate.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflateRaw(buf[, options], callback)", "type": "method", "name": "inflateRaw", "desc": "

Decompress a Buffer or string with InflateRaw.\n\n

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

Decompress a Buffer or string with InflateRaw.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.unzip(buf[, options], callback)", "type": "method", "name": "unzip", "desc": "

Decompress a Buffer or string with Unzip.\n\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", "desc": "

Decompress a Buffer or string with Unzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] } ] } ], "classes": [ { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "desc": "

Compress data using deflate.\n\n

\n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "desc": "

Compress data using deflate, and do not append a zlib header.\n\n

\n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "desc": "

Decompress a gzip stream.\n\n

\n" }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "desc": "

Compress data using gzip.\n\n

\n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "desc": "

Decompress a deflate stream.\n\n

\n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "desc": "

Decompress a raw deflate stream.\n\n

\n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

\n" }, { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "desc": "

Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.\n\n

\n", "methods": [ { "textRaw": "zlib.flush([kind], callback)", "type": "method", "name": "flush", "desc": "

kind defaults to zlib.Z_FULL_FLUSH.\n\n

\n

Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.\n\n

\n", "signatures": [ { "params": [ { "name": "kind", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.params(level, strategy, callback)", "type": "method", "name": "params", "desc": "

Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.\n\n

\n", "signatures": [ { "params": [ { "name": "level" }, { "name": "strategy" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "desc": "

Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "methods": [ { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "desc": "

Returns a new [Deflate][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "desc": "

Returns a new [DeflateRaw][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "desc": "

Returns a new [Gunzip][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "desc": "

Returns a new [Gzip][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "desc": "

Returns a new [Inflate][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "desc": "

Returns a new [InflateRaw][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "desc": "

Returns a new [Unzip][] object with an [options][].\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "Zlib" } ], "stability": 2, "stabilityText": "Stable", "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\n

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

\n", "methods": [ { "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])", "type": "method", "name": "captureStackTrace", "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\n

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack  // similar to `new Error().stack`
\n

The first line of the trace, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().\n\n

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

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:\n\n

\n
function MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would should up in the .stack property. by passing\n// the constructor, we omit that frame and all frames above it.\nnew MyError().stack
\n", "signatures": [ { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ] } ], "properties": [ { "textRaw": "Error.stackTraceLimit", "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\n

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

\n

If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.\n\n

\n", "properties": [ { "textRaw": "error.message", "name": "message", "desc": "

Returns the string description of 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\n

\n
const err = new Error('The message');\nconsole.log(err.message);\n  // Prints: The message
\n" }, { "textRaw": "error.stack", "name": "stack", "desc": "

Returns a string describing the point in the code at which the Error was\ninstantiated.\n\n

\n

For example:\n\n

\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

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

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

\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

The location information will be one of:\n\n

\n\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.\n\n

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

\n

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

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

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

\n

For example:\n\n

\n
require('net').connect(-1);\n  // throws RangeError, port should be > 0 && < 65536
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.\n\n

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

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.\n\n

\n
doesNotExist;\n  // throws ReferenceError, doesNotExist is not a variable in this program.
\n

ReferenceError instances will have an error.arguments property whose value\nis an array containing a single element: a string representing the variable\nthat was not defined.\n\n

\n
const assert = require('assert');\ntry {\n  doesNotExist;\n} catch(err) {\n  assert(err.arguments[0], 'doesNotExist');\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\n

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

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n  // err will be a SyntaxError\n}
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.\n\n

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

\n
require('url').parse(function() { });\n  // throws TypeError, since it expected a string
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.\n\n

\n" } ], "globals": [ { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "desc": "

Used to handle binary data. See the [buffer section][].\n\n

\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "desc": "

[clearImmediate] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "clearInterval(intervalObject)", "type": "global", "name": "clearInterval", "desc": "

[clearInterval] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "clearTimeout(timeoutObject)", "type": "global", "name": "clearTimeout", "desc": "

[clearTimeout] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "console", "name": "console", "type": "global", "desc": "

Used to print to stdout and stderr. See the [console][] section.\n\n

\n" }, { "textRaw": "global", "name": "global", "type": "global", "desc": "

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

\n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

The process object. See the [process object][] section.\n\n

\n" }, { "textRaw": "setImmediate(callback[, arg][, ...])", "type": "global", "name": "setImmediate", "desc": "

[setImmediate] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "setInterval(callback, delay[, arg][, ...])", "type": "global", "name": "setInterval", "desc": "

[setInterval] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "setTimeout(callback, delay[, arg][, ...])", "type": "global", "name": "setTimeout", "desc": "

[setTimeout] is described in the [timers][] section.\n\n

\n" }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

The process object is a global object and can be accessed from anywhere.\nIt is an instance of [EventEmitter][].\n\n

\n", "events": [ { "textRaw": "Event: 'beforeExit'", "type": "event", "name": "beforeExit", "desc": "

This event is emitted when Node.js empties its event loop and has nothing else \nto schedule. Normally, Node.js exits when there is no work scheduled, but a \nlistener for 'beforeExit' can make asynchronous calls, and cause Node.js to \ncontinue.\n\n

\n

'beforeExit' is not emitted for conditions causing explicit termination, such \nas [process.exit()][] or uncaught exceptions, and should not be used as an\nalternative to the 'exit' event unless the intention is to schedule more work.\n\n

\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "desc": "

Emitted when the process is about to exit. There is no way to prevent the\nexiting of the event loop at this point, and once all 'exit' listeners have\nfinished running the process will exit. Therefore you must only perform\nsynchronous operations in this handler. This is a good hook to perform\nchecks on the module's state (like for unit tests). The callback takes one\nargument, the code the process is exiting with.\n\n

\n

This event is only emitted when Node.js exits explicitly by process.exit() or\nimplicitly by the event loop draining.\n\n

\n

Example of listening for 'exit':\n\n

\n
process.on('exit', (code) => {\n  // do *NOT* do this\n  setTimeout(() => {\n    console.log('This will not run');\n  }, 0);\n  console.log('About to exit with code:', code);\n});
\n", "params": [] }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

Messages sent by [ChildProcess.send()][] are obtained using the 'message'\nevent on the child's process object.\n\n

\n" }, { "textRaw": "Event: 'rejectionHandled'", "type": "event", "name": "rejectionHandled", "desc": "

Emitted whenever a Promise was rejected and an error handler was attached to it\n(for example with .catch()) later than after an event loop turn. This event\nis emitted with the following arguments:\n\n

\n\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 rejection\ncan be handled at a future point in time — possibly much later than the\nevent loop turn it takes for the 'unhandledRejection' event to be emitted.\n\n

\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 is a\ngrowing-and-shrinking list of unhandled rejections. In synchronous code, the\n'uncaughtException' event tells you when the list of unhandled exceptions\ngrows. And in asynchronous code, the 'unhandledRejection' event tells you\nwhen the list of unhandled rejections grows, while the 'rejectionHandled'\nevent tells you when the list of unhandled rejections shrinks.\n\n

\n

For example using the rejection detection hooks in order to keep a map of all\nthe rejected promise reasons at a given time:\n\n

\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

This map will grow and shrink over time, reflecting rejections that start\nunhandled and then become handled. You could record the errors in some error\nlog, either periodically (probably best for long-running programs, allowing\nyou to clear the map, which in the case of a very buggy program could grow\nindefinitely) or upon process exit (more convenient for scripts).\n\n

\n", "params": [] }, { "textRaw": "Event: 'uncaughtException'", "type": "event", "name": "uncaughtException", "desc": "

The 'uncaughtException' event is emitted when an exception bubbles all the\nway back to the event loop. By default, Node.js handles such exceptions by \nprinting the stack trace to stderr and exiting. Adding a handler for the\n'uncaughtException' event overrides this default behavior.\n\n

\n

For example:\n\n

\n
process.on('uncaughtException', (err) => {\n  console.log(`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", "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\n

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

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

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

\n", "type": "module", "displayName": "Warning: Using `'uncaughtException'` correctly" } ], "params": [] }, { "textRaw": "Event: 'unhandledRejection'", "type": "event", "name": "unhandledRejection", "desc": "

Emitted whenever a Promise is rejected and no error handler is attached to\nthe promise within a turn of the event loop. When programming with promises\nexceptions are encapsulated as rejected promises. Such promises can be caught\nand handled using [promise.catch(...)][] and rejections are propagated through\na promise chain. This event is useful for detecting and keeping track of\npromises that were rejected whose rejections were not handled yet. This event\nis emitted with the following arguments:\n\n

\n\n

Here is an example that logs every unhandled rejection to the console\n\n

\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

For example, here is a rejection that will trigger the 'unhandledRejection'\nevent:\n\n

\n
somePromise.then((res) => {\n  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch` or `.then`
\n

Here is an example of a coding pattern that will also trigger\n'unhandledRejection':\n\n

\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\nvar resource = new SomeResource();\n// no .catch or .then on resource.loaded for at least a turn
\n

In cases like this, you may not want to track the rejection as a developer\nerror like you would for other 'unhandledRejection' events. To address\nthis, you can either attach a dummy .catch(() => { }) handler to\nresource.loaded, preventing the 'unhandledRejection' event from being\nemitted, or you can use the ['rejectionHandled'][] event.\n\n

\n", "params": [] }, { "textRaw": "Signal Events", "name": "SIGINT, SIGHUP, etc.", "type": "event", "desc": "

Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGHUP, etc.\n\n

\n

Example of listening for SIGINT:\n\n

\n
// Start reading from stdin so we don't exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n  console.log('Got SIGINT.  Press Control-D to exit.');\n});
\n

An easy way to send the SIGINT signal is with Control-C in most terminal\nprograms.\n\n

\n

Note:\n\n

\n\n

Note that Windows does not support sending Signals, but Node.js offers some\nemulation with process.kill(), and child_process.kill(). Sending signal 0\ncan be used to test for the existence of a process. Sending SIGINT,\nSIGTERM, and SIGKILL cause the unconditional termination of the target\nprocess.\n\n

\n", "params": [] } ], "modules": [ { "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", "desc": "

This causes Node.js to emit an abort. This will cause Node.js to exit and\ngenerate a core file.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.chdir(directory)", "type": "method", "name": "chdir", "desc": "

Changes the current working directory of the process or throws an exception if that fails.\n\n

\n
console.log(`Starting directory: ${process.cwd()}`);\ntry {\n  process.chdir('/tmp');\n  console.log(`New directory: ${process.cwd()}`);\n}\ncatch (err) {\n  console.log(`chdir: ${err}`);\n}
\n", "signatures": [ { "params": [ { "name": "directory" } ] } ] }, { "textRaw": "process.cwd()", "type": "method", "name": "cwd", "desc": "

Returns the current working directory of the process.\n\n

\n
console.log(`Current directory: ${process.cwd()}`);
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.disconnect()", "type": "method", "name": "disconnect", "desc": "

Close the IPC channel to the parent process, allowing this child to exit\ngracefully once there are no other connections keeping it alive.\n\n

\n

Identical to the parent process's [ChildProcess.disconnect()][].\n\n

\n

If Node.js was not spawned with an IPC channel, process.disconnect() will be\nundefined.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

Ends the process with the specified code. If omitted, exit uses the\n'success' code 0.\n\n

\n

To exit with a 'failure' code:\n\n

\n
process.exit(1);
\n

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

\n", "signatures": [ { "params": [ { "name": "code", "optional": true } ] } ] }, { "textRaw": "process.getegid()", "type": "method", "name": "getegid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the effective group identity of the process. (See getegid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getegid) {\n  console.log(`Current gid: ${process.getegid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the effective user identity of the process. (See geteuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.geteuid) {\n  console.log(`Current uid: ${process.geteuid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n

\n
if (process.getgid) {\n  console.log(`Current gid: ${process.getgid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Returns an array with the supplementary group IDs. POSIX leaves it unspecified\nif the effective group ID is included but Node.js ensures it always is.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n

\n
if (process.getuid) {\n  console.log(`Current uid: ${process.getuid()}`);\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.hrtime()", "type": "method", "name": "hrtime", "desc": "

Returns the current high-resolution real time in a [seconds, nanoseconds]\ntuple Array. It is relative to an arbitrary time in the past. It is not\nrelated to the time of day and therefore not subject to clock drift. The\nprimary use is for measuring performance between intervals.\n\n

\n

You may pass in the result of a previous call to process.hrtime() to get\na diff reading, useful for benchmarks and measuring intervals:\n\n

\n
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n  var diff = process.hrtime(time);\n  // [ 1, 552 ]\n\n  console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);\n  // benchmark took 1000000527 nanoseconds\n}, 1000);
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.initgroups(user, extra_group)", "type": "method", "name": "initgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Reads /etc/group and initializes the group access list, using all groups of\nwhich the user is a member. This is a privileged operation, meaning you need\nto be root or have the CAP_SETGID capability.\n\n

\n

user is a user name or user ID. extra_group is a group name or group ID.\n\n

\n

Some care needs to be taken when dropping privileges. Example:\n\n

\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", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "desc": "

Send a signal to a process. pid is the process id and signal is the\nstring describing the signal to send. Signal names are strings like\nSIGINT or SIGHUP. If omitted, the signal will be SIGTERM.\nSee [Signal Events][] and kill(2) for more information.\n\n

\n

Will throw an error if target does not exist, and as a special case, a signal\nof 0 can be used to test for the existence of a process. Windows platforms\nwill throw an error if the pid is used to kill a process group.\n\n

\n

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

\n

Example of sending a signal to yourself:\n\n

\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

Note: When SIGUSR1 is received by Node.js it starts the debugger, see\n[Signal Events][].\n\n

\n", "signatures": [ { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ] }, { "textRaw": "process.memoryUsage()", "type": "method", "name": "memoryUsage", "desc": "

Returns an object describing the memory usage of the Node.js process\nmeasured in bytes.\n\n

\n
const util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\n

This will generate:\n\n

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

heapTotal and heapUsed refer to V8's memory usage.\n\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.nextTick(callback[, arg][, ...])", "type": "method", "name": "nextTick", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ], "desc": "

Once the current event loop turn runs to completion, call the callback\nfunction.\n\n

\n

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

\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

This is important in developing APIs where you want to give the user the\nchance to assign event handlers after an object has been constructed,\nbut before any I/O has occurred.\n\n

\n
function MyThing(options) {\n  this.setupOptions(options);\n\n  process.nextTick(() => {\n    this.startDoingStuff();\n  });\n}\n\nvar thing = new MyThing();\nthing.getReadyForStuff();\n\n// thing.startDoingStuff() gets called now, not before.
\n

It is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:\n\n

\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

This API is hazardous. If you do this:\n\n

\n
maybeSync(true, () => {\n  foo();\n});\nbar();
\n

then it's not clear whether foo() or bar() will be called first.\n\n

\n

This approach is much better:\n\n

\n
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n

Note: the nextTick 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\n

\n" }, { "textRaw": "process.send(message[, sendHandle[, options]][, callback])", "type": "method", "name": "send", "signatures": [ { "return": { "textRaw": "Return: {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object" }, { "textRaw": "`options` {Object} ", "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle" }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

When Node.js is spawned with an IPC channel attached, it can send messages to its\nparent process using process.send(). Each will be received as a\n['message'][] event on the parent's ChildProcess object.\n\n

\n

Note: this function uses [JSON.stringify()][] internally to serialize the message.\n\n

\n

If Node.js was not spawned with an IPC channel, process.send() will be undefined.\n\n

\n" }, { "textRaw": "process.setegid(id)", "type": "method", "name": "setegid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the effective group identity of the process. (See setegid(2).)\nThis accepts either a numerical ID or a groupname string. If a groupname\nis specified, this method blocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the effective user identity of the process. (See seteuid(2).)\nThis accepts either a numerical ID or a username string. If a username\nis specified, this method blocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the group identity of the process. (See setgid(2).) This accepts either\na numerical ID or a groupname string. If a groupname is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set gid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the supplementary group IDs. This is a privileged operation, meaning you\nneed to be root or have the CAP_SETGID capability.\n\n

\n

The list can contain group IDs, group names or both.\n\n

\n", "signatures": [ { "params": [ { "name": "groups" } ] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

Note: this function is only available on POSIX platforms (i.e. not Windows,\nAndroid)\n\n

\n

Sets the user identity of the process. (See setuid(2).) This accepts either\na numerical ID or a username string. If a username is specified, this method\nblocks while resolving it to a numerical ID.\n\n

\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  }\n  catch (err) {\n    console.log(`Failed to set uid: ${err}`);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

Sets or reads the process's file mode creation mask. Child processes inherit\nthe mask from the parent process. Returns the old mask if mask argument is\ngiven, otherwise returns the current mask.\n\n

\n
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);
\n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

Number of seconds Node.js has been running.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "process.arch", "name": "arch", "desc": "

What processor architecture you're running on: 'arm', 'ia32', or 'x64'.\n\n

\n
console.log('This processor architecture is ' + process.arch);
\n" }, { "textRaw": "process.argv", "name": "argv", "desc": "

An array containing the command line arguments. The first element will be\n'node', the second element will be the name of the JavaScript file. The\nnext elements will be any additional command line arguments.\n\n

\n
// print process.argv\nprocess.argv.forEach((val, index, array) => {\n  console.log(`${index}: ${val}`);\n});
\n

This will generate:\n\n

\n
$ node process-2.js one two=three four\n0: node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four
\n" }, { "textRaw": "process.config", "name": "config", "desc": "

An Object containing the JavaScript representation of the configure options\nthat were used to compile the current Node.js executable. This is the same as\nthe config.gypi file that was produced when running the ./configure script.\n\n

\n

An example of the possible output looks like:\n\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" }, { "textRaw": "`connected` {Boolean} Set to false after `process.disconnect()` is called ", "type": "Boolean", "name": "connected", "desc": "

If process.connected is false, it is no longer possible to send messages.\n\n

\n", "shortDesc": "Set to false after `process.disconnect()` is called" }, { "textRaw": "process.env", "name": "env", "desc": "

An object containing the user environment. See environ(7).\n\n

\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

You can write to this object, but changes won't be reflected outside of your\nprocess. That means that the following won't work:\n\n

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

But this will:\n\n

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

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

\n

Example:\n\n

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

Use delete to delete a property from process.env.\n\n

\n

Example:\n\n

\n
process.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined
\n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

This is the set of Node.js-specific command line options from the\nexecutable that started the process. These options do not show up in\nprocess.argv, and do not include the Node.js executable, the name of\nthe script, or any options following the script name. These options\nare useful in order to spawn child processes with the same execution\nenvironment as the parent.\n\n

\n

Example:\n\n

\n
$ node --harmony script.js --version
\n

results in process.execArgv:\n\n

\n
['--harmony']
\n

and process.argv:\n\n

\n
['/usr/local/bin/node', 'script.js', '--version']
\n" }, { "textRaw": "process.execPath", "name": "execPath", "desc": "

This is the absolute pathname of the executable that started the process.\n\n

\n

Example:\n\n

\n
/usr/local/bin/node
\n" }, { "textRaw": "process.exitCode", "name": "exitCode", "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\n

\n

Specifying a code to process.exit(code) will override any previous\nsetting of process.exitCode.\n\n\n

\n" }, { "textRaw": "process.mainModule", "name": "mainModule", "desc": "

Alternate way to retrieve [require.main][]. The difference is that if the main\nmodule changes at runtime, require.main might still refer to the original main\nmodule in modules that were required before the change occurred. Generally it's\nsafe to assume that the two refer to the same module.\n\n

\n

As with require.main, it will be undefined if there was no entry script.\n\n

\n" }, { "textRaw": "process.pid", "name": "pid", "desc": "

The PID of the process.\n\n

\n
console.log(`This process is pid ${process.pid}`);
\n" }, { "textRaw": "process.platform", "name": "platform", "desc": "

What platform you're running on:\n'darwin', 'freebsd', 'linux', 'sunos' or 'win32'\n\n

\n
console.log(`This platform is ${process.platform}`);
\n" }, { "textRaw": "process.release", "name": "release", "desc": "

An Object containing metadata related to the current release, including URLs\nfor the source tarball and headers-only tarball.\n\n

\n

process.release contains the following properties:\n\n

\n\n

e.g.\n\n

\n
{ name: 'node',\n  sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz',\n  headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz',\n  libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }
\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\n

\n" }, { "textRaw": "process.stderr", "name": "stderr", "desc": "

A writable stream to stderr (on fd 2).\n\n

\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed (end() will throw), they never emit the finish\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)\n\n

\n" }, { "textRaw": "process.stdin", "name": "stdin", "desc": "

A Readable Stream for stdin (on fd 0).\n\n

\n

Example of opening standard input and listening for both events:\n\n

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', () => {\n  var 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

As a Stream, process.stdin can also be used in "old" mode that is compatible\nwith scripts written for node.js prior to v0.10.\nFor more information see [Stream compatibility][].\n\n

\n

In "old" Streams mode the stdin stream is paused by default, so one\nmust call process.stdin.resume() to read from it. Note also that calling\nprocess.stdin.resume() itself would switch stream to "old" mode.\n\n

\n

If you are starting a new project you should prefer a more recent "new" Streams\nmode over "old" one.\n\n

\n" }, { "textRaw": "process.stdout", "name": "stdout", "desc": "

A Writable Stream to stdout (on fd 1).\n\n

\n

For example, a console.log equivalent could look like this:\n\n

\n
console.log = (msg) => {\n  process.stdout.write(`${msg}\\n`);\n};
\n

process.stderr and process.stdout are unlike other streams in Node.js in\nthat they cannot be closed (end() will throw), they never emit the 'finish'\nevent and that writes can block when output is redirected to a file (although\ndisks are fast and operating systems normally employ write-back caching so it\nshould be a very rare occurrence indeed.)\n\n

\n

To check if Node.js is being run in a TTY context, read the isTTY property\non process.stderr, process.stdout, or process.stdin:\n\n

\n
$ node -p "Boolean(process.stdin.isTTY)"\ntrue\n$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"\nfalse\n\n$ node -p "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p "Boolean(process.stdout.isTTY)" | cat\nfalse
\n

See [the tty docs][] for more information.\n\n

\n" }, { "textRaw": "process.title", "name": "title", "desc": "

Getter/setter to set what is displayed in ps.\n\n

\n

When used as a setter, the maximum length is platform-specific and probably\nshort.\n\n

\n

On Linux and OS X, it's limited to the size of the binary name plus the\nlength of the command line arguments because it overwrites the argv memory.\n\n

\n

v0.8 allowed for longer process title strings by also overwriting the environ\nmemory but that was potentially insecure/confusing in some (rather obscure)\ncases.\n\n

\n" }, { "textRaw": "process.version", "name": "version", "desc": "

A compiled-in property that exposes NODE_VERSION.\n\n

\n
console.log(`Version: ${process.version}`);
\n" }, { "textRaw": "process.versions", "name": "versions", "desc": "

A property exposing version strings of Node.js and its dependencies.\n\n

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

Will print something like:\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" } ] } ], "vars": [ { "textRaw": "\\_\\_dirname", "name": "\\_\\_dirname", "type": "var", "desc": "

The name of the directory that the currently executing script resides in.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__dirname);\n// /Users/mjr
\n

__dirname isn't actually a global but rather local to each module.\n\n

\n

For instance, given two modules: a and b, where b is a dependency of\na and there is a directory structure of:\n\n

\n\n

References to __dirname within b.js will return\n/Users/mjr/app/node_modules/b while references to __dirname within a.js\nwill return /Users/mj/app.\n\n

\n" }, { "textRaw": "\\_\\_filename", "name": "\\_\\_filename", "type": "var", "desc": "

The filename of the code being executed. This is the resolved absolute path\nof this code file. For a main program this is not necessarily the same\nfilename used in the command line. The value inside a module is the path\nto that module file.\n\n

\n

Example: running node example.js from /Users/mjr\n\n

\n
console.log(__filename);\n// /Users/mjr/example.js
\n

__filename isn't actually a global but rather local to each module.\n\n

\n" }, { "textRaw": "exports", "name": "exports", "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\n

\n

exports isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" }, { "textRaw": "module", "name": "module", "type": "var", "desc": "

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

\n

module isn't actually a global but rather local to each module.\n\n

\n

See the [module system documentation][] for more information.\n\n

\n" }, { "textRaw": "require()", "type": "var", "name": "require", "desc": "

To require modules. See the [Modules][] section. require isn't actually a\nglobal but rather local to each module.\n\n

\n", "properties": [ { "textRaw": "`cache` {Object} ", "type": "Object", "name": "cache", "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.\n\n

\n" }, { "textRaw": "`extensions` {Object} ", "type": "Object", "name": "extensions", "stability": 0, "stabilityText": "Deprecated", "desc": "

Instruct require on how to handle certain file extensions.\n\n

\n

Process files with the extension .sjs as .js:\n\n

\n
require.extensions['.sjs'] = require.extensions['.js'];
\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\n

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

\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "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\n

\n", "signatures": [ { "params": [] } ] } ] } ] }